My Software Notes

Useful things I discover

Replacing Constructors with Object Initializers

leave a comment »

I was refactoring a class (in C#)  that had gotten big and messy and I realized that several of the static “factory-ish” methods that returned an instance of the class type were really not needed.  I call them “factory-ish” because they looked like they were doing the job you’d expect of a factory method (return a specific instance of a parent type based on a selector value) but what was really going on inside was simply passing a lookup value to a constructor and returning the object.  There was no hierarchy just instances of the same class.  The factory-ish methods all looked like this:

public static Thing FindByLookupValueA(string lookupA)
{
    var thing = new Thing(lookupA);
    thing.Load();
    return thing;
}

There were five methods like this.  They had grown over the years one by one, like warts on your neck just below the collar so you don’t notice them.  There were also constructors matching these static methods.  It just seemed unnecessary.

So I began replacing the static methods with calls to constructors.  At first I used the existing constructors like “Thing(int lookup)”, “Thing(string lookup)”, etc.  Then I thought, “wait a minute!”.  All those constructors did was:

public Thing(string lookupA) : this()
{
    LookupA = lookupA:
}

What a waste of typing.

If all a constructor does is set values on properties and nothing else – no calculations, no special initialization, no nothing – then it doesn’t need to exist.  Use an object initializer instead:

var thing = new Thing() {  LookupA = lookupA  };

Simple as that.

Doing it this way I got rid of five static methods and three constructors.  That’s eight unnecessary public API members of the class gone.  Simplicity rules!

KISS!

Advertisements

Written by gsdwriter

June 3, 2009 at 1:15 pm

Posted in Languages

Tagged with ,

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: