Wednesday, July 19, 2006

Applying PicoContainer.NET with Presentation Patterns - Part I

There is a couple favourite presentation-layer design patterns that I have been consistently using to build .NET applications. In particular, they are Presentation Model and Model-View-Presenter. Both are extremely handy when it comes to making the code-behind of your View more testable by delegating its responsibilities to another layer of code. From that layer, you can start chipping in various flavors of dependency injections and stubs and mocks to start going all-out unit testing assault to your code.

In many cases, on a per View basis (like a page or user control), there is a Presentation Model class, or a Presenter class, sitting behind it ready to receive a call from its corresponding View, then execute the behavior called upon.

PicoContainer.NET (Pico from here on) encourages more decoupled object-oriented class design by helping you to manage your classes' dependencies. As a quick example, suppose you have a class iPod (you know what it is, right?) and a class Battery. Obviously iPod depends on a battery. However, the iPod class at construction time creates its own Battery instance to use and cannot take any other battery types (to the dismay of iPod users). Now your iPod stopped working and you have to figure out why. If you need to test your iPod, you have to be extremely creative to figure out where the problem is related to its battery or not somehow. How do you know if the problem lies in the iPod, or its battery? This is why good code minimize dependencies. Suppose, however, your iPod receives a Battery instance through its constructor. Then in the unit tests of your iPod class, you can then mock/stub the battery out and start exclusively interrogating and verifying the behaviors of your iPod class. iPod now can be injected with a mock Battery instance, and hence your iPod class is more testable, and its tests are more "unit" and not touching other parts of your code. You can then start writing more automated unit tests that run in milliseconds easily.

The question now is who then is responsible for passing a Battery instance into iPod. That's where Pico shines. If, as mentioned, your iPod has such a constructor that takes in the Battery dependency, using Pico as a container, you register your iPod and Battery class into the container, when you ask the container for an iPod instance, the Battery instance (since it is also registered) will be instantiated automagically and you can now start using your iPod object, without having to hard-code your iPod class to instantiate its own Battery.

Because Pico is such a great tool, I have used it in various .NET projects of mine. Since Pico uses a registration scheme, whatever you put into a Pico container you get its dependency-wiring functionality for free, many things tend to be put into it. Afterall, Pico encourages good design, right? As a result, Views, Presentation Models, Presenters, etc., are all registered into Pico container. The Pico container is set up at public static void Main() time, and when you run Application.Start(form) you pass it into your form object. From there all of your Views can programmatically ask for its dependencies. Life is good.

Why are Views being put into the container? Because every View needs a delegating Presentation Model or Presenter to handle its behavior, meaning, every View "depends" on a Presentation Model or Presenter. As a result, they all get registered into Pico in order for the form to get navigate the user to the correct View.

Life is good - until stuff happens. Since constructor injection is the preferred way to inject dependencies, if your View "depends" on something, then your View would need a constructor passing in its dependencies before Pico can start wiring dependencies on your behalf. Every .NET programmer knows that, every View (regardless you use a Form or User Control) has a default parameter-less constructor that has a default line InitializeComponent(). This is because the Visual Studio .NET IDE uses this constructor to support WYSIWYG at design time. Tampering with or getting rid of this constructor and/or the InitializeComponent() method call will get your IDE trouble in supporting editing your View at design time.

A second problem that would arise is that, consider I have a User Control. It is also a View, albeit being used and instantiated by its parent View (maybe another User Control). Since this child user control instance is created by the auto-generated code from the parent Views InitializeComponent() method call, you cannot modify this child user control's default constructor to take in its "dependency" Presentation Model/Presenter, and then hope that its parent Form can somehow inject the child control's dependencies inside its InitializeComponent() method. Even if you can modify these auto-generated code, your IDE design-time support is now in jeapardy. Because of this problem, some Pico programmers would buck the constructor injection coding consistency, pass in the child user control's dependencies into the parent View's constructor, and start using setter injection to inject the child user control's dependencies, after the parent Form's InitializeComponents() method call. That way at least you can leave the child user control's default constructor alone and continue to use VS's strong IDE support, while managing your child control's dependencies.

What to do? Now comes Part II - My attempt to get the best sides of all worlds: Use Pico to manage dependencies; and have VS.NET IDE WYSIWYG support.

Wednesday, July 12, 2006

Ruby sugar you can't find in C#

Coming as a C# programmer to learn Ruby, as I journey from a compiling language to a dynamically typed language, of course there are some concepts in Ruby that are easier (or harder) for me to grasp than others. I want to write out loud some of these interesting bits and pieces for others who are also interested in trying out Ruby.

String vs. Symbol
In Ruby a string can be single-quoted or double-quoted (eg. "foo"). A symbol is a variable name prefixed with a colon (eg. :foo). Symbols somtimes are used pretty much synonymously with strings. The reason they exist is that by using symbols, in memory they only exist as a single copy per symbol no matter how many times you refer to them in your code. String however will create a new copy of the string in memory every time you refer to them, even though they are exactly the same. This in C# is equivalent to string interning, and is the difference between using between a StringBuilder and regular string concatenation. So don't be baffled when you see them next time.

Methods vs. Messages
In Ruby, everything is an object, including a number and a string. Ruby programmers like to think that when you are calling a method on an object, you are sending a message to that object in hope of it doing something for you. One of the cool features in Ruby is that one can call methods that are not defined at programming time but define and call them at runtime. For example:

class Foo
def programming_time_method
puts "programming time method"
end

def define_more_methods
self.class.class_eval do
define_method(:new_born_method) { puts "i was born!" }
end
end
end

Now if you do:
f = Foo.new
f.programming_time_method
puts f.respond_to?(:new_born_method) #Does f have method by that name?
f.define_more_methods
puts f.respond_to?(:new_born_method) #Does f have method by that name, now?
f.new_born_method

then you get results:

>ruby test.rb
programming time method
false
true
i was born!

One can do much more fancier stuff with Ruby too. Read on.


Class Methods vs. Static Methods
In C# most developers I worked with frowned upon static methods. They are flat-out evil. You cannot effectively mock method calls of them, and that they encourage non-OO style procedural programming. Pretty much all of the arguments that they are good for something are trumped by the hard-to-test reason. Introducing class methods in Ruby:

class Customer
def self.class_method
puts "class method getting called"
end
end

Customer.class_method
>ruby test.rb
class method getting called


