Nov 27 2008

Lazy Init VS Constructor Init

Category: Software Developmentemilioc @ 01:18

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:

Nov 22 2008

Dependency Injection for the Compact Framework, Part 2

Category: Software DevelopmentJeff @ 00:18

Last week I wrote about my need for Dependency Injection for the Compact Framework.  Many DI frameworks do not support the Compact Framework, so I identified four options:

  1. Don't use IoC and dependency injection
  2. Continue to "roll-my-own" dependency injection tool
  3. Pray that Jeremy Miller ports StructureMap to the Compact Framework
  4. Use Ninject

Well, there is a fifth option that I hadn't considered: finding an open source project that does what I need.  Germán Schuager pointed me to a project he created on Google Code called Compact Container. It is lightweight, clean and simple.  After reviewing Germán's code, I found that it would support most of my needs, short of a couple of nice-to-have features.

  1. Marking the injectable constructor with an attribute
  2. Setting a default object life cycle for a container (rather than having to pass in the life cycle every time a type is registered with the container)
  3. Ability to resolve concrete types that have not yet been registered with the container

In the spirit of open-source, I created the necessary code and sent it back to Germán for inclusion in the project.  As of this posting, he's included the constructor attribution feature in the source repository, and hopefully he'll also add the other features as well.

My struggle with Ninject came down to the fact that it operates in a fashion quite distinct from other DI frameworks. I must admit that the Ninject DSL is quite appealing, but certain things that I'm comfortable doing with StructureMap are difficult if not impossible to attain using Ninject without creating a bunch of direct dependencies on the Ninject assemblies.  So it looks like Compact Container is the winner at this point.  We'll see if it sticks.

 

Tags: , , , ,

Nov 14 2008

T4 Templates For The .NET Compact Framework

Category: Software DevelopmentJeff @ 22:48

