Daily DRY Tip

May 17, 2008 at 9:36 am Leave a comment

Today’s DRY tip gives up some to gain some.

Let’s look at the problem at hand :

class CArbitrary
{
  public:
   CArbitrary()
   : mv_Value( 0. )
   {}
  private:
    double  mv_Value ;
};

Have you spotted the DRY-violation?
It’s in this line : mv_Value( 0. )

The literal 0. is a double, and the member variable mv_Value is also a double. So, you’re repeating yourself, definitely a DRY-violation.

A solution to this problem is calling the default ctor of your member variable explicitly.

Like so :

class CArbitrary
{
  public:
   CArbitrary()
   : mv_Value()
   {}
  private:
    double  mv_Value ;
};

This does not feature a literal of type double, but does initialize the member to 0.
Now where did we give up DRY-ness?
Suppose our class was a template.

template
class CArbitrary
{
  public:
   CArbitrary()
   : mv_Value()
   {}
  private:
    at_ValType  mv_Value ;
};

We are now forced to call the default ctor of our member variable explicitly although C++ would call it automatically…for non-built-in types. And that’s the dilemma we’re facing. Not writing the member default ctor would make this template behave differently for built-in vs. custom types. But writing it also makes us repeat the name of our member variable, and we don’t like to repeat ourselves. One reason for not wanting to do this is in case you would add other member variables. You’d have to remember to also change the ctor to include the extra member default ctors.

template
class CArbitrary
{
  public:
   CArbitrary()
   : mv_Value()
   {
      // oops, mv_ExtraValue not initialized 
      // if at_ValType == built-in type    
   }
  private:
    at_ValType  mv_Value ;
    at_ValType  mv_ExtraValue ;   
};
Advertisements

Entry filed under: Truly important stuff.

Daily DRY Tip The market is flooded with mini laptops

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

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Categories


%d bloggers like this: