Saturday, November 29, 2008

Marick's Law

This delightful post from Robert "Uncle Bob" Martin describes with much better sentences what I was trying to express with my latest post Professional Under Pressure.

When it comes to code, it never pays to rush.

I also need to get myself one of those talking green wrist bands for Christmas :-).

Thursday, November 27, 2008

Professional Under Pressure

A first delivery of our current project is going into production very soon. The team has worked hard and is still working very hard to straighten out the last issues. As with every delivery, pressure always rises a tiny bit. This is were the men are separated from the boys.

We have all been in those situations. When your boss or the entire management team is breathing down your neck in order to put out that delivery. Pressure is something we have to deal with in our day-to-day lives. Everything goes fine until you discover some hiatus in your otherwise perfect code. This is were professional, disciplined developers really shine. The reaction of most developers in this scenario is to hack their way to glory so they can compile and put out the bits as soon as possible. At one (probably more) point in our careers, we've all said that popular sentence that makes me cringe:

'You know what? We'll provide a quick & dirty solution now and come back to the code during the next sprint'

Well, I've got a newsflash coming up: there will be no next sprint and when there will be a next sprint, you won't have the time to refactor that particular piece of crap.

O well, then we will fix it the next time we have to change or extend that particular piece of code. Wrong again. There will be not next time. There is no tomorrow when it comes to writing clean code. If you don't deliver quality today, then you won't deliver anything at all tomorrow.

Writing a quick hack in otherwise good code introduces a broken window. The next developer that comes along and starts changing the code, notices the broken window and starts smashing some more. Before you know it, you're once so perfectly developed code is now a big ball of mud. I don't know about you, but if I would ever buy a new house then I certainly won't start smashing in windows. Why do we do that to our code and think that its a good idea at the same time?

If you thought that writing clean code is hard, then keeping code clean is even harder and requires pure discipline of everyone on the team. We like to believe that putting a quick & dirty hack in the code delivers value, but instead we achieve the exact opposite. The only way we can deliver value, even when we are under pressure, is providing the most elegant and simple solution we can think of. Developers who prefer a quick & dirty solution instead of a good and clean solution simply refuse to think about the problem at hand. Refusing to think is probably the worst thing we can do to our customers.

These are just some thoughts and observations I had over the last couple of weeks. Pressure is something that helps me to focus and brings out some of my best thinking (taking into account my mental disabilities).

Till next time

Wednesday, November 26, 2008

How TFS Lost my Trust

This morning, I spent the first 30 minutes of my day figuring out why the CI build failed after I checked in some changes to the code. No big deal, right? I just messed up. Turns out that I didn't screw up the code but TFS did.

Before committing the code to the source repository, I merged with the latest version on the trunk and ran all the unit tests. Everything was fine and dandy. After I checked in the code, TFS decided in all its wisdom to not update 5 source files, which were randomly picked of course. I didn't get any errors when I committed the code, so I was completely unaware of any problems whatsoever.

When I noticed that the CI build had failed, I naturally tried to figure out what was going on. From the build log I noticed some compiler errors about classes that couldn't be found. I checked and double-checked whether I forgot to commit them, but I didn't.

This is something that happens about once or more times a week. To fix this again, a colleague has to update its local copy of the source code and determine which files are skipped by TFS. Then I have to 'touch' those files on my machine and check them back in. At this point, valuable time of two persons is wasted.

I strongly believe that a source control system is the backbone of any proficient and productive development team. If you can't rely on a stable source control system, then what's the point? I consider TFS to be seriously broken. The upside of this sad story is that I've really come to appreciate a stable source control system like Subversion and the people who spent their free time in order to accomplish that.

There, I've got it out of my system. I can breathe normal again.

Sunday, November 23, 2008

NHibernate Fact when Saving a Transient Entity with Second Level Caching Enabled.

After attending the Advanced NHibernate workshop at the Kaizen Conference, I started to do some experimenting with NHibernate in order to gather more in dept knowledge about my favorite ORM tool. A topic that quite interests me about NHibernate, is its support for caching. NHibernate currently comes with 5 different caches:

  • Identity map (Session)
  • Entities cache (SessionFactory)
  • Collections cache (SessionFactory)
  • Timestamp cache (SessionFactory)
  • Query cache (SessionFactory)

