One of my favorite things about programming is also one of the most
frustrating things about programming. There's always more than one way
to solve a problem. Software developers are faced with many choices.
There is much to consider at every phase in the process. Efficiency,
deadlines, performance, maintainability and scalability are all
important topics to consider. So what criteria should you use to
choose the correct convention or pattern? I'm here to let you know,
there is no definitive answer (surprise). Also, this versus article is
not meant to declare a victor. I wanted to use this example to
illustrate my point on the choices developers have to make and the
criteria that affect those choices.
Let's take on lazy init first. Below is a simple class with a Names property.
Instead of initializing the list when the object is created,
initialization is delayed until the property is needed. The if block is there to protect against the creation of a new list every time you retrieve the Names property. Performance is the most common argument I hear for using lazy init. Performance is a very good reason to use lazy init.
As you can see, there is quite a bit going on for a simple object
initialization. At minimum, you need a field and a property, not to
mention the null object precaution. If you've been developing for a
while, it is easy to get in the habit of starting with optimized code.
Shouldn't the goal be to start simple and refactor as required? Is
this common convention needless complexity?
public class SimpleClass {
private IList<string> _names;
public IList<string> Names {
get {
if (_names == null) {
_names = new List<string>();
}
return _names;
}
}
public SimpleClass() {
}
}
And in this corner we have the challenger, constructor init. Using this approach, the Names property will be initialized when SimpleClass is initialized. One benefit of constructor init, as seen in the example below, is simplicity. There is no need for a field or an if
statement. What about performance? Performance is a valid concern but
it should be weighed against code efficiency. Simply put, a developer
has a lot less code to write when using constructor init. The need to optimize for performance may never arise. In fact, if lazy init improves your code's performance, you might have a problem with SRP (zing).
public class SimpleClass {
public IList<string> Names { get; private set; }
public SimpleClass() {
Names = new List<string>();
}
}
It's probably obvious that I prefer simplicity over complexity. I
acknowledge that complexity has its place in development and is
appropriate at times. I believe the priorities and factors that lead
to code complexity are an important and overlooked part of software
development. If you're not sure why you need it, maybe you don't. The
complex solution should answer the why.
Note: a similar comparison can be made for Service Locator and Constructor Injection but I will save that for another post.
Tags: process