Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a method be static?

In addition, are there any performance advantages to static methods over instance methods?

I came across the following recently: http://www.cafeaulait.org/course/week4/22.html :

When should a method be static?

  1. Neither reads from nor writes to instance fields
  2. Independent of the state of the object
  3. Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value
  4. Factory methods that serve in lieu of constructors

I would be very interested in the feedback of the Stack Overflow community on this.

like image 545
Scott Lawrence Avatar asked Sep 07 '08 20:09

Scott Lawrence


People also ask

Why would you make a method static?

Sometimes a method or class is used a lot throughout your project that you don't want to make a lot of instances of it, so you just make it static.

When should a method be static vs non-static?

A static method can access only static members and can not access non-static members. A non-static method can access both static as well as non-static members. Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding.


2 Answers

Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.

You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.

like image 162
Tom Hawtin - tackline Avatar answered Nov 09 '22 12:11

Tom Hawtin - tackline


Whether or not a method is static is more of a design consideration than one of efficiency. A static method belongs to a class, where a non-static method belongs to an object. If you had a Math class, you might have a few static methods to deal with addition and subtraction because these are concepts associated with Math. However, if you had a Car class, you might have a few non-static methods to change gears and steer, because those are associated with a specific car, and not the concept of cars in general.

like image 36
Kyle Cronin Avatar answered Nov 09 '22 14:11

Kyle Cronin