I have a top-level class which instantiates sub modules using composition. The user knows that the top class will have these submodules. Is it a good idea to make the submodule objects public members so that the user can call their functions directly?
The alternative seems to be to wrap their function calls which protects the submodules from being made public, but doesn't have any encapsulation benefit since the user needs to specify the submodule anyway.
Here is a top-level class House with submodules kitchen and bathroom.
// Public member objects
class Kitchen {
public:
void turn_on_tap();
int compute_area();
};
class Bathroom {
public:
void turn_on_tap();
int compute_area();
};
class House {
public:
Kitchen kitchen;
Bathroom bathroom;
int compute_area() { return kitchen.compute_area() + bathroom.compute_area(); }
};
//User code:
House house;
house.kitchen.turn_on_tap();
house.bathroom.turn_on_tap();
house.compute_area() // OK
house.bathroom.compute_area(); // may not want user to be able to do this
// Private member objects
class House {
Kitchen kitchen;
Bathroom bathroom;
public:
void turn_on_kitchen_tap() { kitchen.turn_on_tap(); }
void turn_on_bathroom_tap() { bathroom.turn_on_tap(); }
int compute_area() { return kitchen.compute_area() + bathroom.compute_area(); }
};
//User code:
House house;
house.turn_on_kitchen_tap();
house.turn_on_bathroom_tap();
house.compute_area();
I prefer the syntax of the first but it means making the member objects public.
The second approach seems tedious because of the additional functions I have to write to wrap the underlying function calls. And I lose the nice dot hierarchical dereferencing because the user knows (and needs to know) about the underlying hierarchy.
EDIT: But if I make them public, I will expose other backend public functions in Kitchen and Bathroom that I don't necessarily want the user to be aware of. So then I might have to make those private and use "friend" which gets a little ugly.
Added compute_area() to above code.
It depends. If a house is a simple aggregate, i.e:
A valid value of a House is any combination of valid values of Kitchen, and Bathroom. That is to say, there is no House specific invariant to keep.
The individual components handle their own invariants correctly by themselves, and by extension the container's given point No. 1.
The container's member functions are just tiny wrappers around each component, or even just return a reference to a component for modification.
Then yes, a simple struct (for the default public access) is indeed proper. "Encapsulating" here is just an exercise in verbosity. Sometimes the object you need is just a bunch of stuff glued together, with no further logic.
So whether or not it's a good a idea is something you will need to examine for your own application by yourself.
Related
I am starting to code bigger objects, having other objects inside them.
Sometimes, I need to be able to call methods of a sub-object from outside the class of the object containing it, from the main() function for example.
So far I was using getters and setters as I learned.
This would give something like the following code:
class Object {
public:
bool Object::SetSubMode(int mode);
int Object::GetSubMode();
private:
SubObject subObject;
};
class SubObject {
public:
bool SubObject::SetMode(int mode);
int SubObject::GetMode();
private:
int m_mode(0);
};
bool Object::SetSubMode(int mode) { return subObject.SetMode(mode); }
int Object::GetSubMode() { return subObject.GetMode(); }
bool SubObject::SetMode(int mode) { m_mode = mode; return true; }
int SubObject::GetMode() { return m_mode; }
This feels very sub-optimal, forces me to write (ugly) code for every method that needs to be accessible from outside. I would like to be able to do something as simple as Object->SubObject->Method(param);
I thought of a simple solution: putting the sub-object as public in my object.
This way I should be able to simply access its methods from outside.
The problem is that when I learned object oriented programming, I was told that putting anything in public besides methods was blasphemy and I do not want to start taking bad coding habits.
Another solution I came across during my research before posting here is to add a public pointer to the sub-object perhaps?
How can I access a sub-object's methods in a neat way?
Is it allowed / a good practice to put an object inside a class as public to access its methods? How to do without that otherwise?
Thank you very much for your help on this.
The problem with both a pointer and public member object is you've just removed the information hiding. Your code is now more brittle because it all "knows" that you've implemented object Car with 4 object Wheel members. Instead of calling a Car function that hides the details like this:
Car->SetRPM(200); // hiding
You want to directly start spinning the Wheels like this:
Car.wheel_1.SetRPM(200); // not hiding! and brittle!
Car.wheel_2.SetRPM(200);
And what if you change the internals of the class? The above might now be broken and need to be changed to:
Car.wheel[0].SetRPM(200); // not hiding!
Car.wheel[1].SetRPM(200);
Also, for your Car you can say SetRPM() and the class figures out whether it is front wheel drive, rear wheel drive, or all wheel drive. If you talk to the wheel members directly that implementation detail is no longer hidden.
Sometimes you do need direct access to a class's members, but one goal in creating the class was to encapsulate and hide implementation details from the caller.
Note that you can have Set and Get operations that update more than one bit of member data in the class, but ideally those operations make sense for the Car itself and not specific member objects.
I was told that putting anything in public besides methods was blasphemy
Blanket statements like this are dangerous; There are pros and cons to each style that you must take into consideration, but an outright ban on public members is a bad idea IMO.
The main problem with having public members is that it exposes implementation details that might be better hidden. For example, let's say you are writing some library:
struct A {
struct B {
void foo() {...}
};
B b;
};
A a;
a.b.foo();
Now a few years down you decide that you want to change the behavior of A depending on the context; maybe you want to make it run differently in a test environment, maybe you want to load from a different data source, etc.. Heck, maybe you just decide the name of the member b is not descriptive enough. But because b is public, you can't change the behavior of A without breaking client code.
struct A {
struct B {
void foo() {...}
};
struct C {
void foo() {...}
};
B b;
C c;
};
A a;
a.c.foo(); // Uh oh, everywhere that uses b needs to change!
Now if you were to let A wrap the implementation:
class A {
public:
foo() {
if (TESTING) {
b.foo();
} else {
c.foo();
}
private:
struct B {
void foo() {...}
};
struct C {
void foo() {...}
};
B b;
C c;
};
A a;
a.foo(); // I don't care how foo is implemented, it just works
(This is not a perfect example, but you get the idea.)
Of course, the disadvantage here is that it requires a lot of extra boilerplate, like you have already noticed. So basically, the question is "do you expect the implementation details to change in the future, and if so, will it cost more to add boilerplate now, or to refactor every call later?" And if you are writing a library used by external users, then "refactor every call" turns into "break all client code and force them to refactor", which will make a lot of people very upset.
Of course instead of writing forwarding functions for each function in SubObject, you could just add a getter for subObject:
const SubObject& getSubObject() { return subObject; }
// ...
object.getSubObject().setMode(0);
Which suffers from some of the same problems as above, although it is a bit easier to work around because the SubObject interface is not necessarily tied to the implementation.
All that said, I think there are certainly times where public members are the correct choice. For example, simple structs whose primary purpose is to act as the input for another function, or who just get a bundle of data from point A to point B. Sometimes all that boilerplate is really overkill.
This is really a question of good form/best practices. I use structs in C++ to form objects that are designed to basically hold data, rather than making a class with a ton of accessor methods that do nothing but get/set the values. For example:
struct Person {
std::string name;
DateObject dob;
(...)
};
If you imagine 20 more variables there, writing this as a class with private members and 40-something accessors is a pain to manage and seems wasteful to me.
Sometimes though, I might need to also add some sort of minimal functionality to the data. In the example, say I also sometimes need the age, based on dob:
struct Person {
std::string name;
DateObject dob;
(...)
int age() {return calculated age from dob;}
}
Of course for any complex functionality I would make a class, but for just a simple functionality like this, is this "bad design"? If I do use a class, is it bad form to keep the data variables as public class members, or do I just need to accept it and make classes with a bunch of accessor methods? I understand the differences between classes and structs, I'm just asking about best practices.
I think there are two important design principles to consider here:
Hide a class's representation through an interface if there is some invariant on that class.
A class has an invariant when there is such thing as an invalid state for that class. The class should maintain its invariant at all times.
Consider a Point type that represents a 2D geometric point. This should just be a struct with public x and y data members. There is no such thing as an invalid point. Every combination of x and y values is perfectly fine.
In the case of a Person, whether it has invariants depends entirely on the problem at hand. Do you consider such things as an empty name as a valid name? Can the Person have any date of birth? For your case, I think the answer is yes and your class should keep the members public.
See: Classes Should Enforce Invariants
Non-friend non-member functions improve encapsulation.
There's no reason your age function should be implemented as a member function. The result of age can be calculated using the public interface of Person, so it has no reason to be a member function. Place it in the same namespace as Person so that it is found by argument-dependent lookup. Functions found by ADL are part of the interface of that class; they just don't have access to private data.
If you did make it a member function and one day introduced some private state to Person, you would have an unnecessary dependency. Suddenly age has more access to data than it needs.
See: How Non-Member Functions Improve Encapsulation
So here's how I would implement it:
struct Person {
std::string name;
DateObject dob;
};
int age(const Person& person) {
return calculated age from person.dob;
}
In C++, Structs are classes, with the only difference (that I can think of, at least) being that in Structs members are public by default, but in classes they are private. This means it is perfectly acceptable to use Structs as you are - this article explains it well.
In C++, the only difference between structs and classes are that structs are publicly visibly by default. A good guideline is to use structs as plain-old-data (POD) that only hold data and use classes for when more functionality (member functions) is required.
You may still be wondering whether to just have public variables in the class or use member functions; consider the following scenario.
Let's say you have a class A that has a function GetSomeVariable that is merely a getter for a private variable:
class A
{
double _someVariable;
public:
double GetSomeVariable() { return _someVariable; }
};
What if, twenty years down the line, the meaning of that variable changes, and you have to, let's say, multiply it by 0.5? When using a getter, it is simple; just return the variable multiplied by 0.5:
double GetSomeVariable() { return 0.5*_someVariable; }
By doing this, you allow for easy maintainability and allow for easy modification.
If you want some data holder then prefer struct without any get/set methods.
If there is more to it, as in this case "Person".
It models real world entity,
Has definite state and behaviour,
Interacts with external world,
Exhibits simple/complex relationship with other entities,
it may evolve overtime,
then it is a perfect candidate for a class.
"Use a struct only for passive objects that carry data; everything else is a class."
say google guidlines, I do it this way and find it a good rule. Beside that I think you can define your own pragmatics, or deviate from this rule if it really makes sense.
I don't want to sparkle a holy war here; I usually differentiate it in this way:
For POD objects (i.e., data-only, without exposed behavior) declare the internals public and access them directly. Usage of struct keyword is convenient here and also serves as a hint of the object usage.
For non-POD objects declare the internals private and define public getters/setters. Usage of class keyword is more natural in these cases.
For just clearing the confusion for some! And easy picking! Here some points!
In struct! you can have encapsulation and visibility operators (make private or public)! Just like you do with classes!
So the statement that some say or you may find online that say: one of the differences is that structures have no visibility operator and ability to hide data, is wrong!
You can have methods just like in classes!
Run the code bellow! And you can check it compiles all well! And run all well! And the whole struct work just like class!
Mainly the difference is just in the defaulting of the visibility mode!
Structures have it public! Classes privates by default!
#include<iostream>
#include<string>
using namespace std;
int main(int argv, char * argc[]) {
struct {
private:
bool _iamSuperPrivate = true;
void _sayHallo() {
cout << "Hallo mein Bruder!" << endl;
}
public:
string helloAddress = "";
void sayHellow() {
cout << "Hellow!" << endl;
if (this->helloAddress != "") {
cout << this->helloAddress << endl;
}
this->_sayHallo();
}
bool isSuperPrivateWorking() {
return this->_iamSuperPrivate;
}
} testStruct;
testStruct.helloAddress = "my Friend!";
testStruct.sayHellow();
if (testStruct.isSuperPrivateWorking()) {
cout << "Super private is working all well!" << endl;
} else {
cout << "Super private not working LOL !!!" << endl;
}
return 0;
}
In memory they are the same!
I didn't check myself! But some say if you make the same thing! The compiled assembly code will come the same between a struct and a class! (to be checked!)
Take any class and change the name to typedef struct ! You'll see that the code will still works the same!
class Client {
}
Client client(...);
=>
typedef struct Client {
....
} Client;
Client client(...);
If you do that all will works the same! At least i know that does in gcc!
YOu can test! In your platform!
I'm trying to make an efficient "entity system" in C++, I've read a lot of blog/articles/documentation on the Internet to get lot of information but I've got some questions again.
I've find two interesting subjects:
Data-driven system
Entity component system
For me, the two systems look very similar.
So, I've found this example by Adam Smith: https://stackoverflow.com/a/2021868
I need to have a flexible system like this:
// Abstract class
class Component
{
// data here
}
// exemple
class Car : public Component
{
// Data here
}
// Entity with components
class Entity
{
std::vector<Component*> components;
}
So, if my entity have the followings components: Car, Transform, Sprite,
did my components array will had linear data like data-driven system?
Now, I have Systems:
class System
{
virtual void init();
virtual void clear();
virtual void update();
std::unordered_map< const char*, Entity*> entities;
}
class RendererSystem : public System
{
// Methods's definition (init, clear, …).
void update()
{
for( entity, … )
{
Sprite* s = entity->getComponent('sprite');
...
}
}
}
I've read that virtual functions are bad, it's bad in that case?
Get component need a static_cast, that's bad?
In data-driven system, I saw pointer everywhere, si where is the "original" variables, I need to put new everywhere or I will have a class with an array of same data?
Did I make this right?
All this points look "blur" in my mind.
Virtual functions do have some overhead but nothing that you should care about unless you are doing millions of calls per second so just ignore that fact.
A static cast is not bad by itself but it breaks static type checking where it is used so if you can move the behavior inside the object on which you cast so that you just call the appropriate method without having to know the specific runtime instance of an object then it's better
It's not clear what you are asking, even if you have vectors of element in a data-driven approach, each element in the collections needs to be allocated with a new (if it's a pointer). Then once you allocated it you won't need to do it again as soon as you will pass the reference to the item around
//////////////////////////////////////////////////////////////////////////////////////////
// Note: Automatically generate getter and setter
template<typename T>
class Wrap {
public:
...
const T& operator()() const
{
return m_element;
}
void operator()(const T& element)
{
m_element = element;
}
...
private:
T m_element;
};
// Pro: The container may have more than 20 different member variables.
// Each goes with a simple getter and setter for now. Due to the Wrap
// class, we don't have to add getter and setter for any new variable
// Con: Since this is a public API interface, if the user directly adopt the
// Wrap class, it is difficult for any future improvement. Based on this design,
// we cannot make Wrap private embeded class of Container since the user needs to
// access those public member variables of Container
class Container
{
public:
Wrap<int> Age;
Wrap<double> Balance;
...
};
//////////////////////////////////////////////////////////////////////////////////////////
// Con: For each different member variable, we have to add getter and setter methods
// which will be a problem considering if you have 20 member variables.
// Pro:
// By using PIMPL pattern, we can make the interface more robust for future improvement
// without breaking our client's code.
class PimplClass
{
public:
int Age() const;
PimplClass& Age(int _age);
double Balance() const;
PimplClass& Balance(double _balance);
private:
Pimpl* m_data; // hide internal data structure from the public API interface
};
//////////////////////////////////////////////////////////////////////////////////////////
Question> Is there a better design that I can combine both auto getter+setter generation and PIMPL design pattern
into this public API interface?
Thank you
// ****** Updated ************
After reading all those articles, I am convinced that getter and setter are evil. Now the question comes to how to avoid them all together.
For example,
class Bond
{
...
private:
long m_lPrice;
std::string m_strBondName;
int m_iVolume;
}
Give the above class Bond which includes three member variables, without using getter and setter, how does client get the price, name, or volume of an bond object?
This is the another example of getter/setter in Qt4.
Here's the improved QProgressBar API:
class QProgressBar : public QWidget
{
...
public:
void setMinimum(int minimum);
int minimum() const;
void setMaximum(int maximum);
int maximum() const;
void setRange(int minimum, int maximum);
int value() const;
virtual QString text() const;
void setTextVisible(bool visible);
bool isTextVisible() const;
Qt::Alignment alignment() const;
void setAlignment(Qt::Alignment alignment);
public slots:
void reset();
void setValue(int value);
signals:
void valueChanged(int value);
...
};
Thank you
Getters and setters are there so that you can "grab" into an object's guts and fiddle with its innards. That should make your alarm bells ring very loudly. For a well-designed class, you do not have to dig through its guts, since it lets you do everything you need to do through its interface without leaking any of its implementation details through the abstraction.
Design a class from the point of view of a user of the class ("if I have a qrxl object, I would need to make it wrgl() like this, and I also need to pass it a lrxl object occasionally, which it then uses to do frgl()"), rather than from the point of view of the implementer who needs to somehow organize his data and algorithms into useful (for him!) chunks. ("Let's just put this Johnny over here into that class, because that's where it is close to where I need it for implementing the xrxl() algorithm.")
I think in this regard Java has done a huge disservice to humanity in that it requires you to put everything into some class, even if this is against how you actually visualize your design in your head, and even if you are not (yet) thinking object-oriented. This seems to have made a design style en vogue where programmers just stuff everything into some class somewhere because "that's the way it's done."
In lots of Java code I've seen the underlying programming style is actually Structured Programming (basically "collect your data in useful chunks, and pass those to your algorithms", as done in C or Pascal), rather than Object-oriented Programming. Just because you replace struct/record by class and make the data members in this chunk only accessible through getters and setters, this doesn't mean you are doing object-oriented programming.1 This is what the author of that wonderful short paper calls pseudo classes
From what little I know about Qt, its design is also a pretty good example for a pretty bad example, with everything allocated on the heap, handed around in naked pointers, and employing the quasi-class school of design.
Give the above class Bond which includes three member variables, without using getter and setter, how does client get the price, name, or volume of an bond object?
This is the wrong question. The right question is why would a user need to get at those values? If you need to get at them manually, then Bond isn't high enough an abstraction for OO design, it's a mere C-style struct where you throw together all the data you need in one place. Ask yourself:
What would a user of a Bond want to do with such an object? How can I make the class support those operations without users having to grab into it and fiddle with its guts? How can I make the classes that interact with Bond do this? Can I pass them Bond objects, rather than price, name, or volume of an bond object?
Yes, sometimes you have to have just a bond's price in order to display it, and if that's the case, then Bond will need to support a getter function for the price, and that's Ok then. But you could still pass a Bond object to your BondPriceTable's displayBonds() function, and let that decide whether it wants to just grab the name and the price and throw that at the screen or display more values. There is no need to extract name and price manually and pass those to a display() function.
1 That's especially appalling because Java aficionados so often look down at C++ for not being "purely OO".
Here is my code:
class Soldier {
public:
Soldier(const string &name, const Gun &gun);
string getName();
private:
Gun gun;
string name;
};
class Gun {
public:
void fire();
void load(int bullets);
int getBullets();
private:
int bullets;
}
I need to call all the member functions of Gun over a Soldier object. Something like:
soldier.gun.fire();
or
soldier.getGun().load(15);
So which one is a better design? Hiding the gun object as a private member and access it with getGun() function. Or making it a public member? Or I can encapsulate all these functions would make the implementation harder:
soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()
So which one do you think is the best?
I would say go with your second option:
soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()
Initially it's more work, but as the system gets more complex, you may find that a soldier will want to do other things before and after firing their gun (maybe check if they have enough ammo and then scream "Die suckers!!" before firing, and mutter "that's gotta hurt" after, and check to see if they need a reload). It also hides from the users of the Soldier class the unnecessary details of how exactly the gun is being fired.
First off, you'd be violating the Law of Demeter by accessing the Gun from outside the Soldier class.
I would consider methods like these instead:
soldier.ArmWeapon(...);
soldier.Attack(...);
This way you could also implement your fist, knife, grenade, baseball bat, laser cat, etc.
The Law of Demeter would say to encapsulate the functions.
http://en.wikipedia.org/wiki/Law_of_Demeter
This way, if you want some type of interaction between the soldier and the gun, you have a space to insert the code.
Edit: Found the relevant article from the Wikipedia link:
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
The paperboy example is very, very similar to the soldier example you post.
Indeed, it depends a lot about how much control you want to have.
To model the real world, you might even want to completely encapsulate the gun object, and just have a soldier.attack() method. The soldier.attack() method would then see whether the soldier was carrying a gun, and what the state of the gun was, and fire or reload it as necessary. Or possibly throw the gun at the target and run away, if insufficient ammunition were present for either operation...
If you expose gun, you allow things beyond the member functions of the Gun, which is probably not a good idea:
soldier.gun = anotherGun; // where did you drop your old gun?
If you use getGun(), the calls look a little ugly, but you can add functions to Gun without modifying Soldier.
If you encapsulate the functions (which I recommend) you can modify the Gun or introduce other (derived) classes of Gun without changing the interface to Soldier.
Usually my decision is based on the nature of the container class (in this case, Soldier). Either it is entirely a POD or is not. If it's not a POD, I make all data members private and provide accessor methods. The class is a POD only if it has no invariants (i.e. there is no way an external actor can make its state inconsistent by modifying its members). Your soldier class looks more like a non-POD to me, so I would go to the accessor method option. If it would return a const reference or a regular reference is your own decision, based on the behaviour of fire() and the other methods (if they modify gun's state or not).
BTW, Bjarne Stroustrup talks a little about this issue in his site:
http://www.artima.com/intv/goldilocks3.html
A sidenote: I know that's not precisely what you asked, but I'd advice you to also consider the many mentions made in other answers to the law of Demeter: to expose action methods (that act on gun) instead of the entire gun object via a getter method. Since the soldier "has" the gun (it is in his hand and he pulls the trigger), it seems more natural to me that the other actors "ask" the soldier to fire. I know this may be tedious if gun has many methods to act on, but maybe also these could be grouped in more high-level actions that the soldier exposes.
Provide a "getGun()" or simply "gun()".
Imagine one day you may need to make that method more complex:
Gun* getGun() {
if (!out_of_bullets_) {
return &gun_;
} else {
PullPieceFromAnkle();
return &secret_gun_;
}
}
Also, you may want to provide a const accessor so people can use a const gun on a const soldier:
const Gun &getGun() const { return gun_; }
There's no golden rule that applies 100% of the time. It's really a judgement call depending on your needs.
It depends on how much functionality you want to hide/disallow for the gun from access to the Solider.
If you want to have only read only access to the Gun you could return a const reference to your own member.
If you want to expose only certain functionality you could make wrapper functions. If you don't want the user to try to change Gun settings through the Soldier then make wrapper functions.
Generally though, I see the Gun as it's own object and if you don't mind exposing all of Gun's functionality, and don't mind allow things to be changed through the Soldier object, just make it public.
You probably don't want a copy the gun so if you make a GetGun() method make sure that you aren't returning a copy of the gun.
If you want to keep your code simple then have the soldier responsible for dealing with the gun. Does your other code need to work with the gun directly? Or can a soldier always know how to work/reload his own gun?
Encapsulate the functions to provide a consistent UI even if you later change the logic. Naming conventions are up to you, but I normally don't use "getFoo()", but just "foo()" as accessors and "setFoo()" as setters.
return reference-to-const when you can (Effective C++ Item #3).
Prefer consts, enums, and inlines to using hard coded numbers (Item #4)
provide unique naming conventions for your private members to distinguish them from arguments
Use unsigned values where they make sense to move errors to compile time
When const values, like maximums, apply to an entire class. Make them static.
If you plan to inherit, make sure your destructors are virtual
initialize all members to sane defaults
This is how the classes look after that. CodePad
#include <iostream>
#include <string>
#include <stdint.h>
using namespace std;
class Gun
{
public:
Gun() : _bullets(0) {}
virtual ~Gun() {}
void fire() {cout << "bang bang" << endl; _bullets--;}
void load(const uint16_t bullets) {_bullets = bullets;}
const int bullets() const {return _bullets;}
static const uint16_t MAX_BULLETS = 17;
protected:
int _bullets;
};
class Soldier
{
public:
Soldier(const string &name, const Gun &gun) : _name(name), _gun(gun) {}
virtual ~Soldier() {}
const string& name() const;
Gun& gun() {return _gun;}
protected:
string _name;
Gun _gun;
};
int main (int argc, char const *argv[])
{
Gun gun; // initialize
string name("Foo");
Soldier soldier(name, gun);
soldier.gun().load(Gun::MAX_BULLETS);
for(size_t i = 0; i < Gun::MAX_BULLETS; ++i)
{
soldier.gun().fire();
cout << "I have " << soldier.gun().bullets() << " left!" << endl;
}
return 0;
}