Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access members directly or always use getters

Tags:

Note: C++ specific question

I personally find it weird/ugly when a class uses a getter to access its own member data. I know the performance impact is none but I just don't like to see all those method calls. Are there any strong arguments either way, or is it just one of those things that's personal preference and should be left to each coder, or arbitrarily controlled in a coding standard?

Update: I'm meaning simple getters, specifically for a class' non-public members.

like image 515
Mr. Boy Avatar asked Sep 27 '10 08:09

Mr. Boy


1 Answers

The reason you might want to use a getter/setter is because it conceals the implementation. You won't have to rewrite all of your code if you are using getters/setters in case the implementation does change, because those members can continue to work.

EDIT based on the many clever comments:

As for a class using setters and getters on itself, that may depend on the particulars. After all, the implementation of a particular class is available to the class itself. In the cases where a class is normally instantiated, the class should use the member values directly for its own members (private or otherwise) and its parent classes (if they are protected) and only use getters/setters in the case that those members are private to the parent class.

In the case of an abstract type, which will usually not contain any implementation at all, it should provide pure virtual getters and setters and use only those in the methods it does implement.

like image 86
SingleNegationElimination Avatar answered Oct 03 '22 09:10

SingleNegationElimination