Re: Using Get() and Set() instead of accessing the variable directly
- From: Joseph M. Newcomer <newcomer@xxxxxxxxxxxx>
- Date: Tue, 20 Mar 2007 12:35:13 -0500
Get and Set are felt to be cleaner. They decouple the semantics from the representation.
A common misconception is that efficiency is an issue. It isn't even in the discussion
unless this is done in an inner loop, and then all you have to do is move the body of the
set or get method to the class definition and it compiles as efficiently as an assignment
statement, so at that point the discussion of performance becomes irrlevant.
All you need to do to answer the question is generate a listing (in release mode only) and
see what it does.
joe
On Tue, 20 Mar 2007 09:47:31 -0700, "Nobody" <Nobody@xxxxxxxxx> wrote:
Is it better to access the variable using Set() and Get() methods, ratherJoseph M. Newcomer [MVP]
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?
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.
- Follow-Ups:
- References:
- Prev by Date: Re: http://forums.microsoft.com/MSDN/
- Next by Date: Re: CreateProcess leaves child windows on rear
- Previous by thread: Re: Using Get() and Set() instead of accessing the variable directly
- Next by thread: Re: Using Get() and Set() instead of accessing the variable directly
- Index(es):
Relevant Pages
|