Access member variables directly or pass as parameter?

谁说我不能喝 提交于 2019-12-05 01:26:20

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.

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.

I understand the problem, having had to maintain large classes in code I didn't originally author. In C++ we have the keyword const to help identify methods that don't change the state:

void methodA() const;

Use of this helps maintainability because we can see if a method may change the state of an object.

In other languages that don't have this concept I prefer to be clear about whether I'm changing the state of the instance variable by either having it passed in by reference or returning the change

this->mMemberVariable = this->someMethod();

Rather than

void someMethod()
{
   this->mMemberVariable = 1; // change object state but do so in non transparent way
}

I have found over the years that this makes for easier to maintain code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!