• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Caffeware

What's your take on protected variables?

27 posts in this topic

What's your take on protected variables?

In the context of c++, it seems most experts (Scott Meyes, Herb Sutter) think is not a good idea. I don't agree. In fact, some languages, for example Ruby, have only automatic protected variables.
It seems silly to make a 'setter' and 'getter' functions for a variable when the derived object is employ in terms of "is-a". Also, making 'setter' functions opens the variable to be manipulated from outside the object! Of course, one could make in the 'setter' protected, but isn't that 'running in a loop'?

Please, discuss.

EDIT:

Let's say I have:

[source lang="cpp"]
class Shape{
public:
virtual void CalculateArea();
private: //private!
int x, y;
int width, height;
};

class Rectangle : public Shape{
public:
void CalculateArea(){
/* I need width and height to calculate, but can't access it.
What can I do? */
}
};
[/source]
If I make 'getters' for Shape class:

[source lang="cpp"]
class Rectangle : public Shape{
public:
void CalculateArea(){
get_width(); //isn't this silly, as width is a fundamental part of Rectangle
//also, now everyone knows my width!
}
};
[/source] Edited by Caffeware
0

Share this post


Link to post
Share on other sites
I never use protected in my code. I find that public and private are expressive enough: I either want this to be part of the interface or a detail of implementation, and I don't feel the need to have derived classes have special privileges. On the other hand, I don't use inheritance all that often, so perhaps protected makes more sense in other styles of coding than my own.
0

Share this post


Link to post
Share on other sites
[quote name='frob' timestamp='1352499274' post='4999455']
Since the compiler optimizers were not that great, having a protected variable meant just a single move instruction whereas mutators and accessors would require multiple jumps and generally hurt performance.
[/quote]

As always, the world has gone full circle :

[url="http://developer.android.com/guide/practices/performance.html"]http://developer.android.com/guide/practices/performance.html[/url]

Google are advocating that programmers should access class field directly, because the Android platform's compiler, at least for now, can't inline acessor/mutator calls.
1

Share this post


Link to post
Share on other sites
[quote name='Khatharr' timestamp='1352519410' post='4999528']
I mean it just sort of strikes me as the same as the "Do not attempt to stop chainsaw with hands or genitals." sticker.
[/quote]

I'm afraid that when it comes to software design a lot of people do still tend to do the equivalent of stopping a chainsaw with their private parts.
Better to educate them about it rather than letting them continue, or let them spread the word to chainsaw-newbies that dismemberment is the right way to go, right?
0

Share this post


Link to post
Share on other sites
I know I'm against the fence here, but I'm gonna try anyway .

[quote name='Hodgman' timestamp='1352521684' post='4999533']
The example code is a straw-man argument. It should look like:
[source lang="cpp"]class Shape{
public:
virtual void CalculateArea();
};
class Rectangle : public Shape{
public:
void CalculateArea(){
return width * height;
}
Rectangle( int w, int h ) : width(w), height(h) {}
private:
int width, height;
};[/source]
[/quote]

The thing about this is that for every 'Shape child' I have to include the width, height, x, y variables separately. Isn't one of the advance of class hierarchy not having to repeat oneself.

By the way, I do AGREE that using setter/getters isn't a good idea.
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1352523806' post='4999545']
Can every shape derivative be descrived with those 4 variables? Bregma hinted earlier that this probably isn't true -- e.g. polygons have a collection of vertices and edges, circles have a radius, squares have an edge-length...

If you're making a polymorphic base class, you shouldn't include any variables that aren't going to be common to all derived classes.
If you do have variables that are common to all derived classes, you probably don't need to be using polymorphism either...
[/quote]

First, thanks for the your time and replies; I really appreciated it.

Now, in Bregma's example, I don't see the 'trouble', since the Circle class would include the necessary variables to calculate it's own area. Yet, the Circle class needs the x, y, width and height variables. I believe it's not in-logic to say the a circle has a width, for example.

