OK, I've learned what a static function is, but I still don't see why they are more useful than private member functions. This might be kind of a newb-ish question here, but why not just replace all private member functions with static functions instead?
Assuming that you're using OOP, use static functions when they don't depend on any class members. They can still be private, but this way they are optimized as they don't depend on any instance of the related object.
Other than the above, I find static functions useful when you don't want to create an instance of an object just to execute one public function on it. This is mainly the case for helper classes that contain public functions to do some repetitive and general work, but don't need to maintain any state between calls.
Because they don't require an instance and can be public. Say you need a function to get the greatest common denominator (GCD; very useful for fraction classes; and yes this is just a simple example). There is no point in creating a class of objects whose sole purpose is that you can have a
this pointer you neither need nor use in
gcd. So you use a static method for it, ideally on the class which actually uses the GCD (e.g. in the fraction class).
Of coures if there are only static methods, you're doing OOP wrong and should either switch to actually doing OOP or using a language more appropriate to your paradigm.
I use them as helper functions to common tasks, examples being:
- Converting degrees into radians (and vice-versa);
- Hashing a string;
- Converting from a enum to something else (in this project I'm working, they act as a hash table);
Most of my files that group static functions have the suffix Helper, meaning that it's what they do, help me get somewhere faster.
As to what a static method is:
Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance.
Examples of when are static methods useful:
- Global/helper methods
- Getting query results from a Data Model class (calling a SP)
Just use them where appropriate only.
- If you find yourself copying the same methods in multiple objects consider making the method static so you can follow DRY.
- Use static methods if you don't need an instance of an object (you're not doing work on and object's instance variables)
If a lot of your data is outside of objects and they are being worked on via static methods then your code is not object oriented and may become difficult to maintain.
Static and private are in fact orthogonal: a method can be static, or private, or none, or both.
Static vs. non-static (a.k.a. 'instance methods') indicates whether the method operates on the class itself (static) or on one particular instance (non-static). Depending on the language, you can call a static method through an instance, but you can never access the instance through a static method (which also implies that you cannot call any non-static methods from inside a static method, simply because you have no
this object). Use static methods to implement behavior that is conceptually linked to the class, but does not 'bind' to one particular instance. Another scenario where you might want to use static methods is when you have a function that operates on two instances of a class, and neither operand deserves a privileged status - for example, assuming you have a class
Vector, and you want to implement addition; your addition method could be called as
Vector.Add(a, b) probably makes more sense.
Private vs. public are about visibility of the method. Private methods can only be accessed from within the class's own scope, while public methods are accessible from anywhere. The most important use for this is encapsulation: by making only those methods and properties public that are absolutely needed by the rest of the code to communicate with your class, you limit the points at which outside code can introduce problems, and you prevent problems inside your class from bleeding into the rest of the project.
So, rule of thumb:
- make all member functions private, except those that need to be called from outside the class
- make all methods instance methods, unless they make sense even when no instance of the class exists
It's funny how nobody has been able to give a good answer yet. I'm not sure this one is either. You should probably take it as a hint that they should be used as little as possible. They're after all procedural rather than OOP.
Here are some more examples:
In Obj-C, where they're called class methods, they're commonly used as allocation wrappers where the object is put in the reference counting pool before being returned.
Another example from Obj-C is to register a new class in to a class collection. Let's say you have a set of classes each handling one type of file. When you create a new class for a new file type you could register it to the collection (a global variable) using a static method in the class that determines the type of file.
In C++ another use I can think of is to softly catch errors. Your constructor function can't fail, except by throwing an exception. You could set an error instance variable, but that's not always appropriate. Instead you can do the parts that might fail in a static wrapper and then allocate and return the new object, or NULL on failure.
"why not just replace all private member functions with static functions instead?"
... because a private member can access instance data whilst only allowing it to happen from calls made inside other member functions. The static function can be private, but its not going to be able to alter or refer to an instance of the class unless the instance is passed in as a parameter.
I would like to point out another use of static f().
Boils down to this:
static functions allow you to create "Named Constructors", i.e you name your static function with suitable and self-documenting name, and this static function calls one of the constructors (since constructors have identical names, and you can have a lot of them, it gets hard to distinguish between them).
Assuming you are speaking of C++ (you didn't say) and you have the terms right (i.e. do not mean member functions/methods):
Even a private member function still has to be declared in the header, which means it actually becomes part of the API and ABI of the class, even though the user can't actually call it. If you add, modify or delete private member function, you are forcing recompilation of all dependent classes (the header has changed, make can't know better) and when you do so in a library, you have to consider compatibility for the application using it.
On the other hand file-scoped static functions don't get a public symbol, so you can add, modify or delete them as you like and nothing beyond the one compilation unit will ever be affected.
A static function (and there's different meanings for that term in different languages), doesn't require any state that is retained between calls. If it is conceptually closely tied to what an class does, make it a class function (as in on a class not an object), or if not, make it a global (or module-level, whatever) function. It doesn't belong on an object if it has no need of the object's state.
If you're passing state to it all the time, its not really a stateless function, you're just making a stateful function with stateless syntax. In that case, it probably belongs on the calling object, or maybe a refactoring to better align the state and behavior is indicated.
Let's say you want to compute the sinus of something.
Math math = new Math() double y = math.sin(x)
double y = Math.sin(x)
It makes no sense to make
sin non-static. It is stateless and just processes the input.
Static functions are not tied to a particular objects. They are "general" functions that are independent of the internal state of the object.
Kind of late here but I'd like to try to create a precise definition: static functions are functions that do not or can not reference instance properties/methods of the containing class.
In some languages, like C#, there might be static fields or properties in static classes, so it's not exactly right to say they're not used for state; a static function might make use of static (global) state.
Basically, it boils down to: static functions, like anything static, are useful when it makes sense for them to always be available with no dependency on non-static instances.
Helper functions, like math functions, are an oft-sited example, but there are others.
If the class you create requires the data be immutable, it might make sense to create static functions that take in an instance and pass a new instance since the instance can't (or shouldn't) be changed. String classes, for instance, might have static functions that take in a string (or 2 or more) and pass back a new string.
Another reason might be that there's a class that keeps a global state or data of some kind. There might be static functions that work with the static properties or fields in that static class.