At first glance they act just like static methods, you do not need an instance but just the class type and you can start making calls on them. However, they are no longer un-mockable. The unit testing framework that comes with Ruby also contains a mock framework. It can mock class methods. All of a sudden class methods, or should I say methods that associate to a class, deserves another look. In fact, Ruby on Rails uses class methods extensively for some of its magical operations. For example, if my Customer class inherits from Model, and has an id and a name in the database, I automatically get these magic methods for free - yes, free!

Customer.find_all                # returns the list of all Customer instances from database
Customer.find_by_id(2) # returns the Customer instance that contains id=2 in database
Customer.find_by_name('STEPHEN') # returns the list of all Customer instances whose name is STEPHEN


When you add a column to your table in the database, you get a free find method without coding. That's Rails.

Method-missing
Any message (aka method) you send (aka call) to an object, if that object does not yet have that method defined, it will go into its method_missing() method, which you can override. From that point, one can be fairly creative given the dynamic nature of what Ruby allows a programmer to do. In fact, method_missing() plays a pretty important role in constructing a DSL (Domain Specific Language).

class Customer
def method_missing(method_symbol, *args)
puts method_symbol.to_s
return self
end
end

customer = Customer.new
customer.pays.me.five.dollars

>ruby test.rb
pays
me
five
dollars

More Ruby sugar will follow. Stay tuned.

Thursday, June 22, 2006

How to use GMail SMTP server to send emails in Rails ActionMailer

Recently I had to use Ruby to send emails. I don't want to go through the hassle of setting up a mail server on my build box, and since I use GMail's hosted webmail service I am thinking I might be able to use their smtp mail server to do it.

Rail's ActionMailer was simply the automatic choice, since I am building a rails app.

Turns out GMail supports only SSL SMTP mailing service, meaning if you cannot create a SSL connection to its SMTP server, you cannot send email through them. My Rails and Ruby (1.84) version do not yet support creating a SSL SMTP connection through Net::SMTP. DHH writes about how to do so through installing msmtp here, but we developers just obviously love options =)

The dynamic nature of Ruby allows me to enhance the functionality of that class. I found the following code from a couple Japanese posts here and here on the web (fairly low Google ranking). Pasting them in my /vendor/plugins as follow:


$ cat vendor/plugins/action_mailer_tls/init.rb
require_dependency 'smtp_tls'


$ cat vendor/plugins/action_mailer_tls/lib/smtp_tls.rb
require "openssl"
require "net/smtp"

Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret, authtype if user or secret

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout
@socket.debug_output = STDERR #@debug_output

check_response(critical { recv_response() })
do_helo(helodomain)

raise 'openssl library not installed' unless defined?(OpenSSL)
starttls
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
@socket.debug_output = STDERR #@debug_output
do_helo(helodomain)

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS')
end

def quit
begin
getok('QUIT')
rescue EOFError
end
end
end

So now, in your ActionMailer::Base's server settings if you have:

ActionMailer::Base.server_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "mycompany.com",
:authentication => :plain,
:user_name => "username",
:password => "password"
}
You call your ActionMailer::Base's deliver method (perhaps from a custom subclass), it will send an email through GMail. Mission accomplished.

Thursday, May 25, 2006

Some unspoken tips on managing an Agile project

Want to have an easier time to manage an Agile project and avoid common pitfalls while have some fun? Read on...

Food
Believe it or not, food is not a luxury item on an Agile project. Food is *essential*. Agile practices encourages as much open-air communication as quickly as possible, be it computer-to-human (through tests) or human-to-human (short iterative cycle). Yet sometimes it is hard to force down onto people to communicate more effectively from a Project Manager. By having good food/snacks, people who are not co-located are going to come to the room much more often than usual, and a casual "how are you guys doing" while shuffling popcorn into his/her mouth is usually a conversation starter on many things the development team needs. And food, of course, improves morale inmeasurably =)

Team co-location
This is key to being able to communicate more effectively, which is one of the tenets of a successful Agile project. By more effectively, I mean the project can execute in less time because people can make more informed decision based on an abundant amount of open-air information. For whatever reasons, people are generally good at filtering useless information but not good at carrying information to the appropriate people who need them. By bringing the team together in a relatively open area with maximum face-to-face communication, you are encouraging team members to make more informed decisions before they waste time to work on the wrong thing based on false assumptions on continually ongoing changes within the development team and the business.

CI build sound
If you use CruiseControl.NET, try putting a sound clip that reminds of some embarrassing moments of some development team members as the build success/failure cctray settings. This can get quite amusing some times. Another morale booster.

Quote sheet
During the course of development, there is bound to be someone who inadvertently said something hilarious about someone or something. Keep a list of them on a wiki on the build server where the team members have access to. This is a must as part of the team-building process. At ThoughtWorks's annual national gathering day, we collect great and funny quotes from ThoughtWorkers from projects everywhere, print them on T-shirts, then auction them out. The money collected goes to donation. Funny and meaningful.

My funny quote of my current project? Nah. You have to ask me personally for that =P

Second story wall for issues after 1.0 release
In a XP story wall, which represents the progress of stories planned for the current iteration, usually contains columns ("DEV Ready", "DEV In Progress", "QA Ready", "QA Complete") that mark the stages of a story from ready for development to QA complete. Now how does the wall change when your application goes 1.0 release?

Generally, after a 1.0 release, the team will create a new branch of the source code for urgent production defect fixing purpose. The problem is that when you have a large team of developers split across urgent production defect fixes and release 1.1 development, or there are many small and frequent 1.x releases coming after your initial release, or for some uncommon reason you have more than one branches of source code (after you have determined it is ultimately unavoidable). Then managing the merging of code from your release branch to your active development branch becomes tricky, because if developers forget to merge, your active development branch now has bugs.

How about at 1.0 release, create a new story/issue wall next to the original story wall, but it only contains columns "Issue Verified", "Issue In Progress", "Issue Resolved", and have the developers merge their source code before they can move any issue cards from "Issue Resolved" column of that wall to the other wall's "QA Ready"? This physical movement of an issue card from one wall to another always remind developers to merge their changes. If that doesn't help the busy and forgetful developers, have them move issue cards to a new column called "Issue Merged".

Stand-up token
A good stand-up meeting is not an avenue to identify "solutions" of problems participants face. It should be a quick meeting to identify individuals who need to hold face-to-face conversations after the stand-up and then move on. But people being people, sometimes conversations go out of hand during a stand-up. Have a stand-up token, like a football, in stand-up so that only the person who has the token can talk. When you see people exchange the token too many times in a conversation, perhaps it's time to ask them to offline it till after the stand-up.

