Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
Shouldn't that be "replace all static functions with private member functions"? Currently, you're stating that you don't see the point of static methods and go on to ask why we don't use more of them. –  delnan Oct 7 '11 at 18:19
4  
What is a "static function"? In C++, there's at least two meanings (and last I looked at C++11 drafts, they'd removed the deprecation notice for static for limiting functions to file scope. –  David Thornley Oct 7 '11 at 18:25
    
Do you mean "static function" in sense of file-scope static free function in C/C++, or as "static memenber function/method"? It's huge difference! –  Jan Hudec Oct 7 '11 at 19:59
    
@JanHudec: I think that given the presence of private member we can safely assume the OP is asking about the OO concept and has no clue about file-scope static. –  Matthieu M. Oct 8 '11 at 12:42
    
@MatthieuM.: Actually the presence of 'private member' is exactly what lead me to believe that he does mean static functions in the C++ sense. Because file-scoped static functions and private member functions are the two things that have very similar use in C++, while replacing public static member with private non-static member just does not make much sense. Unfortunately OP does not seem to be responding. –  Jan Hudec Oct 10 '11 at 5:33
add comment

15 Answers

up vote 12 down vote accepted

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.

share|improve this answer
    
Thank you Bernard. Btw, do you know what it means for a compiler to "bind a method to the class"? –  Dark Templar Oct 8 '11 at 22:01
    
@Dark Templar: Can't say that I do. Is this specific to a particular language? –  Bernard Oct 10 '11 at 17:19
    
I 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. –  newprint Aug 20 '13 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. –  Bernard Aug 21 '13 at 13:32
add comment

I would like to point out another use of static f().

http://www.parashift.com/c++-faq/named-ctor-idiom.html

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).

share|improve this answer
add comment

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.

share|improve this answer
add comment

Let's say you want to compute the sinus of something.

Without static:

Math math = new Math()
double y = math.sin(x)

With static:

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.

share|improve this answer
    
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). –  delnan Oct 8 '11 at 10:59
    
@delnan: true ...you are right. Let me correct this right now. –  arnaud Oct 8 '11 at 11:37
add comment

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.

share|improve this answer
add comment

"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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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 a.Add(b), but 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
share|improve this answer
add comment

Typically you need a static main to act as an entry point for your program. That could be kind of important.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.[1]

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.

  1. If you find yourself copying the same methods in multiple objects consider making the method static so you can follow DRY.
  2. 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.

share|improve this answer
add comment

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();
share|improve this answer
add comment

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).

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.