• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static methods - the norm?

 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I've been hacking at Java for some time now. Lately I've been delving more and more into design patterns and coming to a few realizations.

A lot of my classes have never needed to be extended. Some do, especially where factories are used, but it isn't often. Perhaps more of my methods should be STATIC. While searching for this, I came across this in another forum:

To the best of my knowledge, once static data is loaded it cannot be unloaded by the JVM. This makes sense, because otherwise you would be recreating data that is meant to be initialized once across all instances of that class. In many ways a purely static class is like a singleton and you cannot reclaiming the memory. Thus, it would be more expensive long-term for short lived objects.

Most static utility classes I see are only needed in modestly used scenarios, so instantiating a light-weight object is better. Similarly static final variables, which often are just private Strings or numbers, are light enough that you don't gain anything by keeping them in memory for long periods.

Personally, I try to use statics only for data that is heavy to instantiate and needed once, singletons, and factory methods. Sometimes the less you use a trick, the cleaner and more flexible the code!



It is true that STATIC methods complicate refactoring. But if the class is probably not ever going to be subclassed, wouldn't STATIC methods actually make for a more efficient use of memory?

Any guidance if static should be the rule, not the exception?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static vs not static is not really related to whether the class will be extended, but whether you will have more than one instance of the class or at least the data the methods operate on.

If I have a class like:

I'd probably want to use it like:

I can't make the field "color" or the methods static. They have to be able to work on member data.

Does that much make sense?
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Additionally, whether you make a method static or not has in fact no impact at all on memory usage. The byte code of a class is only loaded into memory once, no matter how many objects of it exist - and it is only garbage collected when the classloader is gc'ed, which in the normal case means "never".

Whether to make a method static or not really is a decision that should be based on design criteria such as maintainibility and extensibility. And for that, you will typically prefer instance methods over static methods.
 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. I also found this article to be helpful:

http://www.javaworld.com/javaworld/javaqa/2001-11/03-qa-1121-mrhappy.html
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If a method only performs operations on non-instance field values it can and should be a static field candidate. Think about how many of the math methods are implemented.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
True.

On the other hand, even if your methods do not depend on any instance fields, it may still make sense to use instance methods. That's because using instance methods makes it easier to implement your methods in more ways than one, and to substitute one implementation for another at runtime.

A common example of this is for testability - you may need to replace your standard implementation with some sort of mock object for easy unit testing, where you may not want to perform various actions "for real" (e.g. database access or file access). It's very tempting to write a FileUtils class with a bunch of static helper methods for easy file access - but in the long run it may well be easier to write the same class using instance methods, making it easy to mock out for testing purposes, where you often don't want to access the actual file system. The Spring framework, and more generally the Inversion of Control / Dependency Injection patterns, as well as the whole idea of Java interfaces, depend heavily on the idea of using non-static methods that you can replace with alternate implementations.

As a result, I would recommend using static methods only for things you are really sure you will never ever need more than one implementation of. Or for private methods, or for things where you're really sure it will be easy to change the public/protected/package API later. I.e. the only people using your code are you, or people you can beat into submission. If you plan on anyone using your code other than yourself or people directly under your control (or people whose opinions you don't care about in any way), then using instance methods will give you a lot more flexibility later if anyone perceives the need for an alternate implementation.
[ September 22, 2007: Message edited by: Jim Yingst ]
 
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ahh,... the master at work.

Charlie, Jim's got the whole thing verbalized - correctly - including the true cause of failure having as much to do with people trying to help you as well as it does design decison such as this. I work on massive projects where sanity is just another tool .... a survival tool. Jim's right.

First, if it is always the same, no matter where or when, I consder making it a static final. I throw away more code than I use, but realize:   coming to a few realizations ...   will continue, and continue. Consider your memory before you consider the machine's memory.

If a class has static methods has little to do with whether it is probably not ever going to be subclassed. Wouldn't STATIC methods actually be better named Singletons ? It would make for a more efficient use of your memory. It would be a better desing if Integer, String and Double - also Boolean and others, were not final. They would be an invaluable base class for some work. Fortuantely, BigInteger allowed me to sub-class it when I went to write some security shells ~ my first attempt. I now have the Random int provided by the consructor written by professionals, as well as the random bytes[] I init'd myself in the constructor.

Don't worry about the the machines memory in the day of terabyte drives and gigabyte rams. One floppy is almost beyond comprehension: Typing at a normal typewriter, type for five or ten miles at ten or twelve point typefont. That's one floppy, which folks will smirk with disdain at thinking it is big enough for you to mention, let alone consider. I heard in another post that Java takes sixteen or 32 or 64 bytes or something for a pointer, which they call an instance. Nothing in the face of contemporary machines.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by John Grath:
If a method only performs operations on non-instance field values it can and should be a static field candidate. Think about how many of the math methods are implemented.



java.lang.Math is a very special case - mainly because of the existence of primitives. If numbers were objects, the needs for most of the Math methods would vanish - they could be directly implemented on the numbers, as instance methods.
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ilja Preuss:
java.lang.Math is a very special case - mainly because of the existence of primitives. If numbers were objects, the needs for most of the Math methods would vanish - they could be directly implemented on the numbers, as instance methods.



 
reply
    Bookmark Topic Watch Topic
  • New Topic