"In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects..."
[url="http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29"]http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29[/url]

I know Wiki is not the best source, but... Edited by Caffeware
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1352523806' post='4999545']
Regarding the bold bit -- no. You need to investigate the use of composition vs inheritance. Composition is a tool to allow for code re-use (not repeating yourself). Inheritance is a tool to allow for polymorphism. If you're looking for code re-use, you should default to composition, and only use inheritance where necessary.
[/quote]

I would agree on this. The classical orthodox use of inheritance is for specialization. But I think it is common to see inheritance in C++ used (misused?) for extending functionality of a base class, which is really a way of re-use, not polymorphism.

In the Google Go programming language, they went so far as to not support inheritance. So you can only use composition if you want to "inherit" implementation. Polymorphism is solved by implicit fulfillment of an interface, which is a separate declaration. At first, you feel handicapped. But after a while you realize your don't miss the inheritance hierarchies.
0

Share this post


Link to post
Share on other sites
[quote name='Caffeware' timestamp='1352496482' post='4999429']
What's your take on protected variables?

In the context of c++, it seems most experts (Scott Meyes, Herb Sutter) think is not a good idea. I don't agree. In fact, some languages, for example Ruby, have only automatic protected variables.
It seems silly to make a 'setter' and 'getter' functions for a variable when the derived object is employ in terms of "is-a". Also, making 'setter' functions opens the variable to be manipulated from outside the object! Of course, one could make in the 'setter' protected, but isn't that 'running in a loop'?

Please, discuss.

EDIT:

Let's say I have:

[source lang="cpp"]
class Shape{
public:
virtual void CalculateArea();
private: //private!
int x, y;
int width, height;
};

class Rectangle : public Shape{
public:
void CalculateArea(){
/* I need width and height to calculate, but can't access it.
What can I do? */
}
};
[/source]
If I make 'getters' for Shape class:

[source lang="cpp"]
class Rectangle : public Shape{
public:
void CalculateArea(){
get_width(); //isn't this silly, as width is a fundamental part of Rectangle
//also, now everyone knows my width!
}
};
[/source]
[/quote]

the problems with getters and setters is, people take them too literally.

they make a get and set for each variable, allowing users to, again, invalidate state.

your rectangle class needs left, right, width, top, bottom, height, area, aspectratio, etc to be publically accessible. and none of those getters/setters/whatevers should make it possible to have an invalid rectangle, ever.

set_width() can check if you enter a negative width, and prevent it. set_right can check if your right is more left than your left, and prevent it. and vice versa.

it's not about making methods that directly expose your variables in public. if you want that, use public directly. getters and setters is about NOT exposing anyting directly. aobut making SMART getters and setters. in that case, about making a rectangle ALWAYS a rectangle. not something that has negative space, or what ever.

and as having an object valid at all time is very important, public variables are dangerous. as are protected ones.

but forget about getters and setters. don't write a car that has get_position and set_position. write a car that can drive(), turn(), break() and return current_position(), current_orientation() instead.

if you expose your variables directly, you did not understand the idea of getters and setters.
1

Share this post


Link to post
Share on other sites
I believe the context here can't be too obscure. This is a video game dev site after all.

[quote name='Servant of the Lord' timestamp='1352536318' post='4999582']
Hodgeman rightly mentioned the warning bells that emerge when "Circle" has to ignore either width or height. The warning bells are actually telling you that Circle doesn't have a width or a height, it has a radius or a diameter. You use the diameter to "calculate" the circle's width or height - except that the diameter is exactly equal to the height and is exactly equal to the width, so nobody bothers explicitly calculating it with circles. But just because a circle's width and height happen to be equal to the circle's diameter, that doesn't mean the circle's width and height are the diameter (or vise-versa). You'd actually be reusing the variable "width" or the variable "height" for an entirely different purpose that just happens to be equal, which wouldn't be good (in this situation, it's a very mild issue - but it's still not a good habit to get into).
[/quote]