Thursday, April 27, 2006

Stacking "using" blocks together

I had always been thinking of using the using-block to instantiate multiple disposable objects so I don't have to remember explicitly calling Close() or Dispose() on them:

            using (IDisposable one = new DisposableOne(), 
                   IDisposable two = new DisposableTwo())
            {
                // Compile time error
            }


But unfortunately C# does not support that. So as a work around, one would do these nested using statements to do the trick:

            using (IDisposable one = new DisposableOne())
            {
                using (IDisposable two = new DisposableTwo())
                {
                    // Ops. Code is now indented
                }
            }


But now, you have messed up your pretty-looking indentation of your code. Remember back in the acadamia your programming class instructor told you that all your if-else/for/while statements will work without curly brackets? Well, surprise, same case for using blocks:

            using (IDisposable one = new DisposableOne())
            using (IDisposable two = new DisposableTwo())
            {
                // This works!                
            }


Time to show off to your pairing friend you can write prettier code than him/her =D

Friday, April 21, 2006

Multi-threading applications tips

Recently I have been involved with a multi-threading application, and throughout development I have been acquiring tips and gotchas here and there. One of the fun things about such applications is that you get to play with some sort of almighty powerful server box. In my case, a cool 8-processor dual core box with 8 GB RAM... How much is it? $70,000. =)

Test your application in a comparable multi-processor testing server. Better yet, test it on your production box
Yes, you heard me. Usually multi-threading applications are performance critical. Otherwise how else can you justify a pricy machine and more complicated code? If you are not able to perform testing on the actual production box, chances are the users will ultimately find the problems. Which means developers, QA, and project managers all have to work OT hours to fix the problem and push those fixes to production, plus the number of phone calls and help desk tickets you have to make. When you multiply these hours and stress, the justification of having another pricy testing server before going into production all of a sudden is not too pricy anymore.

Server GC vs. Workstation GC
.NET garbage collection behaves differently when it is installed on a single processor machine versus on a multi-processor machine. If you install it on a single processor box, it is in Workstation GC mode, meaning there is at most one thread doing garbage collection. When you install .NET onto a multi-processor box, it is installed as Server GC mode, meaning there is one GC thread per CPU. I strongly advise that the environment you deploy to before your production environment to be a multi-processor machine and have Server GC mode turned on. That way you are testing more closely to the real environment. In performance-intensive applications, garbage collection, albeit automatic, is usually worth monitoring as well.

Raise an event thread-safe
In C#, many of us have raised an event this way. In fact, this is the way most books/lectures/tutorials demonstrate it.

    1 public class Battery
    2 {
    3         public const int LOW_BATTERY_LEVEL = 20;
    4 
    5         public event EventHandler LowBattery;
    6         public event EventHandler Depleted;
    7 
    8         private int remainingBattery = 100;
    9 
   10         private void OnLowBattery()
   11         {
   12                 if (LowBattery != null)
   13                 {
   14                         LowBattery(this, EventArgs.Empty);
   15                 }
   16         }
   17 
   18         private void OnDepleted()
   19         {
   20                 if (Depleted != null)
   21                 {
   22                         Depleted(this, EventArgs.Empty);
   23                 }
   24         }
   25 }


Did you know that this is not thread-safe? Thread A could be executing this code, does a null check at line 12, when it is just about to raise the event, Thread B grabs the subscriber and unregisters/unwires the event. When Thread A resumes execution, it tries to raise the event when no one is subscribing to it. Null reference exception.

In order to make the code thread-safe, we can take advantage of delegates are value-types, in other words, you can only create"copies" of them, but not by reference.

   10 private void OnLowBattery()
   11 {
   12         EventHandler handler = LowBattery;
   13         if (handler != null)
   14         {
   15                 handler(this, EventArgs.Empty);
   16         }
   17 }


Use of lock(this) and lock(typeof(Foo))
Every C# programmer is aware of the lock keyword. It prevents multiple threads from referencing the resource while the resource is being modified. When you want to modify a member variable thread-safe, you can go and lock the object that contains it:

public Foo()
{
            lock(this)
            {
                    _memberVariable = "SOMETHING";
            }
}


But what about static variables? Well, interestingly the lock statement allows you to lock a type object as well:

public class Foo
{
            public static string StaticVariable = null;
 
            public void SetUpStatic()
            {
                    lock (typeof(Foo))
                    {
                            StaticVariable = "SOMETHING";
                    }
            }
}


Give you threads names
Yes. Threads in the old days have only a thread id, which gets generated every time when a new thread is genereated, and that makes debugging very painful. Now in .NET you can programmatically give each thread your application creates a name with its t.Name property. Use them, then in your VS.NET Debug/Windows/Threads (Ctrl-Alt-H while debugging) you will see each thread with their name. Now they look much more friendly. Better yet, name your threads after each project manager you have worked with =)

Use .NET synchronization classes
Don't tell people you know how to write multi-threading applications knowing only how to use lock(). If you don't know how Monitor.Wait() and Monitor.Pulse() and the shopping bag of the synchronization classes that .NET provides, you are missing out alot. As a starter, try this excellent article here. It's a must read for anyone programs C# and multi-threading.

Wednesday, April 19, 2006

Checking duplicate Sql statements in Excel

In my current project we are doing database Continuous Integration (CI). This means that every developer will have their own database instance for development, and at every check-in the build server kicks off the CI cycle, which starts getting the latest source code, compile, rebuild the database from scratch through running SQL scripts, re-insert data (reference data) these tables should have, compile, test, etc. When done right, this allows the much-required freedom for developers to develop against the database without interfering other developers' databases, and significantly reduces the time it takes to ask the DBA's to modify the database table for you.

When you acquire from the customer/business analysts a new set of reference data that they would like you to insert into these database tables, I have seen in many cases where these new data conflicts with the data that already exists due to duplication (mostly human error). Since most of these reference data are scripted in text files and there are usually hundreds if not thousands of them, sometimes finding that one duplicating line is like trying to find a needle in a sea.



Fortunately in Excel there is a function to rescue: =COUNTIF(set, to_find).

Usage: Increment count if "to_find" exists in "set".

So to quickly find out which is the offending PK constraint INSERT line, you do this:
=COUNTIF(E3:E11, E3)



And as you see you will quickly find out where that awful INSERT statement is... Time to bug the customer =)

Thursday, March 16, 2006

Pragmatic NAnt scripting

