views:

590

answers:

13

I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.

A: 

This thread looks relevant: http://stackoverflow.com/questions/169378/c-method-can-be-made-static-but-should-it The difference's between C# and Java won't impact its relevance (I think).

jcollum
+1  A: 

My rule of thumb is: if the method performs anything related to a specific instance of a class, regardless of whether it needs to use class instance variables. If you can consider a situation where you might need to use a certain method without necessarily referring to an instance of the class, then the method should definitely be static (class). If this method also happens to need to make use of instance variables in certain cases, then it is probably best to create a separate instance method that calls the static method and passes the instance variables. Performance-wise I believe there is negligible difference (at least in .NET, though I would imagine it would be very similar for Java).

Noldorin
I see, so if I may reiterate your point to make sure I understand what you're saying. . .stick to static methods as a means of simplicity while only if a variable's access is forbidden I should fall back on on an instance method. . .Is this sort of like a way to keep things encapsulated?
asdfqwer
Remember that static methods can't be overridden.
Kevin Day
It's really just putting methods where they're most appropiate (though it's not always obvious). To be honest, you'll often change your mind in the development process. Also, as you mention, it is probably best to make it static at first if you don't explicitly need it to be an instance method.
Noldorin
+14  A: 

One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods are more suited to utilitarian types of operations where the behavior is set in stone. Things like base 64 encoding or calculating a checksum for instance.

laz
+1  A: 

If you keep state ( a value ) of an object and the method is used to access, or modify the state then you should use an instance method.

Even if the method does not alter the state ( an utility function ) I would recommend you to use an instance method. Mostly because this way you can have a subclass that perform a different action.

For the rest you could use an static method.

:)

OscarRyz
+1  A: 

Your default choice should be an instance method.

Craig P. Motlin
A: 

If it uses an instance variable it must be an instance method.

If not, it's up to you, but if you find yourself with a lot of static methods and/or static non-final variables, you probably want to extract all the static stuff into a new class instance. (A bunch of static methods and members is a singleton, but a really annoying one, having a real singleton object would be better--a regular object that there happens to be one of, the best!).

Bill K
+2  A: 

If the implementation of a method can be expressed completely in terms of the public interface (without downcasting) of your class, then it may be a good candidate for a static "utility" method. This allows you to maintain a minimal interface while still providing the convenience methods that clients of the code may use a lot. As Scott Meyers explains, this approach encourages encapsulation by minimizing the amount of code impacted by a change to the internal implementation of a class. Here's another interesting article by Herb Sutter picking apart std::basic_string deciding what methods should be members and what shouldn't.

In a language like Java or C++, I'll admit that the static methods make the code less elegant so there's still a tradeoff. In C#, extension methods can give you the best of both worlds.

If the operation will need to be overridden by a sub-class for some reason, then of course it must be an instance method in which case you'll need to think about all the factors that go into designing a class for inheritance.

Dave Ray
The link you provide is really another exercise in deciding what behavior belongs in a class and what doesn't. In Meyers' Wombat example, nap() method has information that Wombat doesn't know (like how long to sleep; that could come from any source) but that doesn't mean it needs to be static.
moffdub
Isn't that the question? When should a method be static or not? Functioning code can be written at either extreme. He's discussing the tradeoff between each side.
Dave Ray
p.s. the scrumboard cartoon is great.
Dave Ray
+9  A: 

I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C.

You need to think about the messages the object you are designing responds to. Those will always be your instance methods. If you think about your objects this way, you'll almost never have static methods. Static members are ok in certain circumstances.

Notable exceptions that come to mind are the Factory Method and Singleton (use sparingly) patterns. Exercise caution when you are tempted to write a "helper" class, for from there, it is a slippery slope into procedural programming.

moffdub
A: 

Basically, the rule of thumb is if it uses any data specific to the object, instance. So Math.max is static but BigInteger.bitCount() is instance. It obviously gets more complicated as your domain model does, and there are border-line cases, but the general idea is simple.

Matthew Flaschen
A: 

I would use an instance method by default. The advantage is that behavior can be overridden in a subclass or if you are coding against interfaces, an alternative implementation of the collaborator can be used. This is really useful for flexibility in testing code.

Static references are baked into your implementation and can't change. I find static useful for short utility methods. If the contents of your static method are very large, you may want to think about breaking responsibility into one or more separate objects and letting those collaborate with the client code as object instances.

cliff.meyers
A: 

IMHO, if you can make it a static method (without having to change it structure) then make it a static method. It is faster, and simpler.

If you know you will want to override the method, I suggest you write a unit test where you actually do this and so it is no longer appropriate to make it static. If that sounds like too much hard work, then don't make it an instance method.

Generally, You shouldn't add functionality as soon as you imagine a use one day (that way madness lies), you should only add functionality you know you actually need.

For a longer explanation...

http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It

http://c2.com/xp/YouArentGonnaNeedIt.html

Peter Lawrey
A: 

the issue with static methods is that you are breaking one of the core Object Oriented principles as you are coupled to an implementation. You want to support the open close principle and have your class implement an interface that describes the dependency (in a behavioral abstract sense) and then have your classes depend on that innterface. Much easier to extend after that point going forward . ..

ooo
A: 

My static methods are always one of the following:

  1. Private "helper" methods that evaluate a formula useful only to that class.
  2. Factory methods (Foo.getInstance() etc.)
  3. In a "utility" class that is final, has a private constructor and contains nothing other than public static methods (e.g. com.google.common.collect.Maps)

I will not make a method static just because it does not refer to any instance variables.

finnw