Is it good practice to create functions to access class variables? - c++

As the title says: Is it good practice to create functions to access class variables?
I have seen quite a number of pieces of code that do something like the following:
class MyClass {
public:
void setx(int a);
void sety(int b);
int read_x;
int read_y;
private:
int x;
int y;
};
void MyClass::setx(int a) {
x=a;
}
void MyClass::sety(int b) {
y = b;
}
int MyClass::read_x() {
return x;
{
int MyClass::read_y() {
return y;
}
So rather than accessing variables directly(MyClass.x) they use functions to read and set the variable values etc.
Is this a standard or good practice?

Yes, accessor functions are preffered to direct member access for several reasons. They provide a unique access point, are easier to track and to debug.
For example, instead of setting a breakpoint everywhere in the code where MyClass.x is changed, you can just set a single breakpoint in MyClass::setX().
However, although better than direct member access, accessor methods are not without their drawbacks, if misused. For details, you can visit Getters and Setters are bad OO design?

Rather than access variables directly? Absolutely. Creating a programmatic interface layer decouples you from the implementation details of those internal variables themselves. You then afford yourself additional flexibility for things like creating mocked-out implementations of the class in question (for testing), creating proxy classes (for decorated functionality like logging, etc.)
I'd warn against automatically creating them for everything where you may not need them. But that's a different issue.
Much like working out at the gym: It gives back more than it takes ;)

Yes they are ok, however I would also say that you should keep your classes small than you would with say Java and what not so you don't end up with types that are mostly getters and setters.
Typically a class holds a (ideally single) state (which can be got if needed) and has an implementation which should ideally remain private.

This is important as it separates the interface of the class from the underlying data model. You often see basic code like the example you posted, and at first, a lot of it can seem like an unnecessary complication. However, it provides a (self documenting) framework where the implmentation of the object can be changed without breaking code that accesses the objects of the class via the defined interface.

Related

Writing many void methods in a c++ class, and keeping track of variable changes

I am a bit new to C++ having come from a very moderate C background so please excuse me if this question seems very elementary.
I have currently been given some C++ source code to read and modify.
However the code seems to me to be very ugly for a newbie but I am not sure whether the code is considered good C++ practice.
Basically there is only one class called STORAGE and all the information is public.
class STORAGE
{
public:
STORAGE();
virtual ~STORAGE();
//DATA
int np,nn;
int istep;
int print_step;
//...and many more variables.
//METHODS
void eos(double rho, double e, double &p, double &cs);
void ThermalEnergy(double rho,double &e,double p);
void allocation();
void initialization();
void var_dt();
// and many more methods which return void,
};
Now when I am reading the algorithm which calls these methods, I see each of them modifying many member variables of STORAGE, with many methods modifying the same set of variables, in a long list of method calls. Many of the methods are quite irritatingly of the type void A ()
With such a style , it seems to be very hard to keep track mentally of the changes to the large number member-variables.
My question: Is this style of programming common to C++ when using classes? Giving a method access to all members of the class seems a bit dangerous, and it seems that a lot of buggy code could arise.
Psychologically for me it looks much more simpler to write code, if I know that the only variables being modified in a function call are the input variables to a function.
"..all the information is public"
Yes, it it bad practice and contradicts the basic notion of encapsulation. Everybody outside the class, would be able see and modify all the members. Ideal is: to make the data members private, and provide public get/set methods (depending on need).
"Is this style of programming common to C++ when using classes?" -- Common but not good.
"Giving a method access to all members of the class seems a bit dangerous"
I think this is common, member functions should have access to member variables. Otherwise, who else will :) ? However, if you still want to prevent them to modify member variables, you can use the declare the function as const. (This approach is already described by Connor above).

Missing convention for C++ accessors?