Why am I talking about NAnt when the rest of the world is in love with Ruby and Rake? Well, I still think NAnt has its value. Rake is still pretty raw (it doesn't even have an NUnit task yet), and until it has matured there is still a huge group of developers out there not wanting to spend a huge deal of time learning Ruby/Rake. Plus, most companies out there who have already adopted NAnt is stuck with their NAnt code. This article provides some insights on how to provide such companies business value by making NAnt scripts more maintainable.

Based on my experiences with NAnt, I am concluding the followings are true:

  1. NAnt scripts are very hard to maintain, due to reasons such as:

    • Target dependencies are all intermingled into a big unmanageable web.
    • No consistencies across NAnt scripts. There is no coding convention in NAnt scripts.
  2. The scripts have to handle a lot if you think about it. It has to handle...
    • Pre-Build (like build artifact directory creations)
    • The CI (Continuous Integration) cycle like GetLatest, Compile, UnitTests, OtherTests.
    • Post-Build (like package, stage, distribute, deploy, blah...)
  3. Build scripts are nasty and no one wants to inherit, and that's why names like "build monkey" (and even more provocative ones) are created and stick to people who initially start the script and tend to stick to those people until they leave the project. It is a thankless job.
  4. Build scripts are, nevertheless, crucial to any projects. If you have a good set of build scripts, they can help developers writing higher quality code, BAs to verify story functionalities quicker, QA to mitigate environment nightmare, and streamlines deployment process by deployment team.

And here are some tips that I have found to be useful to extend the maintainability and lifespan of your build scripts.

Have multiple build script files
I would break down what I see in many projects one monolithic projectname.build file into many smaller build files named after their build function. For example, the file below is called Sesame.build. It has one and only one purpose: to build a project, and test it. I am putting these two build functions together into one build file because the targets involving testing the build output is usually small, and usually go hand-in-hand together. Conveniently co-locating them into one file I think is better than creating a small and isolated test.build file. But other build disciplines, such as package & deploy, by itself could be a big deal, so if complexity warrants I will have a separate file for them. The only encapsulation we can apply to build scripts is really separating them into files.

<?xml version="1.0" ?>
<project name="cruise" default="all">

    <target name="all" depends="get, build, tag" description="Target executed by CCNet." />

    <target name="get" depends="get.get_latest" description="Gets the latest source code from Subversion." />
    <target name="build" depends="build.build" description="Compile and build the source code." />
    <target name="tag" depends="tag.tag" description="Tag the successful build by the naming convention tags\\CRUISE-B999" />

    <target name="get.get_latest">
        
    </target>

    <target name="build.build">
        <nant buildfile="Sesame.build" target="all" />
    </target>

    <target name="tag.tag">
        
    </target>

</project>


<?xml version="1.0" ?>
<project name="Sesame" default="all">

    <target name="all" depends="build, test" description="Compile, build, and test the Sesame project." />

    <target name="build" depends="build.compile, build.database" description="Compiles the .NET source code and setup local database instance." />
    <target name="test" depends="test.unit_test, test.other_test" description="Runs unit tests and functional tests." />

    <target name="build.compile">
            ...
    </target>

    <target name="build.database">
            ...
    </target>

    <target name="test.unit_test">
            ...
    </target>

    <target name="test.other_test">
            ...
    </target>

</project>


NAnt target categorizations and naming convention
The ultimate sin of unmaintainable build scripts more or less attribute to the over-profileration of target dependencies. When targets start having a complex web of dependencies, build scripts will take an enormous amount of courage and time to repair.

By breaking down all targets in a single NAnt build file into three categories, and through coding consistency and naming conventions, build scripts can last for a very long time. I find the following categorizations of all NAnt targets in your build scripts useful.

<?xml version="1.0" ?>
<project name="Sesame" default="all">

    <!-- Level 1 -->
    <target name="all" depends="build, test" description="Compile, build, and test the Sesame project." />

    <!-- Level 2 -->
    <target name="build" depends="build.compile, build.database" description="Compiles the .NET source code and setup local database instance." />
    <target name="test" depends="test.unit_test, test.other_test" description="Runs unit tests and functional tests." />

    <!-- Level 3 -->
    <target name="build.compile">
        // Compile using the build.solution_configuration property value...
    </target>

    <target name="build.database">
        // Rebuild database using the database_server property value...
    </target>

    <target name="test.unit_test">
            
    </target>

    <target name="test.other_test">
            
    </target>

</project>


Points of interests:

  • Level 1: These are targets that orchestrates the order of executions of various Level 2 targets and not Level 3 targets. They will only contain depends, but never have a target body. They are the common entry points into the build function the script file represents (eg. target "all" in cruise.build will be called by CruiseControl.NET to kick off the CI build process). They must have descriptions. I prefer names to be underscore-delimited.

  • Level 2: These are targets that group Level 3 targets together to make a cohesive unit of work of function. For example, a "clean" target might do altogether a few things to clean a build: build artifacts directories, build results directories, VS.NET bin/obj/VSWebCache, etc. They again will never have a target body. These targets will also have descriptions. I again prefer their names to be underscored.

  • Level 3: These targets will *never* contain depends. They will *only* do one very refined detail piece of work. In addition, their names should be namespaced by a Level 2 target name using a period, and then their function, so that they are easily distinguishable from other targets. This helps newcomers to recognize them and start treating them differently. They never have descriptions (think of these as private methods in a class that does one very specific function for you).
The namespacing naming convention can also be expanded to properties as well.

Use properties to consolidate paths
Have a file (eg. common_paths.build) that extensively use NAnt properties to consolidate your source's folder structure. This will save a lot of code duplication in your build scripts in the longer run if you intend to keep your build scripts for a while.



<?xml version="1.0" ?>
<project name="common_paths.nant" default="all">
    <property name="trunk.dir" value="." />

    <property name="build_output.dir" value="${trunk.dir}\build_output" />
    <property name="build_results.dir" value="${trunk.dir}\build_results" />
    <property name="source.dir" value="${trunk.dir}\source" />
    <property name="tools.dir" value="${trunk.dir}\tools" />

    <property name="dotnet.dir" value="${source.dir}\dotnet" />
    <property name="dts.dir" value="${source.dir}\dts" />
    <property name="sql.dir" value="${source.dir}\sql" />

    <property name="nunit.dir" value="${tools.dir}\nunit" />
    <property name="nant.dir" value="${tools.dir}\nant" />
    <property name="nantcontrib.dir" value="${tools.dir}\nantcontrib" />

</project>


Use the target description attribute
NAnt provides a -projecthelp command line switch to list all of the targets in a given build file. When you give targets a description these targets gets first-class recognition in the listing as "Main Targets":



Combining this tip with the naming convention of the Level 3 targets can be a very powerful technique in improving the readability of your build scripts. As a bonus tip, consider also implementing a target named "help" to display all this -projecthelp target lists.

Use depends or call, but not both
If you start using both, you will be impairing the readability of your build scripts. They more or less do the same thing anyways. I would use depends over call because newcomers to NAnt would be much more likely to learn about depends ahead of call.

Know your property inheritance
NAnt's property inheritance convenience is commonly overlooked and under-valued. Many people chose using <call> task to preserve locally declared property values, rather than experimenting property inheritance of various kinds. I am publishing my findings here.

<?xml version="1.0" ?>
<project name="example" default="example">

    <include buildfile="common_paths.nant" unless="${property::exists('trunk.dir')}" />

    <target name="example" depends="calling_script.properties">
        <nant buildfile="example_two.build" inheritall="true">
            <properties>
                <property name="solution.configuration" value="DEBUG" />
                <property name="build_output.dir" value="c:\modified_build_output" />
            </properties>
        </nant>
    </target>

    <target name="calling_script.properties">
        <property name="calling_script.depends_inherited" value="Inherited from depends clause." />        
    </target>

</project>


<?xml version="1.0" ?>
<project name="example_two">

    <include buildfile="common_paths.nant" unless="${property::exists('trunk.dir')}" />

    <echo message="1) Explicitly inheriting property from nant task tag: solution.configuration='${solution.configuration}'" />
    <echo message="2) Explicitly overriding property in calling script's nant task tag: build_output.dir='${build_output.dir}'" />
    <echo message="3) Implicitly inheriting property from calling depends clause: calling_script.depends_inherited='${calling_script.depends_inherited}'" />

    <echo message="Is (1) readonly? ${property::is-readonly('solution.configuration')}" />
    <echo message="Is (2) readonly? ${property::is-readonly('build_output.dir')}" />
    <echo message="Is (3) readonly? ${property::is-readonly('calling_script.depends_inherited')}" />

</project>




1 & 2) Inherit properties through <nant> task
You can call the <nant> task and include a <properties> set within the tags, while setting the inheritall attribute to true to pass those properties to the build script that is getting invoked. In addition, as shown in (2), you can also override the loaded property "build_output.dir" in the properties section prior to passing it into the callee build script.