No. As I see it, the Circle class will include all three: width, height and diameter. The width and height still serves the same purpose for Circle class as it did for Rectangle class. Now, the diameter variable (or maybe radius), will be used to calculate the area of the circle.

[quote]
There's a more serious, but more subtle issue with re-using the Shape's width, height, x, and y. As I already mentioned, you'd actually be re-purposing either width or height for a different purpose. But how many people here realize you'd also be re-purposing x and y for a different purpose as well?
...
What is x and y? A coordinate on a Cartesian grid. Right? But in naming it 'x' and 'y' you are actually naming it what it is, instead of what it's for (Which is why it would be better off wrapped in a Point or Coord class). A variable's type should say what the variable is, but the variable's name should describe it's purpose.
What does 'x' mean to a Shape? 'x' does not describe the purpose, it only describes that it is a horizontal location in space. It could serve any purpose - the name isn't describing the purpose.
It's precisely because it's so generically named that you tricked yourself with your Shape class, and also trick future users of your class:
[/quote]

I don't agree with this. The width and height variables are raw data. Data should be used for whatever it needs to be used.
Of course, the 'x' variable could be named better, let's say 'x_coordinate', or even better, as you say, it could be a point. But my argument is that EVERY child of the Shape class will need a x variable and a y variable, or a point, etc.
It doesn't matter where the point will be located in the shape, the object stills need it.

The Circle class example is the 'whale' of the mammals class.

I must say, I have nothing against composition. I use it much in my code. Yet some things simply belong in a class. And I can't conceive how the child can't have access to the parents data when he is INHERING from that same class. If you permit to me make another example:

[source lang="cpp"]class Dog{
private:
Fangs fangs;
//many other variables
};
class GermanShepherd : public Dog{}[/source]

So you are telling me that class GermanShepherd can't have access to Dog class's private variables?

Or are you going to argue that some dogs don't howl, so they don't fit together in a class. Should I compose GermanShepherd class from Dog class?

You are arguing against inheritance, not against protected variables!

[font=courier new,courier,monospace]inhere [?n?h??]
vb (intr; foll by in) to be an inseparable part (of)[/font] Edited by Caffeware
1

Share this post


Link to post
Share on other sites
[quote name='Caffeware' timestamp='1352654682' post='4999956']
No. As I see it, the Circle class will include all three: width, height and diameter.[/quote]
Why? Width and height can be calculated from diameter (or radius). Including all three just wastes memory and gives you more opportunities to let data get out of sync. See [url=http://en.wikipedia.org/wiki/Don't_repeat_yourself]DRY[/url].

[quote]The width and height still serves the same purpose for Circle class as it did for Rectangle class. Now, the diameter variable (or maybe radius), will be used to calculate the area of the circle.[/quote]
These two sentences contradict each other. Width and height for the rectangle are used to calculate area. Diameter or radius are used to calculate area for the circle. Width and height obviously do not serve the same purpose for a circle. If you're saying clients of the shape base class can use the height and width of a circle the same way they could use the height and width of a rectangle you've just described an interface: i.e. virtual functions the base class can supply, not what should be member variables of the base class.

But again, you keep supplying toy examples without context. Real examples with actual context include how your class hierarchy is intended to be used, not just what it's intended to be modeled. How do you plan to use your Shape class or your Dog class? What problem are these meant to solve? Why should your Dog class even have fangs in the first place? Without context it's impossible to say whether x, y, height, width or fangs are even necessary much less why or why not derived classes should have access to them.
2

Share this post


Link to post
Share on other sites
I find I use protected variables from time to time. Most of the time they are const variables initialized once, so there's no need to worry about invalid state, or messing things up, ect... In theory they could be made public but why clutter the public interface? The other time is for small/specific classes that I have no intention of anyone else inheriting from, and then its mostly for convenience. Off the top of my head I can't think of any time I've absolutely required them, but none-the-less I'm quite glad they're there.
2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0