Skip navigation

I’m one of those programmers who HATES it when he sees things like:


public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get
    {
      return m_hp ;
    }
    set
    {
      m_hp = value ;
    }
  }
}

Encapsulation or no encapsulation, this just SEEMS dumb.

Sometimes you’ll see this written as:


public class Grunt
{
  private int m_hp ;

  public int HP
  {
    get { return m_hp ; }
    set { m_hp = value ; }
  }
}

Which further proves my point: You can compress code like that when its not meant to be looked at.

The point is, THERE IS NO POINT in having pass-thru getters/setters like this.

In languages other than C#, you’ll see people using functions of course instead of C# properties.


class Grunt
{
private:
  int m_hp ;

public:
  void ChangeHp( int toVal )
  {
    m_hp = toVal ;
  }

  int Hp()
  {
    return m_hp ;
  }
} ;

VERSUS:


class Grunt
{
public:
  int hp ;
} ;

Isn’t there a very slight performance hit for writing code that always uses methods? Yes. ++points for public members.

HOWEVER. Recently I have thought of ONE major benefit to this “methods only/no public members” style that I never really credited to the style before.

Readability.

Think of client code using the Grunt class:


Grunt g ;

if( g.Hp() > 10 )
{
  g.ChangeHp( 12 ) ;
}

VERSUS:


Grunt g ;

if( g.hp > 10 )
{
  g.hp = 12 ;
}

What reads better? g.ChangeHp( 12 ) or g.hp = 12?

Really, g.hp = 12 ; LOOKS more cryptic because even though you know what its doing if you think about it for a fraction of a second, (changing hp to 12), for the method way g.ChangeHp(12) you CANNOT READ IT without knowing exactly what it does like, even faster than the one with the =.

SO. Maybe all private members and all accessor methods aren’t such a bad idea after all.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: