• Welcome to Valhalla Legends Archive.
 

Personal pet hate regarding OO

Started by Arta, December 03, 2003, 09:24 AM

Previous topic - Next topic

Arta

I hate pointless accessor functions!

Given:


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


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!

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.

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:

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;
 }
};


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. :)
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


Skywing


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.

Skywing

Quote from: Arta[vL] on December 03, 2003, 02:10 PM
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.
Use a const object with mutable members.

Maddox

asdf.