Static Methods and Classes – Best Practices in Object-Oriented Programming

object-orientedprogramming practices

I know that static methods/variables are associated with the class and not the objects of the class and are useful in situations when we need to keep count of, say the number of objects of the class that were created. Non-static members on the other hand may need to work on the specific object (i.e. to use the variables initialized by the constructor)

My question what should we do when we need neither of the functionalities?

Say I just need a utility function that accepts value(s) and returns a value based solely on the values passed. I want to know whether such methods should be static or not. How is programming efficiency affected and which is a better coding practice/convention and why.

PS: I don't want to spark off a debate, I just want a subjective answer and/or references.

Best Answer

Methods which are not attached to any specific class like these are called "free functions", and as you have adequately noted, OO does not provide for them, and some languages also do not provide the facilities for them.

In a language like C++ you can just place the function in a namespace. But if you're working in Java or C# you must pointlessly place them in a class and make them a static member for no good reason at all.