Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access member variables directly or pass as parameter?

I noticed that even when paying respect to the single responsibility principle of OOD, sometimes classes still grow large. Sometimes accessing member variables directly in methods feels like having global state, and a lot of stuff exists in the current scope. Just by looking at the method currently working in, it is not possible anymore to determine where invidiual variables accessible in the current scope come from.

When working together with a friend lately, I realized I write much more verbose code than him, because I pass member variables still as parameters into every single method.

Is this bad practice?

edit: example:

class AddNumbers {
public:
    int a, b;
    // ...
    int addNumbers {
        // I could have called this without arguments like this:
        // return internalAlgorithmAddNumbers();
        // because the data needed to compute the result is in members.
        return internalAlgorithmAddNumbers(a,b);
    }

private:
    int internalAlgorithmAddNumbers(int sum1, int sum2) { return sum1+sum2; }
};
like image 256
Tom Avatar asked Aug 04 '12 17:08

Tom


2 Answers

If a class has member variables, use them. If you want to pass parameters explicitly, make it a free function. Passing member variables around not only makes the code more verbose, it also violates people's expectations and makes the code hard to understand.

The entire purpose of a class is to create a set of functions with an implicitly passed shared state. If this isn't what you want to do, don't use a class.

like image 51
Antimony Avatar answered Oct 11 '22 17:10

Antimony


Yes, definetely a bad practice. Passing a member variable to a member function has no sense at all, from my point of view. It has several disadvantages:

  1. Decrease code readability
  2. Cost in term of performances to copy the parameter on the stack

Eventually converting the method to a simple function, may have sense. In fact, from a performance point of view, call to non-member function are actually faster (doesn't need to dereference this pointer).

EDIT:

Answer to your comment. If the function can perform its job only using a few parameters passed explicitely, and doesn't need any internal state, than probably there is no reason to declare it has a member function. Use a simple C-style function call and pass the parameters to it.

like image 23
Heisenbug Avatar answered Oct 11 '22 17:10

Heisenbug