Showing posts with label .net. Show all posts
Showing posts with label .net. Show all posts

Tuesday, December 04, 2007

The last "D" in TDD means more than just "Development"

When asked "Do you write tests?", a lot of developers these days will say "of course" as their answers. However, not everyone can admit to doing TDD (Test Driven Development) correctly. Test Driven Development says, a developer will write a test that fails first, then write code to make the test pass, and refactor when possible, and repeat. This is what most people's TDD rhythm is. For the most part this is fairly easy to do. But to reach the next level, one has to understand TDD as a tool: TDD means more than just test your own code. Here is a couple tips on what the last "D" means:

Discipline

It takes a great deal of discipline to even write a failing test before writing the actual code. Sometimes, we write a little seudo-code here, or move a method definition there, or changing code else where trying to see if more new code needs to be written after it, and sooner than you think you are writing the actual implementation of the methods you wanted to test (Test Afterwards Development anyone?). Other times you write the test, but you are too anxious to even run it and see it fails. And other times you want to jump into the actual code immediately when you see your new test fails, but failing for the unexpected reasons.

Don't fall into these traps. If anything is true, testing is hard, but it is at the same time rewarding and fun. What's also true is, it will pay off. Write the failing test, draw up your list of tests you will need to write, and satisfy them one by one. Having discipline is the cornerstone of becoming a better programmer.

Design

It takes too long to write a test? Tests are running too slowly? Are your tests difficult to read? Are they too brittle and fail all the time? Hang in there! You ever had the feeling you saw code in the codebase that irks the living hell out of your mind written by someone else on your team? Well, it is time for you to get some of these feedback about your own code. Yay, your code sucks! Your tests are telling you that! Let's address each of these one by one.

Slow running tests? You shouldn't be hitting a database or web service in your unit tests, because you can mock/stub them out. Difficult to mock/stub it out? There probably is a better way to design your classes your tests are hitting. Ever heard of Inversion of Control (or Dependency Injection)? Master them. True TDD masters use them extensively.

Unreadable tests? Is it because of too many mocks/stubs? Or is it the code is 500 lines long and doing high octane 720-double-backflip logic? Either way, you have to learn to like small objects. Check this blog post of mine out.

Hard to test something? Tests too brittle? Perhaps you have encapsulation issues in your class design. If your classes are referencing 15 other neighbors, of course they are hard to mock/stub. Chances are, you have to spend time to debug your tests to find out what's wrong! Heard of Law of Demeter? Even if you have, take a look at this highly entertaining yet informative post. It might change your perspective a little.

The bottom line is, TDD is a way to guide you to writing good code, but only if you know how to use it as a tool. Now that you know, hopefully you will have a new perspective next time you write a test.

Sunday, September 24, 2006

Enhance your irb experience on Windows

You can extend the functionality of your irb on Windows by creating a file .irbrc in your %userprofile% directory. Put some Ruby code in there, and they will get loaded when you launch your irb, as well as your script/console. I have put in some code snippets in there to aid my irb experience.

(You may have issues trying to create a file with its name beginning with a period on Windows Explorer. Try to run the command "notepad .irbrc" in your cmd.exe)

Tab Completion

require 'irb/completion'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
Do you miss intellisense? If you do this, then in irb, type in like "text".s[tab][tab] will give you a list of methods in String that starts with s.

