views:

160

answers:

4

Why should I use an object instance to access member functions rather than class::staticFunction?

( or why not? )

A: 

Static members of a class only hold global state. Instances each have their own state.

rlbond
+1  A: 

Because the object contains the variables that the method might act on.

If you don't use this facility, you are not using OOP (Object Oriented Programming), you are using perl modules.

On the other hand, sometimes what you propose–just using static functions–is appropriate.

Alex Brown
+3  A: 

You're allowed to use the object.function() notation for a static function, but I'd advise against it -- it gives the misleading impression that the function is associated with the specific object, like with a non-static member function. Using the classname::function() syntax portrays the situation clearly and accurately.

Jerry Coffin
This was my thinking, but realizing what Alex Brown mentioned (breaking OOP) had concerned me. But your agreement has confirmed that it was a needless concern.
Nona Urbiz
I think Alex and I had slightly different takes on the question. I took it as: "when you're calling a static function, which syntax should you use." <p>From his answer, I'd guess Alex took your question as something more like: "Should you only ever use static functions." For that question, he's quite right: you're not getting much out of classes if you only ever use static functions.
Jerry Coffin
A: 
  • instance methods belong to a single instance/object to which state/variables they have access.

  • static methods belong to a whole class and no specific instance/object and do not have access to any instance members. They only can use other static members.

codymanix