If you use this style of properties passing, it is a very good idea to pass them as readonly=true to avoid your customization of script behaviors to be reset again by the callee script.

3) It's important to know that properties declared earlier in the depends clause can be used further downstream in the later depends targets, even into another callee build script. This technique is useful when you do not want to load all properties for all targets up front (with the side-effect that the last target in your execution will have access to all properties declared in every single previously executed target, but I am okay with it because I rarely run into properties nightmare compare to build scripts nightmare). Therefore, the following readable script can be achieved:

<?xml version="1.0" ?>
<project name="Sesame" default="all">

    <target name="all" depends="build, test" description="Compile, build, and test the Sesame project." />
    
    <target name="build" depends="build.properties, build.compile, build.database" description="Compiles the .NET source code and setup local database instance." />

    <target name="build.properties">
        <property name="build.solution_configuration" value="DEBUG" unless="${property::exists('build.solution_configuration'}" />
        <property name="build.database_server" value="localhost" unless="${property::exists('build.database_server'}" />
    </target>

    <target name="build.compile">
        // Compile using the build.solution_configuration property value...
    </target>

    <target name="build.database">
        // Rebuild database using the database_server property value...
    </target>


I am sure there are lots of other tips as well, but that's it for this post. Comments, feedback welcome.

Thursday, February 02, 2006

A good way to create a custom Value-Type object in C#?

Have you ever written code like this?

State state = new State("AZ");
Money money = new Money(299.95);
 
State state = State.Parse("AZ");
Money money = Money.Parse(299.95);

How many domain-specific Value Type classes (you care about equality but not identities) have you been creating every project? The question of should I use the "new" keyword or a static .Parse() method to create them is always a coding consistency problem.

What if I tell you that you can do this in C#:

State state = "AZ";
Money money = 299.95;

Simple and clean. Here's how:

public class State
{
    private readonly string _state;
 
    private State(string state)
    {
        _state = state;
    }
 
    public static implicit operator State(string state)
    {
        return new State(state);
    }
}

Tuesday, January 24, 2006

Few findings about Presentation Model

Almost every project that I have been on strives for code testability. By increasing code testability one can better the design of the solution as well as continue to change code without worries. However when it comes to increase testability of the view in the classic MVC, it is always hard to do. Microsoft proclaims that they have achieved MVC (or Model-ASPX-CodeBehind), but it fails to address the testability issue of the code in V and C: CodeBehind logic are extremely hard to test against. Both the Presentation Model (PM) and the Model-View-Presenter (MVP) pattern address this issue.

Having used both patterns for my past few projects, I think I am seeing some pros/cons. Today let's look at the Presentation Model first:

Presentation Model:
I like using Presentation Model (PM) when I am developing a web application. In web apps, there are a couple major headaches when it comes to increase code testability, the first of which is carrying state across requests. Secondly, in ASP.NET, the Page class gets created and disposed of every request, making using an intermediary class (such as a Presenter) to "push" content from the model to the view very difficult, and hence a directional referencing problem.

PM employs a "pull" model, meaning the consumer class (aka the code-behind) will ask for data that the PM has prepared for it. Because of this model, at each Page cycle step (Page_Load, Page_Init, etc.) the view will be in the driving seat as far as controlling when to reload the controls and what to load them with. The PM simply sits there and wait for someone to tap his shoulder to ask him to produce something. Notice the directional reference: the view has a reference to the PMs. The PMs do not know about the view, and do not push content out to force the view's state to be refreshed.

Usually you will have one PM per ASPX page, which I call a Page PM. When the page gets busy, your Page PM is likely to be a gynormous 1,000 line class, containing many properties for the use of the many dynamic view controls' use. Therefore, use sub-PM classes to better organize your code and avoid code duplication. The levels of sub-PM classes from my experience probably won't go deeper than 3 inheritance hierarchy.

Most of your Page PMs usually will have reference to the session object, in which most probably the aggregate root of your Domain Model will be stored. For a more complex Domain Model, the PM's task of flattening out this 3-dimensional beast starting with this aggregate root will make your view look extraordinarily simple.

