Using Get() and Set() instead of accessing the variable directly



Is it better to access the variable using Set() and Get() methods, rather
than accessing the variable directly?

I suppose I learned early on to access variables directly, instead of using
Set() and Get() methods.
It was easier for simple stuff, but it caught up with me as I progressed
further.
Now, I feel as though accessing variables directly is just bad practice.

An example would be that even within the same class,
I can access private/protected variables, but when I divide up the class
into manageable parts,
I often have to add Get() and Set() methods anyways.

private:
int m_x;
int m_y;
inline void SetX(int NewX){ m_x = newX;} //inlined
inline int GetX(){ return m_x; } //inlined
public:
inline void SetY(int NewY){ m_y = newY;} //inlined
inline int GetY(){ return m_y; } //inlined


void SomeClass::SomeFunc()
{
m_y = 3; //Bad
SetY(3); //Good
m_x = 1; //Bad
SetX(1); //Good
}

I don't know if it really saves any time or not?
I don't know if the compiler treats it as accessing the variable directly or
not?
Maybe you can clear that up for me.

I just think it is just better practice to use Set() and Get() methods for
each variable even if they are only accessed within the same class.

Thoughts, Opinions?


.



Relevant Pages

  • Re: Valid C syntax.
    ... int  a,b,c; ... You should not over-think what the compiler will do. ... to specifications. ... In practice, I would accomplish the above in two statements if there ...
    (comp.lang.c)
  • Re: Using Get() and Set() instead of accessing the variable directly
    ... A common misconception is that efficiency is an issue. ... I feel as though accessing variables directly is just bad practice. ... I can access private/protected variables, but when I divide up the class ... int m_x; ...
    (microsoft.public.vc.mfc)
  • Re: Using Get() and Set() instead of accessing the variable directly
    ... void SetY(int NewY) { ... I can access private/protected variables, but when I divide up the class into manageable parts, ... int m_x; ... I just think it is just better practice to use Setand Getmethods for each variable even if they are only accessed within the same class. ...
    (microsoft.public.vc.mfc)
  • Re: Does casting lvalue lead to Undefined Behaviour ?
    ... int main ... unsigned char buff; ... and in this case the problem does occur in practice. ... My compiler does not produce any diagnostics for the above ...
    (comp.lang.c)
  • Re: real newbie question on pointers
    ... This is also very old C practice, ... Below, because of sloppy braces, you have a function definition ... mac osx 10.4.11 tiger gcc compiler in terminal. ... int main ...
    (comp.lang.c.moderated)