Archived

This topic is now archived and is closed to further replies.

Best way to change variables

This topic is 5590 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is it better to change a class'' variable value directly from another module or would it be better to call a method in that class which does the changing of that variable? E.g.
  
In input.cpp:

ball->ball_x = 1.0f;  // ball is an instance of class Ball

  
Or is it better to call a method in ball.cpp:
  
In ball.cpp:

void Ball::changeVariable(float f)
{
    ball_x = f;
}
  
In input.cpp: ball->changeVariable(1.0f); [/source] BTW, I haven''t tested this code so apologies if I''ve made a mistake.

Share this post


Link to post
Share on other sites
The generally accepted idiom is to make all data private in the class, and provide accessors/mutators(getters/setters) to access the data. If these methods are trivial, they should be inlined automatically by the compiler and there will be no loss of performance, whilst maintaining encapsulation.
Some languages even formalize this pattern, through a special syntax for properties. C# example:

  
public Color BackgroundColor
{
get{ return this.backgroundColor; }
set{ this.backgroundColor = value; }
}

If the class is little more than an aggregation of data, like f.ex a Point or a Vector3D, it can be considered acceptable to make the data public.
Further reading: http://www.cuj.com/experts/1902/hyslop.htm?topic=experts


"We should always be disposed to believe that that which appears white is really black, if the hierarchy of the Church so decides."

Ignatius Loyola, founder of the Jesuits

Share this post


Link to post
Share on other sites