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.
Thank you Bernard. Btw, do you know what it means for a compiler to "bind a method to the class"? Oct 8, 2011 at 22:01
@Dark Templar: Can't say that I do. Is this specific to a particular language?– BernardOct 10, 2011 at 17:19
1I have a slight problem with your definition "they don't depend on any class members". Member static functions can't access any non-static member, however they can access static members. Static members are members of the class.– newprintAug 20, 2013 at 23:48
@newprint: You are correct, however that is not what I said. I said when they don't depend on any class members. Using static members is fine if they are necessary, but that may not always be the case.– BernardAug 21, 2013 at 13:32
We already have functions then why the concept of static methods still exists? I mean we use the static methods as same as we use the functions, right? then what is the need for static methods? Sorry if I'm mistaken or my question is too basic. Thanks a lot in advance :)– MilanNov 4, 2020 at 1:49
Trying for a more simplified explanation than the above (pretty good ones).
An object is code + data normally. A static method is used when you only have the "code" portion to deal with (there is no data/state being maintained (except static data members)).
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.
1Wouldn't it be better in your example to use a free function?– Ela782May 22, 2014 at 10:11
2@Ela782 If the language has free functions, yes.– user7043May 22, 2014 at 10:20
1Okay, thanks for the reassurance. I only learned this best practice recently. However, then I'm at the moment having trouble seeing when a public static member-function could actually be useful, let's say in a language like C++. The use-case for both is when the function does not depend or need an instance of the class, and then, free functions are the recommendation. Maybe this should be a new question.– Ela782May 22, 2014 at 10:28
1@Ela782 Yeah, it could make a fine question. Two quick points: In C++ specifically, static members are useful for template meta programming since you can pass a type as template parameter but not a namespace. In general, static functions can be used to indicate that the function really closely belongs to some class, as opposed to just belonging in a namespace (think
stuff::LoadThing()).– user7043May 22, 2014 at 10:31
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.
DRY is not a sufficient justification alone, since unless the function needs privileged access to private members of instances passed in or otherwise available to it, it can and should just be a free function, thus minimising the chance of unexpected changes to instance state May 11, 2021 at 9:07
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).
I use static methods in both C++ and C# for Utility classes, classes that don't have any instance data, just one way to bundle a collection of useful, related methods.
int count1 = DBUtil::GetCountOfSlackerEmployees(); int count2 = DBUtil::GetCountOfEmployedSlackers();
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.
Typically you need a static main to act as an entry point for your program. That could be kind of important.
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.
Static methods aren't "guaranteed to be stateless". While it's true that they can't use instance data, they also have access to some state (namely static members, both of the class to which the static method belongs and to other globally visible state such as other classes's static variables).– user7043Oct 8, 2011 at 10:59
@delnan: true ...you are right. Let me correct this right now. Oct 8, 2011 at 11:37
x.sin(). Your answer assumes that sin should be a function of "Math", whereas it's clearly operating on an double. Aug 28, 2018 at 6:52
This is a poor answer because the real solution is not to have a pointless class at all. Just use a namespace and free functions therein. May 11, 2021 at 9:05
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.
staticfor limiting functions to file scope.
private memberwe can safely assume the OP is asking about the OO concept and has no clue about file-scope static.