The identity map is known as the first level cache, while the last four cache types in the list are all part of the second-level cache. Gabriel Schenker wrote a magnificent article on The NHibernate FAQ that provides a great overview of the different caching options available with NHibernate.

There is one point that I want to add to this article that may be unclear about using the second level cache. Gabriel mentions that when a transient entity is saved to the database, NHibernate automatically puts the date of the new entity into the second level cache. This is most certainly the case, but under one condition. A transient entity is added to the second-level cache only if its identifier is not automatically generated by the underlying database. Let me show a quick example.

Suppose I have an entity named User whose Id property is configured like the following:

    <id name="Id" type="Int32">
        <column name="Id"/>
        <generator class="native"/>
    </id>

When an new instance of User is saved in the database, NHibernate doesn't put the data of the entity in the second level cache. When this particular entity is retrieved using a different session than the session that saved the new entity in the database, NHibernate issues a query to the DB instead of retrieving it from the second level cache.

Suppose we change the mapping of the Id property to something like this:

    <id name="Id" type="Int32">
        <column name="Id"/>
        <generator class="assigned"/>
    </id>

When retrieving this entity from a different session, NHibernate now reconstructs the entity from the data in the second level cache instead of sending a query to the database.

This little nuance had left me completely in the dark until I read this post on the NHibernate user group. In case of auto-generated identifiers, NHibernate doesn't store the data of the transient entity into the second level cache because it has to hit the database anyway for retrieving the value of the corresponding identifier. Maybe this will change with NHibernate 2.1? Who knows?

I hope this clears things up.

Sunday, November 16, 2008

Chain of Responsibility Using Castle Windsor and a First Experience With StructureMap - Part 2

In my previous post, I outlined an issue that I had with Castle Windsor for configuring multiple chains of responsibility. I want to have different ProcessConsumer classes that require a slightly different chain of processors:

ProcessConsumer1 -> Processor1 -> Processor2

ProcessConsumer2 -> Processor3 -> Processor1 -> Processor2

Solution with Castle Windsor

For achieving this scenario using Castle Windsor, without it throwing a CircularDependencyException at me, I needed to split up the IProcessor interface and the BaseProcessor class like so:

