I have been writing python OO for a while and every time when I create a method, I always ask myself, should this be instance method or staticmethod (or classmethod)?
As you might already aware that the difference between instance method and static method is that static method doesn’t have access to the instance, same goes with class method which only has access to the class.
At first, I thought an instance method can turn into a static method if I pass all the necessary parameters, right?! It’s easier to write unit tests against a static method since I don’t have to prepare an instance.
There were times I started with static methods and then having the need to call another static method, but the inner static method need to access a variable that is not relevant to the outer static method, so I had to pass that variable into the outer static method, sounds code smell isn’t it?!
The performance between the 2 is negligible, so deciding the 2 is mostly OO design issue.
So I have come up some simple rules to decide when to create instance method or static method:
- if the method is likely to call other methods (or instance methods), better be on the safe side, use instance method
- if the method is very thin(great cohesion), or unlikely to call other methods, use static method
- if the method alters the instance state, use instance method
Please let me know what you think by leaving a comment.