Because PMs usually flatten out your Domain Model into some easily readable grid or string format, your Domain Model objects may not be the ultimate data holder objects that your view 's controls bind to. For example, you will obviously need a new object for a grid showing an insurance policy's type, coverages, each and every insured entity, and each coverage's premiums. (Hopefully they live in separate objects in your Domain Model). Create some what I call "Data Item" objects to facilitate data binding to your grids or lists. Data Item objects are just for holding your diced and sliced Domain Model data and have no behaviors. Think of them as classes that represent a row of data in every single grid on your page. In the above example, your PolicyInfoDataItem class will have public properties of [PolicyType :string, CoverageName :string, InsuredEntityName :string, CoverageAmount :double]. This inspiration comes from DataGridItem, and various ListItem variants in the .NET Framework.

Unit testing your Page PMs in NUnit is always not easy because it uses the Session object, which is not available in NUnit testing. I have seen people use reflection to create a fake HttpContext object that stores Session data on the current thread, which then during [SetUp] set the context object (yes it does have a setter). Then your PM unit test classes have access to HttpContext.Session.

Speaking of unit testing PMs, I find it to be much more work to use mocking to unit tests your PMs. Especially if you love constructor injection, having your PM's ctor to take all those IEverything classes and during unit tests have them all mocked out is a lot of work because PMs is much more object state dependent than behavior loaded. As a result, I would prefer state-based testing (Stubs or the Object Mother pattern) to facilitate unit testing PMs. One must also manage the creation and customization of your domain model's state carefully, because these tend to duplicate code across your test classes easily if you go with state-based testing.

Your view also should not directly instantiate or reference any Domain Model objects (as a guideline, not rule). Whenever possible, pass primitive type user input information gathered off the Page and pass them directly to the Page PM for actions. This can consolidate exception handling routines (instead of scattering them all over your views), and also decouple your view from your Model, which you might later put them into separate assemblies.

Your Page PM can also handle behaviors that your view requests. For example, whenever a button is clicked, its code-behind event handler will make a call to the Page PM's "Save" method, passing the necessary information gathered off the controls, and then the Page PM will delegate the responsibility of the actual save to the Domain Model layer.

Saturday, January 14, 2006

Agile story tips

Stories in an Agile project tend to be less talked about than Test Driven Development, Continuous Integration, and Food :-). But in fact, when it's done well it can profoundly affect the project team's productivity and end users' satisfaction towards the software. The following are a few findings from my experience related to stories management that will drive better software. Their importance are rated on a a scale of 1 to 5 asterisks:

  • Stories should be a thin-thread from the frontend all the way to the backend. (*****)

    This helps the features being developed each iteration to be completed more consistently, and consistency drives predictability, and thus increases visibility and helps business to prioritize and plan given the available time and resources.

  • Business analysts (or the sponsor/end user) should own the stories. During IPM (Iteration Planning Meeting), they should be signed-off, meaning no changes should be made when developers start developing them. (*****)

    By freezing the requirements, developers can be much more productive. Compare a 100m race between two runners, one can go all the way from start to finish without stopping, while the other has to stop-and-go every 10m because he has to worry about the next 10m track he runs will be changed. Also, by someone owning the stories, after the stories were developed the owner of the story will have the responsibility to verify the correctness of the solution. Thus this requires better-written story specifications (tying back to freezing requirements), and in the end the developed story becomes exactly what business wants.

  • Stories should be measured in terms of difficulties or story points, instead of ideal development days (IDD). (****)

    There are two camps of people when it comes to this bullet. One camp uses IDD to estimate the difficulty of a story, then uses Load Factor to measure how off they were in their original estimates. The other camp uses Level of Difficulty such as small/medium/large, or Story Points such as 1-5, so they can measure purely based on yesterday's weather, and not a number that someone uncomfortably being forced to make up.

    IMHO, the first camp's glossaries were created at "post-mortem," literally. Consider the following conversation after a project failure:
    Business: Why did you guys fail to deliver? You only delivered half of what I want.
    Developers: Because we were not productive.
    Business: Why?
    Developers: Too many damn meetings.
    Business: Hm... so in "ideal time" if you had no meetings you would be able to deliver?
    Developers: Oh yea...
    Business: So in hindsight, the original estimates you guys told me was off by a "load factor" of 1/2. Next time should I want a new software I better take that into my budget account...

    The problem is that all these numbers are only meaningful within the context of that one project. But people being people, they like to carry these numbers with them to any projects they walk into wherever they go... because apparently they have been burned before. Next time when business asks for budget for a brand new project, guess what. They will bump up the budget by half, because of that "load factor."

    By using the terms of the second camp, one is implicitly forced to think of these measurements in the context of the current project. When I say this story's difficulty is a Large, one has to ask: Relative to what? Of course, the answer is relative to the other stories of this project. When I say, Story A is a 1 and Story B is a 3, again you are forced to think in the context of the current project.

    You might ask, now if you don't bump up the budget by half, then doesn't the business not get all of what they ask for? The answer is yes. But that's the beauty of short, iterative releases. If we can do that, then in the end the business without bumping up the original budget, yes they will exactly get what they have asked for according to their business priority, perhaps the 6 out of their 10 features, but since we have delivered at least some of the features in early iterations, not only the business has saved money due to those features being rolled out, but also the business is in better shape when it comes to repositioning itself to face more real world challenges, and thus will pump more budget to continue develop the software to give them what they want.

  • If stories are small enough, then there is no need to task them out during an IPM (Iteration Planning Meeting). If stories are to be tasked, they should be estimated. As each of them are completed, actuals should be measured.

    Admit to it. Small estimates are much more accurate than big estimates. Therefore, if each story is tasked out into small chunks of time estimates, and after story completion we have its corresponding actual time spent measurement, we then can find out how much work really is to complete say Story A, a medium-difficulty story or one that has Story Points of 3.

    So what are these estimates and actuals for? They are actual prove (or tracked history) of how we complete our Stories. Let's say in Iteration One we have a story "Public user login" that has a Story Points of 3. In that iteration (two-weeks), at the IPM the development team estimates that there are a total of 10 tasks to be done to complete that story, and they busted their ass to complete that and only that story. Then, in Iteration Seven, a similar story "Restricted user login" shows up. Relatively speaking, it also has a Story Points of 3, since they are about equally difficult. However, since most of the one-time tasks to do that has been completed, the actual number of tasks to complete this story in Iteration Seven might be just 3 tasks. Now the team can use the rest of the time to build other stories, and thereby achieve more Story Points. If it turns out the team achieved total of 7 points in the end, then we say the team is kicking some ass and is more productive than they were in Iteration One. You would notice the total time spent on all tasks between the two iterations will be somewhat the same (assuming no resources change), but completed Story Points increased. From the point of the business, it rocks, because they are seeing more stuff being churned out by the team, in exactly the manner they want it to be.

    This brings up another very important point, if you notice...

  • For story difficulty measurements, whatever you use (IDD, Small/Medium/Large, Story Points), you should always estimate it using the same scale as you estimate the entire story list. (*****)

    This is the only way to measure whether the team is improving over the course of the development.

    Using the example in the last bullet, if in Iteration One the team thinks that "User login story" is a 3 Story Points story, and in Iteration Seven the team completes a similar also 3 Story Points story "Restricted login story", then if in Iteration Ten business comes back and say they want a brand new but similarly difficult "CEO only login story", now despite the fact that in Iteration Ten, after doing those two login stories, this new story requires very very little work to complete, we must again make this story have 3 Story points.

    This way, the measurements will tell the business the following:
    In Iteration One, the development completed 3 Story Points.
    In Iteration Seven, the development completed 7 Story Points (because the tasks required to do the "Restricted login story" has reduced.
    In Iteration Ten, the development completed 14 Story Points (because even few tasks is required to complete the new 3-Point "CEO only login" story).
    In terms of the business people, Story Points = functionalities = business value. They know what they are getting in a consistent basis.

    Should there be a case somewhere in Iteration Eight the number of Story Points dropped, then one has to figure out why. Here's the task actuals can come into handy. In Iteration Seven, 7 Story Points and total of say 100 actual hours of time were needed to complete all tasks. In Iteration Eight, only 6.5 Story Points were completed. But if we look at the hours of the actual, only 90 hours were recorded from all tasks. Now we know the time the team spent on the actual tasks for all stories are about the same. Probably because people having vacations or public holidays that contributes to the drop in productivity.

Tuesday, November 29, 2005

Do you check in your OSS source into trunk?

How to use Open-Source Software? What I mean is, should you see OSS source code as part of your project's source code, keep their source code around and maintain/update them, or should you just use them in your project and wait for it to be maintained by their authors? This is a question for a lot of development teams, because by now almost anyone would have known the pros and cons of OSS. The bottomline is, you will use them at one point or another. The bigger question is, how to use them to your project's benefits, without carrying too much overhead.

For me, I want to maintain as few lines of code as possible. So my answer is, don't ever give me the OSS's source code. Give me your project's source code plus the OSS assemblies that are in use. I should be able to checkout your project's trunk and go. Don't assume I have stuff installed after I downloaded your project's source code. If at some point in the future the code does not run because of an OSS bug, fix the bug then submit it back to the community. If this happens more than few times, use something else.

This solves the problem of trying to maintain a chunk of code that a team has no idea about. At the minimum, it solves any new dev's problem of not having to download a 100MB trunk with 80MB of it is OSS source code (admittedly it's more a nuisance than a problem).

