I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example
String.format(String, Object...)
in Java.Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the
getInstance()
andvalueOf()
methods in the Java API.getInstance()
is the conventional instantiation method in singletons whilevalueOf()
are often type-conversion methods, like inString.valueOf(int)
.Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
One example: when Creation has to happen in a specific way.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.