I first learned about the Text Template Transformation Toolkit (T4) about a month ago when reading some blog posts from Rob Conery and Scott Hanselman. T4 is a code generation tool that comes with Visual Studio 2008 (there's also an add-in for VS 2005).  Rob likes T4 so much, that he's rewriting his SubSonic data access layer builder to use T4 template generation (check out his second preview of SubSonic 3.0).

As I wrote about a few days ago (Dependency Injection for the Compact Framework), I've recently returned to the world of building Smart Device applications using the .NET Compact Framework.  I've been working on building the basic foundations of the domain model and I started running into some situations where code generation could make my team more productive.  So, I tried adding a T4 template to my Compact Framework project (a file with a ".tt" file extension) and *boom*!  Three errors crop up:

  1. Compiling transformation: The type or namespace name 'CompilerError' does not exist in the namespace 'System.CodeDom.Compiler' (are you missing an assembly reference?)
  2. Compiling transformation: The type 'System.CodeDom.Compiler.CompilerErrorCollection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
  3. Compiling transformation: 'System.CodeDom.Compiler.CompilerErrorCollection' does not contain a definition for 'Add'

Why doesn't this work?  Because Visual Studio is attempting to use the Compact Framework assemblies in order to process the T4 template file.  But the Compact Framework assemblies don't include the System.CodeDom namespace. 

I don't think Microsoft is ever going to add the CodeDom namespace to the Compact Framework.  But there is a way to get T4 templates working in a Compact Framework project.  You basically start off by creating two separate projects, one targeting the full .NET Framework, and another targeting the Compact Framework.  Then, combine these projects into the same folder so they can share files between them.  Finally, you can add .tt files to the full .NET Framework project and include the generated .cs files in your Compact Framework project.  Voila!  Templates for the Compact Framework.

I've created a quick-start document to walk you through the process: T4 Templates for the .NET Compact Framework

Happy code generating!

Tags: , ,

Nov 13 2008

Strongly Typed Model Object Without Code-Behind (Sort of)

Category: Software Developmentemilioc @ 20:21

Are you using ASP.NET MVC?  Do you want a strongly typed ViewData.Model object without a code-behind file?  Tough, who said life was fair?  I am just kidding ;p. 

After reading Look Ma, No Code-Behind! by Chad Myers, I was inspired to share my approach.  In my approach, I swap a code-behind file for an ordinary class file.  I create a file per view folder named _ViewDataModelType.cs.  The file name is optional and can be changed per view folder.  I like to use the same name over and over because I am lazy.

Setup

In this file I declare all the ViewPage and ViewUserControl subclasses needed for this particular view folder.  Use your namespaces wisely because if you're not careful you can run into naming collisions.  Below is an example of what one these classes might look like.

namespace NoCodeBehind.Views.Employee {
    public class EmployeeIndex : ViewPage<IEnumerable<Employee>> {
    }

    public class EmployeeShow : ViewPage<EmployeeViewModel> {
    }

    public class EmployeePartial : ViewUserControl<EmployeePartialViewModel> {
    }
}

Usage

All you need now is to wire up your .aspx page.  The Inherits attribute is the important piece.  Below is an example.

<%@ Page Language="C#" AutoEventWireup="true" Inherits="NoCodeBehind.Views.Employee.EmployeeIndex" %>

After that, you are done.  You now have a strongly typed model object at your finger tips. 

Conclusion

Using a code-behind file for every view page is a non-option for me.  This is a simple work around and helps keep my project slim around the waistline.  I am definitely open to other solutions to this issue.  I hope this helps if you are wrestling with the same issue.

Tags:

Nov 12 2008

jQuery and The Amazing Selectors Part 1

Category: Software Developmentemilioc @ 21:54

If you are looking around for a JavaScript library or looking to switch libraries, you should give jQuery a sample.  If you have been doing web development for any period of time, then I am sure you've heard of it.  From my experience, jQuery is an incredibly easy library to learn.   I made the decision to learn jQuery several months ago and it has been a godsend.  It has dramatically improved my relationship with JavaScript; a strained relationship, at best, no thanks to IE.  But those days are history along with the days of getElementById.  This brings me to the topic of this post.  I wanted to take a little time to talk about jQuery selectors and showcase a few of my favs.  When using jQuery, IDs are optional.  You can select elements using class name, DOM position, attribute value and IDs (if you feel like being all precise and stuff).

Keep in my mind this is not an exhaustive list of every possible selector.  It is, however, a list of my most used (read favorite) selectors.

1.  var value = $('.fields:first input:hidden').val();

Selector number 1 will find the first instance of the fields class (.fields:first) and then select all hidden inputs (input:hidden) found within the containing tag.  Since there is only one hidden input that matches the selection, only one will be returned.  Making the retrieval of the hidden inputs value a snap.

    <div class="fields">
        <input type="text" id="textBox1" name="textBox1"  />
        <input type="text" id="textBox2" name="textBox2"  />
        <input type="hidden" id="Hidden1" name="Hidden1"  value="Hello"/>
    </div>

    <div class="fields">
        <input type="text" id="textBox3" name="textBox3"  />
        <input type="text" id="textBox4" name="textBox4"  />
        <input type="hidden" id="Hidden2" name="Hidden2"  value="Goodbye"/>
    </div>

 2. $('.fields input, .fields select, .fields .someClass').click(function() { alert('hello') });

Numero dos on the list is the multi-selector.  I am not sure if that is the official name but that's what I like to call it.  Using this selector, you combine multiple selectors into one separating each selector with a comma.  This will allow you to manipulate the matches of three selections as one.  It can be very useful if you need to assign an event to multiple elements of different types. 

<div class="fields">
    <input type="text" id="textBox1" name="textBox1"  />
    <select>
        <option>opt 1</option>
        <option>opt 2</option>
        <option>opt 3</option>
    </select>
    <input type="text" id="textBox2" name="textBox2" class="someClass"  />
</div>

3. $(this).nextAll('ul').toggle();

This selector is kind of a stretch.  Inside an event you can pass in the this keyword as a selector and get instance access to the element that fired the event.  If you need to find some related DOM elements you need a change in strategy.  The this keyword can't be concatenated with string selectors.  One possibility, is to grab the ID attribute of the element that fired the event ($(this).attr('id')).  But what if your element doesn't have an ID?  That's where jQuery's traversing methods make an entrance.  The nextAll() method will get all sibling objects that appear after the currently selected object.  You can optionally pass selectors in to the the nextAll() method ...

<div>
    <h3 class="toggleButton">Text</h3>
    <ul><li>text</li></ul>
    <ul><li>text</li></ul>
    <ul><li>text</li></ul>
    <ul><li>text</li></ul>
</div>

 $('.toggleButton').click(function(event) {
    $(this).nextAll('ul').toggle();
});

Conclusion

With three short examples I am only scratching the surface of jQuery's amazing selectors.  I hope this post makes you hungry for more and at the very least, gets the uninterested interested in jQuery.  I will be back with more soon!

Tags: ,

Nov 12 2008

Dependency Injection for the Compact Framework

Category: Software DevelopmentJeff @ 08:03

I've spent the last 2 years developing WinForms and ASP.Net MVC applications, so it's been a while since I've worked on a .NET Compact Framework project.  In case you haven't heard of it, the .NET Compact Framework is a compact sub-set of the .NET framework that can run on devices with limited resources (like phones, blackberries, barcode scanners, etc.).  As I began working on the project, I decided up front that I would use the same SOLID principles I use on any other application.  I almost hit a roadblock, however, when it came to choosing a Dependency Injection framework.

I began with just a simple roll-your-own dependency resolver.  But this solution doesn't work well once you need to inject multiple layers of dependencies and build up your object hierarchies in a more complex fashion.  So I did some research into which (if any) DI frameworks support the Compact Framework.  It turns out that only one DI framework supports the Compact Framework: Ninject.  Typically StructureMap has been my DI container of choice, and recently I've spent some time evaluating the Unity container from Microsoft, but neither of these support the Compact Framework.  So I guess I've got a limited number of choices:

  1. Don't use IoC and dependency injection
  2. Continue to "roll-my-own" dependency injection tool
  3. Pray that Jeremy Miller ports StructureMap to the Compact Framework
  4. Use Ninject

Option 1 is not even a real option.  There are too many benefits to be gained from loose coupling and depending on abstractions rather than details.  Option 2 seemed feasible at first, until I needed more complicated object hierarchies.  I can't hold my breath and wait on something that may never happen, so Option 3 isn't a real option either.  So, it looks like I'm going to be heading to Ninja school!  I'll let you know how it goes and what I discover along the way.

Tags: , , , ,

Nov 3 2008

Stay Curious

Category: Agile Project ManagementJeff @ 17:05

Curiosity killed the cat - Eugene O'Neill

What is true for the cat is completely untrue for the agile team member.  The best agile teams place a high value on learning.  Curiosity is the catalyst for knowledge acquisition and creativity.  It helps us remain dispassionate about personal preferences and can unlock our potential for divergent thinking. Often it seems that curiosity is reserved for R&D or design processes, but the best way to maximize its potential is to stay curious throughout the entire product development lifecycle.

Curiosity when planning.  This is a vital element in a design process.  We need to stay curious about potential features and requirements.  We need to stay curious about resource allocation possibilities.  We need to stay curious about platforms, tools and technologies.

Curiosity about processes.  There is no perfect process, but there are processes that fit better for a particular context or situation. We should not simply assume that what worked before will work now.  We should not simply assume that what is new is better.  We should continually mold and shape our processes for maximum effectiveness.

Curiosity about personalities.  Our curiosity can be applied beyond the particular task at hand by extending it to the consideration of organizational culture, people, relationships, interactions and influence.  This can enable us to work better together and to maximize the potential of our teams.  This can also help us diffuse conflict by minimizing presumptuousness and assumption, and instead choosing to remain curious about why other team members are acting in a particular way.  

Curiosity when pondering.  Retrospection is reflecting on what worked, what didn't work and what could work better in the future.  Curiosity helps us to look deeply into our processes, our planning efforts, and our personalities to learn the lessons that will help us hone our skills and achieve better results as we move forward.

So if your goal is to effectively function as an agile team, reflect often, ask a lot of questions, and seek to learn from every possible facet of every possible situation.  Place a high value on staying curious.

Tags: ,