Alex Rivera | Logout

Java: When to make methods static v. instance

Asked 2009-10-24T20:20:04.560
33

I have a Gene class that keeps track of genes. Gene has a method for calculating the distance between two genes. Are there any reasons to make it static?

Which is better?

public static int geneDistance(Gene g0, Gene g1)

or

public int geneDistance(Gene other)

Arguments for/against making it static? I understand what it means for a member to be static, I'm just interested in its implications for maximum cleanliness/efficiency/etc.

I repeat the same pattern for returning trimmed versions of two genes, finding matches between genes, finding matches between animals (which contain collections of genes), etc.

Edit
Report

2 Answers

8

IMO there is no absolute "better", but public int geneDistance(Gene other) is stylistically more similar to other methods in Java (e.g. Object.equals, Comparable.compareTo), so I'd go that way.

answered 2009-10-24T20:26:45.930
7

My rewording of Charle's answer :

If the method in question intends to use the state of the underlying object in any way, make it an instance method. Else, make it static.

Which depends on the way the object's class is designed.

In your case, alphazero, probably the int geneDistance(Gene g0, Gene g1) does not really depend on the state of the Gene instance it is called on. I would make this method static. And put it in a utility class like GeneUtils.

Of course, there might be other aspects of your problem that I am not aware of, but this is the general thumb of rule that I use.

P.S. -> The reason I would not put the method in the Gene class itself is because a Gene should not be responsible for computing it's distance from another Gene. ;-)

answered 2009-11-11T05:29:57.470

Your Answer