Valhalla Legends Forums Archive | C/C++ Programming | Personal pet hate regarding OO

AuthorMessageTime
Arta
I hate pointless accessor functions!

Given:

[code]
class X
{
public
int GetY(void) { return Y };
void SetY(int Value) { Y = Value };
private:
int Y;
}
[/code]

This is stupid! To quote Iago, you don't want people messing with your privates, so why provide functions that let people do just that? If You're providing those functions, doesn't it make a lot more sense to make the variable public? If the accessors implement some kind of sanity checking or other processing, that's totally acceptable, but I see this far too often and it drives me mad. When I asked one of my lecturers his reasoning (he does it ALL the time) he just said that making it public "Wouldn't be very OO".

Bah!
December 3, 2003, 3:24 PM
Adron
Writing it this way allows you to change the implementation of the variable later without changing the code that uses it. Depending on what it is, it might make sense to be able to do that, or not.
December 3, 2003, 4:18 PM
iago
I agree, that is probably the most irritating thing.

However, in non-oo code, you also have that problem. Unless you extern your variables, to use values across files, you have to do this. And nobody likes extern'ing, so here we are!

I would recommend looking up the keyword friend. If you don't know what it means, it's basically that any function that declares you as a friend will let you play with its privates (well, until it's done ;)). I Don't remember exactly how to use it, but it's something like this:
[code]
class c2; // gotta declare it ahead; not so great to do, but it works for this
class c1
{
private:
int myvar;

friend c2;
};

class c2
{
public:
c2(c1 *ptr)
{
ptr->myvar = 4;
}
};
[/code]

2 things worth noting, though:
a) By default, all classes of the same type are friends, so if you have two instances of c1 they can play with each other's privates (some kind of gay thing, I suspect ;))
b) By using inheritance, you can get around this problem. but that obviously won't solve everything.

But don't get my wrong, I totally agree with you. There SHOULD be a readonly: keyword built into the class.

That's my thoughts, anyway. :)
December 3, 2003, 6:36 PM
Skywing
Have you considered using const?
December 3, 2003, 7:51 PM
Arta
I think Iago's point was that a keyword allowing the class to modify it's own member variables, while allowing others only to read them, would be useful.
December 3, 2003, 8:10 PM
Skywing
[quote author=Arta[vL] link=board=30;threadid=4046;start=0#msg33447 date=1070482225]
I think Iago's point was that a keyword allowing the class to modify it's own member variables, while allowing others only to read them, would be useful.
[/quote]
Use a const object with mutable members.
December 3, 2003, 8:12 PM
Maddox
[quote author=iago link=board=30;threadid=4046;start=0#msg33429 date=1070476618]
play with its privates
[/quote]

Hah.
December 7, 2003, 8:40 PM

Search