I've read the community wiki quetion about the 3 different conventions for accessor methods and was supmetwhat surprised not to see the following convention:
const unsigned& amount() const { return _amount; }
unsigned& amount() { return _amount; }
true, it's not quite the same as seamless as being able to avoid the parentheses altogether () - which would (I feel) be idea - but it's still something; right?
It defeats the purpose of accessors. If you provide the two
functions, you might as well make the data member public and be
done with it.
EDIT:
Just to make things perfectly clear: there are cases where
using a C style struct is the most appropriate solution. In
those cases, you make the data members public, and don't worry
about accessors. For classes with significant behavior, on the
other hand, you won't have accessors at all, or very few. For
the most part, the internal state is not reflected directly at
the public interface (and that state which is is usually read
only). About the only time you'd have need for accessors is for
classes which are basically data, but which must enforce
invariants across the data,
(And for what it's worth: if the data is logically an attribute
of the class, I use:
int amount() const { return myAmount; }
void amount( int newValue ) { myAmount = newValue; }
For getters of values which are not logically attributes,
however, I'll use getAmount().)
The second of your examples gives the user access to the original _amount in the class, without any form of protection from the class itself. The purpose of "encapsulation", which is an important aspect of OOP is to ensure that all the accesses to a variable is done within the class itself - that way the class can control the value range or other validity.
If you want the class to transparently allow the user to use amount, then call it amount and make it public. There is no need for accessor functions then.
The problem with this is that it can defeat the purpose of a getter/setter convention. If you're passing a mutable reference to the private member, you might as well expose the member and remove the hassle of function calls.
Also, I found this syntax very ugly and unreadable, but that's my personal taste:
foo.amount() = 23;

Should I use public or private variables?

I am doing a large project for the first time. I have lots of classes and some of them have public variables, some have private variables with setter and getter methods and same have both types.
I decided to rewrite this code to use primarily only one type. But I don't know which I should use (variables which are used only for methods in the same object are always private and are not subject of this question).
I know the theory what public and private means, but what is used in the real world and why?
private data members are generally considered good because they provide encapsulation.
Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.
You'll notice this during debugging. If it's private, you know you can only modify the variable inside the class. If it's public, you'll have to search the whole code-base for where it might be modified.
As much as possible, ban getters/setters and make properties private. This follows the principle of information hiding - you shouldn't care about what properties a class has. It should be self-contained. Of course, in practice this isn't feasible, and if it is, a design that follows this will be more cluttered and harder to maintain than one that doesn't.
This is of course a rule of thumb - for example, I'd just use a struct (equivalent with a class with public access) for, say, a simple point class:
struct Point2D
{
double x;
double y;
};
Since you say that you know the theory, and other answers have dug into the meaning of public/private, getters and setters, I'd like to focus myself on the why of using accessors instead of creating public attributes (member data in C++).
Imagine that you have a class Truck in a logistic project:
class Truck {
public:
double capacity;
// lots of more things...
};
Provided you are northamerican, you'll probably use gallons in order to represent the capacity of your trucks. Imagine that your project is finished, it works perfectly, though many direct uses of Truck::capacity are done. Actually, your project becomes a success, so some european firm asks you to adapt your project to them; unfortunately, the project should use the metric system now, so litres instead of gallons should be employed for capacity.
Now, this could be a mess. Of course, one possibility would be to prepare a codebase only for North America, and a codebase only for Europe. But this means that bug fixes should be applied in two different code sources, and that is decided to be unfeasible.
The solution is to create a configuration possibility in your project. The user should be able to set gallons or litres, instead of that being a fixed, hardwired choice of gallons.
With the approach seen above, this will mean a lot of work, you will have to track down all uses of Truck::capacity, and decide what to do with them. This will probably mean to modify files along the whole codebase. Let's suppose, as an alternative, that you decided a more theoretic approach.
class Truck {
public:
double getCapacity() const
{ return capacity; }
// lots of more things...
private:
double capacity;
};
A possible, alternative change involves no modification to the interface of the class:
class Truck {
public:
double getCapacity() const
{ if ( Configuration::Measure == Gallons ) {
return capacity;
} else {
return ( capacity * 3.78 );
}
}
// lots of more things...
private:
double capacity;
};
(Please take int account that there are lots of ways for doing this, that one is only one possibility, and this is only an example)
You'll have to create the global utility class configuration (but you had to do it anyway), and add an include in truck.h for configuration.h, but these are all local changes, the remaining of your codebase stays unchanged, thus avoiding potential bugs.
Finally, you also state that you are working now in a big project, which I think it is the kind of field in which these reasons actually make more sense. Remember that the objective to keep in mind while working in large projects is to create maintainable code, i.e., code that you can correct and extend with new functionalities. You can forget about getters and setters in personal, small projects, though I'd try to make myself used to them.
Hope this helps.
There is no hard rule as to what should be private/public or protected.
It depends on the role of your class and what it offers.
All the methods and members that constitute the internal workings of
the class should be made private.
Everything that a class offers to the outside world should be public.
Members and methods that may have to be extended in a specialization of this class,
could be declared as protected.
From an OOP point of view getters/setters help with encapsulation and should therefore always be used. When you call a getter/setter the class can do whatever it wants behind the scenes and the internals of the class are not exposed to the outside.
On the other hand, from a C++ point of view, it can also be a disadvantage if the class does lots of unexpected things when you just want to get/set a value. People like to know if some access results in huge overhead or is simple and efficient. When you access a public variable you know exactly what you get, when you use a getter/setter you have no idea.
Especially if you only do a small project, spending your time writing getters/setters and adjusting them all accordingly when you decide to change your variable name/type/... produces lots of busywork for little gain. You'd better spend that time writing code that does something useful.
C++ code commonly doesn't use getters/setters when they don't provide real gain. If you design a 1,000,000-line project with lots of modules that have to be as independent as possible it might make sense, but for most normal-sized code you write day to day they are overkill.
There are some data types whose sole purpose is to hold well-specified data. These can typically be written as structs with public data members. Aside from that, a class should define an abstraction. Public variables or trivial setters and getters suggest that the design hasn't been thought through sufficiently, resulting in an agglomeration of weak abstractions that don't abstract much of anything. Instead of thinking about data, think about behavior: this class should do X, Y, and Z. From there, decide what internal data is needed to support the desired behavior. That's not easy at first, but keep reminding yourself that it's behavior that matters, not data.
Private member variables are preferred over public member variables, mainly for the reasons stated above (encapsulation, well-specified data, etc..). They also provide some data protection as well, since it guarantees that no outside entity can alter the member variable without going through the proper channel of a setter if need be.
Another benefit of getters and setters is that if you are using an IDE (like Eclipse or Netbeans), you can use the IDE's functionality to search for every place in the codebase where the function is called. They provide visibility as to where a piece of data in that particular class is being used or modified. Also, you can easily make the access to the member variables thread safe by having an internal mutex. The getter/setter functions would grab this mutex before accessing or modifying the variable.
I'm a proponent of abstraction to the point where it is still useful. Abstraction for the sake of abstraction usually results in a cluttered mess that is more complicated than its worth.
I've worked with complex rpgies and many games and i started to follow this rule of thumb.
Everything is public until a modification from outside can break something inside, then it should be encapsulated.(corner count in a triangle class for example)
I know info hiding principles etc but really don't follow that.
Public variables are usually discouraged, and the better form is to make all variables private and access them with getters and setters:
private int var;
public int getVar() {
return var;
}
public void setVar(int _var) {
var = _var;
}
Modern IDEs like Eclipse and others help you doing this by providing features like "Implement Getters and Setters" and "Encapsulate Field" (which replaces all direct acccesses of variables with the corresponding getter and setter calls).

In C++ can a class attributes - public,private or protected be set/changed at run-time?

Is it possible to change the class attribute at run-time in C++ language.For example as below :
class base
{
public:
//public members
private :
//private members
};
class derived1 : attribute base
{
public:
//public members
base::<base method name> //so that it an be made accessible from the main - outside the class.
private:
//private members
};
can the attribute-public,private,protected be changed at runtime, dynamically?
Rgds,
softy
It is the compiler that makes sure you don't access private members. Once the compiler finishes its work and the binary code is generated, all information regarding private-ness is lost.
So no, you can't change that in runtime.
I don't know why you would want this, but if you want some functions to be able to be called during some times, but not the others, you can have a variable defining whether they can be called or not. Then, on the top of that function:
int Class::function(...)
{
if (!function_is_allowed)
return OPERATION_NOT_ALLOWED;
...
}
No, the access level cannot be modified, although there are some hacks to go around them.
Refer to this answer - https://stackoverflow.com/a/6886432/673730
If what you're looking for is something similar to Java reflection, where you can access private members by modifying their access level at runtime, then no.
You cannot change the access modifiers of a class. End of story.
Disclaimer: There are hacks for just about everything, including this. Don't use them.
Based on your comments in the question when asked why you want this, it looks like what you're trying to do is control access to a class' run-time properties based on its other run-time properties. For example, maybe a Character's Powers are only accessible if Character's Level is >= 42.
This is not a technical question about the mechanics of C++ syntax, but a business logic question. You'll find the answer to this question in the design of your program and its algorithms -- not some technical C++ trick.
Classes are often used to model things. In your case, a character in a game. Maybe this character has a level and a list of powers (which I'll represent simply as strings).
In that case:
class Character
{
public:
int level_;
vector<string> powers_;
};
...is a simplistic representation of your character model. Now, if you want to control access to powers_ at run-time based on the value of level_, you can use an accessor method:
class Character
{
public:
int level_;
vector<string> Powers() const
{
if( level_ >= 42 )
return powers_;
else
return vector<string>();
}
private:
vector<string> powers_;
};
Now you can only get to the character's powers if the character is of sufficiently high level.
This is still a highly simplistic example, and the above code is not production quality. However, the idea is there -- when implementing your program's business logic, your focus should be on the algorithms you write much more than the technicalities of C++, or whatever language you're using.

C++ should all member variable use accessors and mutator

I have about 15~20 member variables which needs to be accessed, I was wondering
if it would be good just to let them be public instead of giving every one of them
get/set functions.
The code would be something like
class A { // a singleton class
public:
static A* get();
B x, y, z;
// ... a lot of other object that should only have one copy
// and doesn't change often
private:
A();
virtual ~A();
static A* a;
};
I have also thought about putting the variables into an array, but I don't
know the best way to do a lookup table, would it be better to put them in an array?
EDIT:
Is there a better way than Singleton class to put them in a collection
The C++ world isn't quite as hung up on "everything must be hidden behind accessors/mutators/whatever-they-decide-to-call-them-todays" as some OO-supporting languages.
With that said, it's a bit hard to say what the best approach is, given your limited description.
If your class is simply a 'bag of data' for some other process, than using a struct instead of a class (the only difference is that all members default to public) can be appropriate.
If the class actually does something, however, you might find it more appropriate to group your get/set routines together by function/aspect or interface.
As I mentioned, it's a bit hard to tell without more information.
EDIT: Singleton classes are not smelly code in and of themselves, but you do need to be a bit careful with them. If a singleton is taking care of preference data or something similar, it only makes sense to make individual accessors for each data element.
If, on the other hand, you're storing generic input data in a singleton, it might be time to rethink the design.
You could place them in a POD structure and provide access to an object of that type :
struct VariablesHolder
{
int a;
float b;
char c[20];
};
class A
{
public:
A() : vh()
{
}
VariablesHolder& Access()
{
return vh;
}
const VariablesHolder& Get() const
{
return vh;
}
private:
VariablesHolder vh;
};
No that wouldn't be good. Image you want to change the way they are accessed in the future. For example remove one member variable and let the get/set functions compute its value.
It really depends on why you want to give access to them, how likely they are to change, how much code uses them, how problematic having to rewrite or recompile that code is, how fast access needs to be, whether you need/want virtual access, what's more convenient and intuitive in the using code etc.. Wanting to give access to so many things may be a sign of poor design, or it may be 100% appropriate. Using get/set functions has much more potential benefit for volatile (unstable / possibly subject to frequent tweaks) low-level code that could be used by a large number of client apps.
Given your edit, an array makes sense if your client is likely to want to access the values in a loop, or a numeric index is inherently meaningful. For example, if they're chronologically ordered data samples, an index sounds good. Summarily, arrays make it easier to provide algorithms to work with any or all of the indices - you have to consider whether that's useful to your clients; if not, try to avoid it as it may make it easier to mistakenly access the wrong values, particularly if say two people branch some code, add an extra value at the end, then try to merge their changes. Sometimes it makes sense to provide arrays and named access, or an enum with meaningful names for indices.
This is a horrible design choice, as it allows any component to modify any of these variables. Furthermore, since access to these variables is done directly, you have no way to impose any invariant on the values, and if suddenly you decide to multithread your program, you won't have a single set of functions that need to be mutex-protected, but rather you will have to go off and find every single use of every single data member and individually lock those usages. In general, one should:
Not use singletons or global variables; they introduce subtle, implicit dependencies between components that allow seemingly independent components to interfere with each other.
Make variables const wherever possible and provide setters only where absolutely required.
Never make variables public (unless you are creating a POD struct, and even then, it is best to create POD structs only as an internal implementation detail and not expose them in the API).
Also, you mentioned that you need to use an array. You can use vector<B> or vector<B*> to create a dynamically-sized array of objects of type B or type B*. Rather than using A::getA() to access your singleton instance; it would be better to have functions that need type A to take a parameter of type const A&. This will make the dependency explicit, and it will also limit which functions can modify the members of that class (pass A* or A& to functions that need to mutate it).
As a convention, if you want a data structure to hold several public fields (plain old data), I would suggest using a struct (and use in tandem with other classes -- builder, flyweight, memento, and other design patterns).
Classes generally mean that you're defining an encapsulated data type, so the OOP rule is to hide data members.
In terms of efficiency, modern compilers optimize away calls to accessors/mutators, so the impact on performance would be non-existent.
In terms of extensibility, methods are definitely a win because derived classes would be able to override these (if virtual). Another benefit is that logic to check/observe/notify data can be added if data is accessed via member functions.
Public members in a base class is generally a difficult to keep track of.