Ruby Interactive (ri) reference in irb
def ri(*names)
system(%{echo | ri #{names.collect { |name| name.to_s }.join(" ")}})
end
Then you can type ri 'String.strip' to see the Ruby index. The argument has to be a string though.

Remember, on a Windows machine, you have to put "echo | " in front of your ri line or else your irb will just return 'false'. I know it's counterintuitive that it isn't at the end, but it works.

Clear screen
def cls
system('cls')
end
I always wanted clear screen...

Console messed up with long irb lines
If you have a line of Ruby code that is way too long, and you want to go back and make changes, on Windows console it is not very friendly as it will almost guarentee to mess up your edits and disorient your typings. The only way I Googled on how to fix this is to take away the "--readline" switch from the Tab Completion tip above, and replace it with "--noreadline". But then you lose Tab Completion of course. I haven't found a workaround for it yet, but in the mean time I will happily just use Cygwin bash shell =)

Wednesday, July 19, 2006

Applying PicoContainer.NET with Presentation Patterns - Part II

(Part I)

Let's think about what Pico is good at in practical sense. I think Pico is great at wiring dependencies together. That means, it is good at wiring dependencies starting from your Presentation Model/Presenter layer and back, because these are all classes that you have complete control over. For your Views, at least if you develop in Visual Studio .NET, the restriction on their default constructors conflicts with the way Pico works. There are ways around it (setter injection as said in Part I), but they are ugly.

But what if I don't register my Views into my Pico container like other classes? Then the question becomes: how can my View get a reference to its dependent Presentation Model/Presenter?

Before I show you my solution, I have to say one more thing. The method InitializeComponent() synonymously refer controls as components for a reason. Every control in .NET is a component. What is a component? It is something you put in a container. Every container has many components. So yes, I am telling you that these controls/widgets are all being put in a container (not Pico) in the .NET control hierarchy framework. So what does each control being a component in this .NET container hierarchy enable me to do? It allows you to have access to the functionalities from other components in the same container. Let me rephrase: each View, being a component, can have access to other classes like a Presentation Model/Presenter, so long as they are all in the same .NET container hierarchy framework. Didn't I just say that this container framework is not Pico? Yes, I did, but it doesn't mean we have to use only one over the other. We can use them both together to each of their strengths to achieve the best of both worlds. Let me explain.

We have already said using Pico container to host everything starting from the Presentation Model layer is a good thing. So here is some example code on how to do this:

        private static IMutablePicoContainer createMutablePicoContainer()

        {

            IMutablePicoContainer pico = new DefaultPicoContainer();

            pico.RegisterComponentImplementation(typeof(IPageOnePM), typeof(PageOnePM));

            pico.RegisterComponentImplementation(typeof(IPageTwoPM), typeof(PageTwoPM));

            pico.RegisterComponentImplementation(typeof(IWebService), typeof(WebService));

            return pico;

        }



In order to allow the Views to have access to other components (Presentation Model/Presenter), we have to create a .NET container. It is just a class that subclass from System.ComponentModel.Container. I am going to call this an ApplicationContainer to avoid being confused with our Pico container.

        internal class ApplicationContainer : System.ComponentModel.Container

        {

            // ...

        }



To put our Views into this ApplicationContainer, you instantiate an instance of it, and put the Form object that you will start your application with into it like this:

        [STAThread]

        static void Main()

        {

            ApplicationContainer applicationContainer = new ApplicationContainer();

 

            MainForm form = new MainForm();

            applicationContainer.Add(form);

 

            Application.Run(form);

        }



From our Views, the method that they will use to get access to other components is called GetService(Type serviceType). When this method is called from within our Views, if our Views are put in a System.ComponentModel.Container, by default the method will ask for its containing container to traverse all registered components and see who can provide this "service" to it. If it finds such component, the container will return it, and now the requesting component gets a reference to that object. How does the container traverse its registered components and decide to give the component requesting a service the service that it asks for? Well, interestingly a System.ComponentModel.Container also has its own GetService() method to do just that. Now, since we have our own subclass ApplicationContainer, what if we override its GetService(), and while our ApplicationContainer object receives a request for service from any of its components, we can instruct it also look to see if Pico has the stuff that the requesting component has. More concretely, when a View uses GetService(typeof(MyPresentationModel) to get its Presentation Model/Presenter dependency, ApplicationContainer will ask for a Pico container that has already been fully registered to return an instance of that class if it is found, like such:

        internal class ApplicationContainer : System.ComponentModel.Container

        {

            private IMutablePicoContainer _pico = createMutablePicoContainer();

 

            protected override object GetService(Type service)

            {

                object instance = _pico.GetComponentInstanceOfType(service);

 

                if (instance != null)

                {

                    return instance;

                }

 

                return base.GetService (service);

            }

        }



To sum it all up, you need to do the following to get things to work:
1. Create an ApplicationContainer class subclassing System.ComponentModel.Container.
2. Add your starting Form into the ApplicationContainer instance, prior to starting it.
3. Set up a Pico container within the ApplicationContainer instance.
4. Register all dependencies that your Presentation Model/Presenter classes will need in your Pico container. You do not need to register your Views.
5. Override the ApplicationContainer's GetService() method, make it to look further into its already setup Pico container for anything that it should return.

Now from your Views, you can gain access to its dependency, in this case a Presentation Model/Presenter, by calling:

        private void PageOneView_Load(object sender, System.EventArgs e)

        {

            // Add this View to ApplicationContainer. Otherwise we have to instantiate

            // each and every view in public static void Main() and do the adding there.

            base.FindForm().Container.Add(this);

 

            // This GetService() call will now find what we need in ApplicationContainer.

            IPageOnePM service = (IPageOnePM)base.GetService(typeof(IPageOnePM));

        }



And modify your PresentationModel's constructor to include an additional parameter to take in the web service class. Then your class can start using the web service functionality, while in unit testing you can mock/stub it out!

    public interface IWebService

    {

    }

 

    public class WebService : IWebService

    {

    }

 

    public class PageOnePM : PresentationModel, IPageOnePM

    {

        private IWebService webservice;

 

        public PageOnePM(IWebService webservice)

        {

            this.webservice = webservice;

        }

    }

 

    // ApplicationContainer class

    private static IMutablePicoContainer createMutablePicoContainer()

    {

        IMutablePicoContainer pico = new DefaultPicoContainer();

        // ...

        pico.RegisterComponentImplementation(typeof(IWebService), typeof(WebService));

        // ...

        return pico;

    }



So now, we have eliminated the child user control not knowing how to get a Presentation Model/Presenter problem, because a user control is also, well, a component in the same ApplicationContainer. We have also solved the ugly setter injecting child user controls' dependencies problem. You also did not modify a single View default constructor! We can now happily use our Visual Studio .NET IDE to do WYSIWYG design and manage good OO design, plus Inversion of Control-ing our dependencies.

After-thought: Though the title of these two posts say Presentation Patterns, in my mind they are more geared towards just for Presentation Model, due to in my opinion the difference in directional references between Presentation Model and Model-View-Presenter. I mentioned briefly about this in my earlier post here.

By the way, note that now each page can have access to multiple Presentation Model objects, instead of the what-it-used-to-be 1-to-1 relationship between a page and its Presentation Model, so one can do something similar to Ruby on Rails where each View can make calls to multiple Controllers which operates on various Models to complete the desired action! This makes code-sharing between Presentation Models much easier, and also each Presentation Model can be named not after their page but by application functionality!

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, 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.

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, 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

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 o