Answer the question
In order to leave comments, you need to log in
OOP of the brain?
Do you think it's okay for a class to expose its fields to the public?
After all, sometimes getters and seters are just extra pieces of code.
For example, here is a class (for example, let it represent a variable in the code of some interpreter):
class Variable
{
private:
std::string Name;
public:
std::string Value;
std::string GetName() const
{
return Name;
}
Variable ( const std::string &name ): Name( name )
{
};
}
class Variable
{
private:
std::string Name;
std::string Value;
public:
std::string GetName() const
{
return Name;
}
std::string GetValue() const
{
return Value;
}
void SetValue ( const std::string &value )
{
Value = value;
}
Variable ( const std::string &name ): Name( name )
{
};
}
Answer the question
In order to leave comments, you need to log in
When you write a lab or your own little project, you can do whatever you want.
Now imagine a situation when in a team of programmers you wrote a class with public variables, and then the project manager came up and said that for each assignment of a variable, you need to make an entry in the log file. Now all the programmers who used your class rewrite the code from variables to setters instead of work.
I advise you to read "Perfect Code", so as not to ask such questions.
Well, you don’t fly from the Russian Federation to Europe through Australia?)
Why do something like this when it’s clearly not necessary ?!
There are internal class variables that serve for internal calculations, and there are precisely those that serve to set properties to a class object without unnecessary actions (otherwise: in the simplest case - a getter / setter, in a more complex one - a named method).
If this class does not stick out to the public api and only you will use it - it's fine
With open fields, you can only do some structure like std::pair, which, for example, is returned from somewhere as a result (for example, this is the result of calculations and some tag) or which is used only within one class or just in one cpp file as an auxiliary, but no where else.
In other cases, encapsulation is always normal, otherwise it will be bad later and you will suffer. Imagine a situation with a large project, when you need to simply put a break and see who and when changed the value of a field. Or, for example, add any logic before setting/getting values (at least banal notifications).
Just make it a rule to encapsulate and that's it. Pressing a couple of buttons to generate methods is better than suffering later.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question