public interface IProcessor { void Process(Request request); } public interface IChainableProcessor : IProcessor { IProcessor Successor { get; set; } } public abstract class BaseProcessor : IProcessor { public virtual void Process(Request request) { // Some base class behaviour FurtherProcess(request); } protected abstract void FurtherProcess(Request request); } public abstract class BaseChainableProcessor : BaseProcessor, IChainableProcessor { public IProcessor Successor { get; set; } public override void Process(Request request) { base.Process(request); if(null != Successor) { Successor.Process(request); } } }

Chainable processors can now derive from the BaseChainableProcessor class and those processors that should come last in the chain can continue to derive from the BaseProcessor class.

This approach no longer results in circular dependencies. Although it works, I don't like this solution that much because now I can no longer change the order of responsibilities by simply altering the IoC container configuration. If I want to achieve that, I possibly have to change some code as well. This also means that some processors must always come last in the chain, which is not always feasible in complex scenarios.

Solution using StructureMap

One of the things I want to explore in the next couple of months is StructureMap. I was wondering whether this particular IoC container can solve this issue without having to split up the IProcessor interface and BaseProcessor class. It appears that StructureMap can indeed handle this scenario in a graceful way. I just needed to rip out Castle Windsor and replace it with the StructureMap goo. Below you can see the DependencyContainer class that I've been using for this example:

public class DependencyContainer { public void Configure() { ObjectFactory.Initialize(x => { x.AddRegistry(new CORRegistry()); }); } public T Resolve<T>() { return ObjectFactory.GetInstance<T>(); } }

Really straightforward stuff. I derived a class from StructureMap's Registry class and added it to the ObjectFactory. Here is the code for my derived registry class:

public class CORRegistry : Registry { protected override void configure() { ForRequestedType<IProcessor>() .TheDefault.Is.OfConcreteType<Processor1>() .WithName("Processor1") .SetterDependency<IProcessor>() .Is(y => y.OfConcreteType<Processor2><()); ForConcreteType<ProcessorConsumer2>() .Configure .CtorDependency<IProcessor>() .Is(x => x.OfConcreteType<Processor3>() .SetterDependency<IProcessor>() .Is(y => y.TheInstanceNamed("Processor1"))); } }

That's all I had to do. Everything just works now. I really like the way StructureMap handles things (registry classes) and its configuration is quite easy. This code could probably be improved as these are my first baby steps as a noob. This first pleasant experience certainly motivates me to do some more goofing around with StructureMap.

As always, I'm open for suggestions.

Till next time,

Jan, the injected

Chain of Responsibility Using Castle Windsor and a First Experience With StructureMap - Part 1

A couple of months ago, I applied the Chain of Responsibility pattern for the very first time. I've never encountered a scenario before where applying this pattern would be a valid option. But now, after some refactoring, I somehow naturally ended up applying this rarely used design pattern. Lets dive into some code, shall we?

public interface IProcessor { IProcessor Successor { get; set; } void Process(Request request); } public abstract class BaseProcessor : IProcessor { public IProcessor Successor { get; set; } public void Process(Request request) { // Some base class behaviour FurtherProcess(request); if(null != Successor) { Successor.Process(request); } } protected abstract void FurtherProcess(Request request); }

This is the base class for all processor classes (bad naming, huh?) . If there is a follow-up processor available, then its Process method is called. The processor classes can now focus on their main responsibility:

public class Processor1 : BaseProcessor { protected override void FurtherProcess(Request request) { // Do something usefull } }

I'm using Castle Windsor to chain together the different processors in the particular order that I want. This involves setter injection for the Successor property. Although I'm not a huge fan of setter injection, in this case it seems like a viable option. The following example uses the fluent interface of Castle Windsor for configuring the container:

_container.Register( Component.For<ProcessorConsumer1>() .Named("ProcessorConsumer1") .Parameters(Parameter.ForKey("processor") .Eq("${Processor1}")), Component.For<IProcessor>() .Named("Processor1") .ImplementedBy<Processor1>() .Parameters(Parameter.ForKey("Successor") .Eq("${Processor2}")), Component.For<IProcessor>() .Named("Processor2") .ImplementedBy<Processor2>());

Nothing much to it. The ProcessConsumer class simply gets the first processor injected through its constructor. The above configuration results in the following chain:

ProcessConsumer1 -> Processor1 -> Processor2

Everything is fine and dandy so far. Now suppose that I want to add another ProcessConsumer that requires a slightly enhanced chain of processors like so:

ProcessConsumer1 -> Processor1 -> Processor2

ProcessConsumer2 -> Processor3 ->  Processor1 -> Processor2

This is how the configuration of Castle Windsor now looks like:

_container.Register( Component.For<ProcessorConsumer1>() .Named("ProcessorConsumer1") .Parameters(Parameter.ForKey("processor") .Eq("${Processor1}")), Component.For<ProcessorConsumer2>() .Named("ProcessorConsumer2") .Parameters(Parameter.ForKey("processor") .Eq("${Processor3}")), Component.For<IProcessor>() .Named("Processor1") .ImplementedBy<Processor1>() .Parameters(Parameter.ForKey("Successor") .Eq("${Processor2}")), Component.For<IProcessor>() .Named("Processor2") .ImplementedBy<Processor2>(), Component.For<IProcessor>() .Named("Processor3") .ImplementedBy<Processor3>() .Parameters(Parameter.ForKey("Successor") .Eq("${Processor1}")));

With this particular configuration, Castle Windsor now throws an exception with the following description:

A cycle was detected when trying to resolve a dependency.

After some investigation it seems that Castle Windsor wants to set the Successor property of Processor2 with the instance of  Processor1, which is not what I had in mind. The Successor property of Processor2 should remain empty. I believe this has something to do with the approach that Castle Windsor is taking to never inject a null reference, although I'm not completely sure.

Anyway, I got around this issue by splitting up the IProcessor interface and the BaseProcessor class as outlined in my next post.

Monday, November 10, 2008

Book Review : Beyond Code

Beyond Code I read Beyond Code during my flight to Austin for the Kaizenconf. It was a quite enjoyable book that focuses on how to distinguish yourself as a software developer.

As you may suspect, there is no code in this book. Instead, Rajesh Setty provides 9 simple steps that makes the difference between a code monkey and a caring, disciplined software professional.

If life as a whole is a game, then there are two kinds of games: the inner game and the outer game. The inner game we play with ourselves, while the outer game is played with the external world. Both games are important, so the author puts out a lot of advice to succeed in both of them.

Inner Game