One of the good things about OSS is that there usually is an abundant amount of alternatives out there. Take functional testing as an example, Selenium and WATIR. There are things Selenium is good at (cross-browser testing), and there are things WATIR is good at (more powerful script coding). Mock objects anyone? NMock, EasyMock.NET, Rhino.Mocks, etc. Code coverage? There are even TWO NCovers out there that has the same name...

I think the problem of merging a tweaked, home-brew version of an OSS back into using a latest version down the road is much more painful than using multiple OSS in your code base. For the latter at least the breaking changes are documented.

If it hurts to use something in solving your problem. Don't use it. Problem solved. The problem you are getting paid to solve is delivering business value.

Saturday, November 19, 2005

The best Visual Studio.NET blogging companion

Check this out, all I did was in VS 2003, right-click, select "Copy as HTML...", click OK, and CTRL-V in blogger. All of a sudden you get this stylish code colorization in a blog:

    public class Bootstrap : IDisposable
    {
        private IMutablePicoContainer picoContainer;
 
        [STAThread]
        public static void Main()
        {
            try
            {
                using (Bootstrap bootstrap = new Bootstrap())
                {
                    IMainForm mainForm = bootstrap.BuildMainForm();
                    Application.Run((Form) mainForm);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }


Awesome VS.NET Add-in! CopyAsHTMLSource

Web 2.0... the what?

Recently I am hearing more and more about Web 2.0. So what the hell is it? It seems to me no one really knows exactly what it is, but among all opinions they all point to the same direction: enhanced web application's user experience. I guess the industry is looking for the next buzz word after AJAX.

In my company's forum, a couple web sites have been mentioned, and they really impressed me with what they mean by "user experience":
script.aculo.us
Rico

Man I am falling in love with the head-shaking textbox in script.aculo.us!

Monday, October 10, 2005

How to mock out event calls in NMock?

When it comes to .NET eventing, a lot of developers barf at and not knowing how to test them. one is that the event handler methods are correctly wired to the corresponding events, and two the event handler code does what it's supposed to. The first is hard to test, because the wiring of a method to the event is internal to the containing class only. The second is easier, because you could stub out the event handler method and making sure that it is getting called, but pure mockists would dislike this approach.

Consider the following example:


public interface IBattery {
event EventHandler Low;
event EventHandler Depleted;
}

public class Battery : IBattery {
public event EventHandler Low;
public event EventHandler Depleted;

public Battery() {
Low += new EventHandler(OnLowBattery);
Depleted += new EventHandler(OnDepleted);
}

public void SomeMethodThatConsumesBattery() {
.
.
.
if (IsLowBatter("10%")) {
OnLowBattery(this, EventArgs.Empty);
}
}

protected virtual void OnLowBattery(object sender, EventArgs e) {
if (Low!= null) {
Low(sender, e);
}
}
}

public interface ILaptop { }

public class Laptop : ILaptop {
private IBattery battery;

public Laptop(IBattery battery) {
this.battery = battery;

batter.Low += new EventHandler(OnLowBattery);
}

protected virtual void OnLowBattery(object sender, EventArgs e) {
// Count down 15 mins before shutdown!
}
}

We want to unit test the events are wired for our Laptop class, but we want to avoid changing anything any of the classes for the purpose of unit testing, since I am a big advocate of "never change your production code just for testing." You may argue that I have a "protected virtual void" event handler method there to leave room for myself for stubbing, but as far as event handling method goes, I think it is actually a good idea to allow my subclasses to override and extend my default implementation. This is the standard and encouraged way of writing and declaring event handling methods too in writing custom ASP.NET server controls. Check out Nikhil Kothari's book.

So, solution one, create a stub class for our Battery class in testing Laptop, and add extra methods to manually raise the events:

public class BatteryStub : Battery {
privately bool lowBatteryExecuted = false;

public void RaiseLowBattery() {
Low(this, EventArgs.Empty);
}

protected override void OnLowBattery(object sender, EventArgs e) {
lowBatteryExecuted = true;
}

public void Verify()
{
if (!lowBatteryExecuted) throw new ApplicationException();
}
}

[TestFixture]
public class LaptopTests {

[Test]
public void StartCountdownWhenLowBattery() {
IBattery batteryStub = new BatteryStub();
ILaptop laptop = new Laptop(batteryStub);

batteryStub.RaiseLowBattery();

// Assert laptop countdown started.

battery.Verify();
}
}

That's a lot of code to just unit test a single event is wired correctly. Also this stub is really doing a lot of a mock's work. Look at the Verify() and the simplistic stubbed event handler method. The fact that they are there and are simply is because in testing we are not interested in what they do, but that they are getting called. Now, duplicate this kind of test stub class for every object you have events, and you will quickly lose appetite on how many you have to write for all your domain objects.

Fortuntely there is a second solution, if you use NMock 1.1:

(credit to my co-worker and talented friend Levi Khatskevitch)

public class DynamicEventMock : DynamicMock
{
private const string ADD_PREFIX = "add_";
private const string REMOVE_PREFIX = "remove_";

private EventHandlerList handlers = new EventHandlerList();

public override object Invoke(string methodName, params object[] args)
{
if (methodName.StartsWith(ADD_PREFIX))
{
handlers.AddHandler(GetKey(methodName, ADD_PREFIX), (Delegate) args[0]);
return null;
}
if (methodName.StartsWith(REMOVE_PREFIX))
{
handlers.RemoveHandler(GetKey(methodName, REMOVE_PREFIX), (Delegate) args[0]);
return null;
}
return base.Invoke(methodName, args);
}

public void RaiseEvent(string eventName, params object[] args)
{
Delegate handler = handlers[eventName];

if (handler == null)
{
if (mockedType.GetEvent(eventName) == null)
{
throw new MissingMemberException("Event " + eventName + " is not defined");
}
else if (Strict)
{
throw new ApplicationException("Event " + eventName + " is not handled");
}
}

handler.DynamicInvoke(args);
}

private static string GetKey(string methodName, string prefix)
{
return string.Intern(methodName.Substring(prefix.Length));
}
}

Now, in your test class:

[TestFixture]
public class LaptopTests {

[Test]
public void BatteryLowIsRaised()
{
DynamicEventMock mockBattery = new DynamicEventMock(typeof(IBattery));

ILaptop laptop = new Laptop((IBattery)mockBattery.MockInstance);

mockBattery.RaiseEvent("PlayClick", EventArgs.Empty);

// Assert the laptop instance's 15 mins count down started

mockBattery.Verify();
}
}

Should the Low event wasn't wired, this test fails. You have explicitly told the mock object to raise its event, and assuming your events are wired correctly to the correct event handler, you have control over when to fire them.

There are drawbacks, of course. Notice the event name is represented by a string, making event renaming a pain to do, as it is for NMock for method expectations. My only advise is try out EasyMock.NET if that is a real pain for you.

Ruby on Rails demo

A lot of buzz has been generated by Ruby, and given that Ruby on Rails pushes that hype to another level it sure is worth a look. This video from rubyonrails.com is a great tutorial on what is Ruby on Rails and how it works.

http://www.rubyonrails.com.nyud.net:8090/media/video/rails_take2_with_sound.mov

Friday, September 23, 2005

Container framework in .NET - yes - 1.1

Haven't blogged for a good while... =P

I have been looking at the System.ComponentModel namespace. It is obviously an area where I have constantly overlooked. What is in there? There is a ton in there that the Visual Studio .NET IDE extensively uses, so it means it is useless to us as developers, right? Maybe not.

Recently I have found myself interested in digging deeper into PicoContainer.NET. It allows you to design better OO business objects by decoupling your business objects from one another (through IoC). For those who aren't familiar with IoC (Inversion of Control), basically it means in this context instead of having object A to instantiate and use object B in it, object A will ask for an instance of object B in its ctor at its construction time. How it helps OO design is that now object A no longer has a irreplaceable link to object B, thus they are decoupled, and it allows us to test object A easily by either stubbing or mocking out object B.

In the above example, object A and object B are "Components". They will be put in a "Container" and Pico will automagically instantiate object B when you request for an instance of object A.

Back to the System.ComponentModel namespace, it also contains interfaces IContainer, IComponent. Now things get interesting, each IComponent is called "sited" after being added into a IContainer (like the glue between the Container and the Component). A component can now call base.Site.GetService(typeof(anotherComponent)) to access another component's functionality. For our example, in object A's ctor, it can call base.Site.GetService(typeof(ObjectB)) to retrieve an instance of object B and create itself, without having to know how to "hard create" an instance of object B.

How does it help testing? For testing object A, one can stub or mock out its Site property and provide a testing implementation when its GetService() is getting called. This pattern (or good practice) is very important to design decoupled OO systems.

So when to use what? My take is that one should use Pico in your bootstrap class (public static void Main(args[])), and since it is considered harmful to use Pico in anywhere deeper than your bootstrap class, I will consider using the System.ComponentModel stuff in everywhere else I think using a Container-Component pattern will help decoupling my design.

Some excellent reads on the topic:
PicoContainer
[Urban Potato] Geek: System.ComponentModel
[Daniel Cazzulino] Lightweight Containers and Plugin Architectures: Dependency Injection and Dynamic Service Locators in .NET

Friday, June 10, 2005

Want to whip up some quick UI Tree?

I had to produce for one of my clients some form of UI Tree to help them to focus on how various pieces of user interactions with the system is going to take place from a UI perspective. It went from paper bubbles to Visio-lizing it and client still don't like it. Finally, I stumbled across this product that saves the day.

It is basically a map of thoughts organized in a click-me-and-drill-down-as-you-go application. The point is, it proides a very easy drag-and-drop tree creating inetrface to do the job very quickly.

At the end of the day this did wow the people who saw it, and it is extremely easy to use. It got the job done. I am however interested in the many ways of people who create the so-called UI Tree how they do it.