• Blog
  • Services
    • Logo Design
    • Custom Development
    • Website Packages
    • Technology Consulting
  • Contact

Constructors vs. object initializers

Object initializer time vampire

The release of C# 3.0 brought the syntactic sugar of object initializers. I realize that this is dated and has been available for a long time; however, I continue to see bad patterns throughout my consulting career that make working with code difficult. This feature can cause nightmares for other developers and can wreak havoc on a code base when misused.

If you aren’t familiar with object initializers, they look like this:

var task = new Task
{
	Arguments = arguments,
	Created = DateTime.UtcNow
};

task.Start();

They look nicer and save time versus the old method of initializing objects (not using constructors):

var task = new Task();
task.Arguments = arguments;
task.Created = DateTime.UtcNow;
task.Start();

The issues begin once you start to talk about the intended usage of this class – especially as it pertains to a developer less familiar with the inner workings of this object. In this example, let’s assume I am a maintenance developer joining the project in progress. I want to use the Task class to start a scheduled task and capture information about it. Each of the poorly-written examples above do not help me determine what information is needed by the Task class before calling the Start() method. Is the Arguments property required before calling Start()? It is hard to tell without diving into the class and reading the code for myself.

The more classes in a project developed in this manner, the more complicated the code base will be to work with. It basically requires that each developer has a full understanding of the inner workings of all classes – a time vampire.

How do I avoid this issue?

In my opinion, the easiest way to prevent a code base from becoming unwieldy in this manner is through the repeated use of immutable objects and overloaded constructors – assuming the arguments parameter is needed for the construction of the class. Overloaded constructors help give developers the blueprint of a class by forcing the passing of parameters when initializing an object. It should require the parameters needed to construct the class properly. If I were to clean up our Task class in the example above, I would add a constructor like this:

public class Task
{
	public Task(string arguments)
	{
		this.Arguments = arguments;
		this.Created = DateTime.UtcNow;
	}

	public string Arguments { get; private set; }

	public void Start()
	{
		// use arguments to start the task
	}
	
	public void Stop()
	{
		// use arguments to store information about this task's process
	}
}

The constructor forces arguments to be passed in whenever creating the Task object. Additionally, note that I have marked the Arguments property with a private setter. This prevents the property from being manipulated outside of the Task class – making this class impossible to change once instantiated. Returning to our example, I’m a new developer to the team and would like to use this Task class – when creating a new instance, I’m given a hint as to what is needed for a Task to start properly. The code looks as follows:

var task = new Task(arguments);
task.Start();

This code looks much cleaner! Stay tuned for more…

Posted by Brian Lowry on June 6, 2014
Leave a comment

Leave a Comment

Click here to cancel reply.
You can use these HTML tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
  • Recent Posts

    • Understanding Entity Framework and Sql indexes June 30, 2014
    • Setup multiple SSL certificates on an Amazon EC2 instance using a VPC June 16, 2014
    • EF6.1 Mapping between types & tables (including derived/inherited types) June 10, 2014
    • Constructors vs. object initializers June 6, 2014
    • New WordPress redesign for LowryMedia.com! March 2, 2014
  • Subscribe to our technology blog
  • Subscribe to technology blog email updates:
  • © 2021 Lowry Media. All rights reserved.