The question is simple: Is it unnecessary to call getters inside setters to have access to an object's member variables? Suppose that all the getters are inline
d and return const
references to members.
As an example:
class Foo
{
public:
inline const std::uint32_t& getValue( ) const noexcept
{
return m_value;
}
inline const std::uint32_t& getBar( ) const noexcept
{
return m_bar;
}
void setValue( const std::uint32_t value )
{
m_value = value * getBar() * 3; // vs m_value = value * m_bar * 3;
}
private:
std::uint32_t m_value;
std::uint32_t m_bar;
};
Which one is more idiomatic? I think there should be no difference in the generated code by the compiler. But in terms of readability, they're a bit different. What could be the benefits of using getters instead of directly typing e.g. m_bar
?
CodePudding user response:
Code in the class always has full acess to the internal data members (and member functions too). So it is not necessary. My thoughts on if you should do it
- if the getters and particularly setters have side effects (imagine you keep a count of how many times a particular value is changed, or validate a value) then you should call them
- the overhead when compiled for release will disappear since the compiler can see that you are just reading or writing the value (if they are simple read and write get/set)
- you might get into the habit of always calling them just in case you later want them to have side effects
note I dont say whats 'best', just things to take into account