tobias.sturn@vol.at posted:
[color=blue]
> Hi!
>
> My prof told me always to make my members private or protected cause
> its standard to write setter and getter methodes.. Is that in your
> opinion correct?[/color]
I gather that he suggest you write:
class Monkey {
private:
int a;
char b;
public:
void SetA( int const arg ) { a = arg; }
int GetA() const { return a; }
void SetB( char const arg ) { b = arg; }
char GetB() const { return b; }
};
rather than simply:
class Monkey {
public:
int a;
char b;
};
This is ridiculous and amounts to overkill most of the time. But there
are places where it's prefereable to use Getters&Setters. For instance,
maybe in the future, you will rewrite your class such that you no longer
store your values in simple member variables... you might store and
retrieve them from a database for instance. If you have Getters&Setters,
then your client can be totally oblivious to the change in
implementation:
class Monkey {
public:
char GetB() const
{
global_database.open();
global_database.verify_record(17);
return global_datebase.current_record.value();
}
};
However this is extremely rare -- far too rare to adopt a strategy of
ALWAYS writing Getters & Setters. If anything, it demonstrates the
programmers lack of intelligence -- he can't think for himself because
he's too busy adhering to doctrine.
[color=blue]
> Cause I dont see any adventages to write a member of a
> class private if there are no side effects in changing the variable.[/color]
And you're correct.
[color=blue]
> I think you only have to write more (the getter and setters) the code
> gets bigger...[/color]
And you're correct.
I myself have never written code with Getters&Setters. I even prefer to
have "read-only" members rather than Getters on their own. For instance:
class Monkey {
string str;
public:
const string& cstr;
Monkey() : cstr(str) {}
};
Now "str" is modifiable within the class, but constant to the outside
world.
-Tomás