  • Learn: Continuous improvement is key. This does not only mean how to dig new cool technologies, patterns and practices. This also means learning how to accomplish long-term relationships with other people, learning how to communicate with others, learning to be congruent and how to adapt quickly to ever changing situations.
  • Laugh: When you make a mistake, laugh about it, learn and move on.
  • Look: How to deliver beyond what is expected of us. Try to look beyond the horizon.
  • Lasting impression: Every opportunity you get is a chance to add significant value and an impact that doesn't go unnoticed.
  • Love: Just love your job.

Outer Game

  • Leverage: How to leverage as an individual and most importantly as a team. The most obvious leverage points are people, books, blogs, magazines, etc.
  • Likeability: I know I fail on this sometimes, but one can accomplish far more if others like us. If we are not likeable, then things can get quite difficult sometimes.
  • Listen: Start listening to start succeeding.
  • Lead: Look for opportunities to lead. Try to identify voids and step into the gap. You can take advantage of these leadership moments.

Doesn't this get you interested? Tom Peters ends his foreword with the sentence "Read this book as if your life depends on it. It does!". Strong words, slightly exaggerated, but somewhat truthful as well. This book contains a lot of good advice. It's only 120 pages, so what do you have to loose?

Till next time

Sunday, November 09, 2008

Be careful with optional parameters in C# 4.0

I've been playing with the Visual Studio 2010 CTP bits, and I tried to see what named and optional parameters in C# 4.0 can bring to the table. Although they are minor language enhancements at best, they can cause a lot of grief as well.

In my former life as a C++ developer, optional parameters were quite handy in some cases to remove some ceremonial code for providing obvious overloads of a method. Since I came over to the .NET platform, I actually don't miss optional parameters. I just wanted to share a common abuse of optional parameters that you should be aware of. The following code illustrates this:

public class Base { public virtual void Foo(Int32 x = 1) {} } public class Derived { public override void Foo(Int32 x = 2) {} } ... Base f0 = new Base(); f0.Foo(); // Invokes Foo(1) Base f1 = new Derived(); f1.Foo(); // Also invokes Foo(1) Derived f2 = new Derived(); f2.Foo(); // Invokes Foo(2)

This is something you have to watch out for. The object's member function silently takes different arguments depending on the static type you use. This violates the principle of least surprise and is a general PITA. Don't violate the method contract that has been provided by the base class.

Don't say I didn't warn you ;-)

Wednesday, November 05, 2008

Kaizenconf Part 3 - Taking Action

The last day of the conference was all about taking action as a community. Which actions should be taken based on the open-space sessions of the day before? I attended the ESB Patterns session which mostly handled actions for the MassTransit open-source project. Again, the notes of the other "action" sessions are available on the wiki.

I gained a lot of new insights from being at this conference and I realized that I need to learn some more. I know that its kind of early for New Year's resolutions, but I want to put out a number of actions for myself.

  • Learn more about ESB/integration patterns. Diving into the code of MassTransit and NServiceBus will probably give me more insights.
  • I need to get up to speed on web development really soon. I finally need to be proficient at JavaScript, CSS and jQuery.
  • On the programming language front, I need to get back to Boo and want to add Ruby and F# to my tool belt.
  • I've been a fervent user of Castle Windsor for my IoC needs, but I also want to take a look over the fence by leveraging StructureMap because I have the feeling that I'm missing out on some cool stuff.
  • Determining which NHibernate contrib projects can be useful, like NHibernate Search, NHibernate Burrow, NHibernate Caching, etc. ....
  • And last but not least, improving on my development methodologies by learning more about Lean, Kanban, the Toyota Way, etc. ...
  • Further improving my DDD and BDD skills.

I know that this is very ambitious, but hey, it's my list. I hope that I can look back at this post next year while having learned and accomplished most of the items on this list.

I want to round of this post by saying kudos to Scott Bellware, Dave Laribee and all other attendees for a wonderful learning experience.

Also a special thanks to Michael , Conrad and the other guys for driving and letting me and Peter tag along.

IMG_4905

I also finally got to meet fellow Elegant Coder Jarod Ferguson and others who I previously only knew by name or blog picture. I really enjoyed it.

Till next time

Kaizenconf Part 2 - Open Space

After the pre-conference workshops, it was finally time to kick-off the open-space conference itself. Before Steven "Doc" List held his opening speech, Oren and Glenn couldn't wait and began sharing their thoughts:

IMG_4888

After the fish-bowl session, the self-organizing geek thing happened and resulted in a number of sessions on the board.

IMG_4902

On the next morning, a long and exhausting day was ahead of us. A wide variety of topics where chosen, so I needed to make some though decisions about which sessions I was going to attend. You can have a look at the Kaizenconf wiki for all the open-space sessions (as well as the workshop sessions) and the notes that where made during these sessions by the different people who were there.

I attended the following open-space sessions:

A lot of great conversations and I wished that I could split myself up so that I could be in several session rooms at once. Keep an eye on the wiki that I just mentioned, because links to the different video recordings will be posted there.

Kaizenconf Part 1 - Workshops

My colleague Peter and myself got back yesterday from Austin, Texas where we had one of the greatest learning experiences ever: the Kaizen Continuous Improvement Conference. I've really been looking forward to this event and it exceeded my already high expectations.

Before the actual open-space conference, there were two days with workshops. In this post I want to highlight some things I learned from these workshops.

Advanced NHibernate (Ayende Rahien)

I guess that the speaker of this session needs no further introduction. As one of the major contributors of my favorite ORM, he is the right person to talk about some of its advanced usages.

IMG_4877

Here are some random notes:

  • The NHibernate profiler looks really cool.
  • NH is not a 100% solution. Only use NH for an OO view of the world. If you're only interested in data or transforming/reporting, then use something else.
  • A single session can have multiple transactions.
  • NH 2.1 adds PostSharp support for removing the need for virtual properties/methods (proxies/lazy loading).
  • Adaptive Domain Models (e.g. Rhino Security)
  • Multitenancy (e.g. different domain models or databases for different customers).
  • NH profiler is freakin' cool.
  • NHibernate Search = Lucene.NET + NHibernate.
  • Lucene.NET: file store + full text search.
  • FullTextSearchSession only necessary for full text search (through its extra methods). Using a regular NH Session also ensures that the Lucene.NET index gets updated.
  • NHibernate uses 4 different caches:§ First level cache (also identity map at the session level)

    § Second level cache (session factory level)

    • Entities cache
    • Collections cache
    • Timestamp
    • Query cache
  • Enable second level cache at entity level in the mapping files. This also goes for the collection and the entities that populate the collection!!
  • Enable query cache -> SetCacheable(true) on criteria query and enable query cache in the configuration file.
  • Cache regions -> SetCacheRegion on criteria query.
  • Prevalence cache can best be used for smart clients (single machine).
  • SysCache uses the ASP.NET caching (single machine).
  • SysCache2 provides support for SQL dependencies for the ASP.NET cache (not recommended).
  • MemCache is used for distributed applications.
  • Velocity is also used for distributed applications.
  • Did I already mention that the NH profiler is really cool, because it is.

DDD Chalk Talk (Dave Laribee)

This session was a real mind stretcher for me. I've come to realize that I need to reread the "blue book" again. I've got way too many notes from this workshop. I'll just put out some of the topics that were discussed:

  • DSLs in relation to Rich Domain Model
  • Publishing vs protecting a model
  • Verbs vs Domain services
  • Command Query Seperation
  • Model Controller
  • Test models (Michael Feathers)
  • How to introduce/get started with DDD
  • Complexity
  • Bounded context vs Context maps

I saw that a lot of people were recoding this session, so I have a suspicion that it will become available somewhere very soon.

Using and Abusing ASP.NET MVC for Fun and Profit (Jeremy D. Miller and Chad Meyers)

Jeremy and Chad shared their opinionated approach to using ASP.NET MVC for efficiently creating web applications. This very neat stuff is already lined out by this post from Jeremy. I heard some rumors on Twitter that Chad is working on releasing some of the code as open-source. The videos of this workshop are available here.

Presentation Patterns (Jeremy D. Miller and Glenn Block)

This was probably one of the highlights of the pre-conference workshops. There was this amazing back and forth between Jeremy and Glenn that I just forgot to make notes. I hope someone recorded this "masterpiece" because I want to watch it again. I thought that I already knew a lot about Passive View, Supervising Controller, Presentation Model and other companying presentation patterns. I soon realized that I am just a noob and took away lots of stuff from this session.

After the workshops, the open-space conference could finally begin ...