Premature Abstraction

The first time I read the GoF book, I didn’t understand it. This was because I didn’t had a decent understanding of the principles of object-oriented programming at the time. A while after, I read the book Design Patterns Explained. In this excellent book the author formulated the core thought behind the design patterns in the GoF book. He states that when a particular concept varies, it should be encapsulated (by means of an abstract class or and interface). This was a real eye opener for me and guided me to understanding the design patterns described in the GoF book.

But what I also learned after several years is that introducing abstractions in code is not a free ride either. There is a time and place where you want abstractions. I used to add abstractions in domain models all over the place, as soon as I possible could. Now I try to avoid them until the last responsible moment. Only when I gain a deeper understanding, when I start to see variations of the same concept popping up, when concrete implementations start to cause pain, only then am I prepared to consider adding a new abstraction.

Suppose that we have the concept of a communication channel in a particular domain model. If we have more than one communication channel, say SMS, telephone and email, then an abstraction is warranted. Then we might want to introduce an ICommunicationChannel interface. But if we only have SMS as communication channel, then no abstraction is needed. If new communication channels are being added over time, only then do we refactor the code.

Sometimes my brain tricks me into the premature abstraction path. It also happens that I’ve postponed introducing an abstraction a bit too long. I do make mistakes. Who knew? But I do gained some awareness over the years.

Boise Code Camp 2011–WPF for Dummies and Model-View-ViewModel (MVVM) Explained

Wow…  Boise Code Camp rocked this year.  There were great presentations, great people, and great conversations.  You even had an occasional code pairing.  Not to mention the two XBOX Kinects to help fill in the time between sessions. 

This year I only gave two presentations; WPF for Dummies and Model-View-ViewModel (MVVM) Explained.  If you are looking for the code I demoed during one of the presentations you can download them from the links provided below:

  1. WPF For Dummies
  2. Model-View-ViewModel (MVVM) Explained

Thanks to everyone who attended the event this year, and a special thanks to those who attended my sessions. You know who you are ;0).  If you would like more information on or related to anything I presented on the easiest way to find me is on Twitter @BrianLagunas.

Could sealing a class be a sign of a good design

I recently attended this years Øredev conference and one of the things I had the good fortune of doing was to meet-up with a long time twitter friend, Philip Laureano. One of the days me and Philip started talking about a previous discussion he had with another attendee (whom shall remain nameless since I do not know the full details of his exact opinions). Anyway, the short version is that the person suggested that classes should be sealed by default, or at least have the developer explicitly state if the class should be sealed or closed.

My immediate reaction was that this was a terrible idea and that I had been struck down too many times by sealed classes before. But then I started thinking that maybe it was not such a bad idea after all. Maybe it even was a sign of a well designed class and that more developers would be better of by sealing their classes.

Now let me inform you that I am still on the ropes about this, but I would like your thoughts on it. In fact I am hoping that the most interesting part of this post will end up being the discussion in the comment section.

So when you take a moment to think about the S.O.L.I.D principles, most specifically the Open-Closed Principle and Dependency Inversion Principle, a long with the old design principle of ‘Favor object composition over class inheritance’ then maybe it is not such a bad thing after all. Throw in interfaces into the mix and program to an interface and not an implementation, and it will enables you to create different branches if needed. If your classes can flourish while being sealed, chances are that you have some pretty nice structures code in your hands.

There probably are some legit reasons to not seal classes at time, despite the reasoning above, so I am not going to be definitive and say that is never the case. Voice your thoughts in the comments and let us see where this ends up – who knows, I might be left standing as a fool!

As always, you can find me on twitter by the name of @thecodejunkie

Now a Technical Contributor for PluralSight

If you haven’t noticed by now, I have been somewhat quiet in the community lately, but there are a few good reasons for that.  The first reason is that I have been working on my Extended WPF Toolkit project on CodePlex.  I also recently had a new baby girl, born just 4 months ago and haven’t been getting the necessary geek time I normally have. Babies seem to take up any free time you have and all the time you didn’t have. 

I am also excited to announce that I am now a technical contributor for PluralSight. You can check out my lame bio pic and corresponding verbage here.  Now, any speckle of free time I have goes into recording content for the On-Demand library.  I have recently published two modules; one covering the Model-View-ViewModel (MVVM) design pattern, and the other on the Decorator design pattern, both of which can be found in the Design Patterns Library.

During my interview process with PluralSight I had to create a sample video demonstrating a simple concept.  I chose to cover the WPF Eventing model.  Normally, these recordings are discarded and go to waste, never to been seen by anyone.  I have decided to not trash mine, and share with you my first attempt at recording a PluralSight On-Demand video.

Now remember this was my first attempt, and therefore falls within the “First time I did this so any mistakes are forgiven no matter what” rule.

wpf_events_video

Hopefully it didn’t completely suck and maybe you even learned something.  If you would like to test drive PluralSight, sign up for a guest pass. The guest pass is free and allows you to view a few clips from every module in every course in the On-Demand library.  What do you have to loose?  If you have any feedback please feel free to leave it below.

Don’t Give Up on the State Pattern Just Yet – Revisited

In my previous post on the subject, I showed how you can remove some of the friction caused by applying the State pattern. In fact, as some of you rightfully pointed out, this friction isn’t caused by the State pattern itself but by a violation of the Interface Segregation Principle.   The use of role interfaces somewhat mitigated this violation but caused some type checking and casting in the context class (named Account in our example).

I just wanted to put out a slight variation of our solution that defers this kind of type checking until runtime. In other words, we’re going to apply some duck typing in order to come up with some improvements.

But hang on, isn’t C# supposed to be a static language and isn’t duck typing an exclusive feature of dynamic languages like Ruby or Python? Heck no! One can have duck typing in a static language as well. A good example of this is the Boo programming language which is a static language but provides the ability to give up this safety net. But I do believe that dynamic languages like Ruby or Python provide a more supple syntax for supplying duck typing capabilities while a static language usually requires a bit more ceremony.

The latest C# 4.0 compiler delivers some dynamic language features using the dynamic keyword which in turn accomplishes it’s functionality by leveraging the DynamicObject class (which seems to live in the System.Dynamic namespace). I have to admit that I didn’t spent much time on this yet.

But while the rest of the world is still on .NET 3.5 or earlier versions of the .NET framework, we don’t have to wait until the next upgrade to use some of the dynamic language features like duck typing, mixins and the like.

Let me first show you the code of the Account class from the previous post that demonstrates the type checking and casting to a role interface: 

public void Withdraw(double amount)
{
    // One can not always withdraw
    if(false == CanWithdraw())
    {
        // Should throw an exception or at least a towel
        Console.WriteLine("No funds available for withdrawal!");
        return;
    }

    var canWithdraw = (ICanWithdraw)State;
    canWithdraw.Withdraw(amount);

    ...
}

private Boolean CanWithdraw()
{
    return State is ICanWithdraw;
}

What I would like to do is to remove the CanWithdraw check entirely without running into a NullReferenceException when a particular state doesn’t support withdrawing money. But first, I want to slightly decouple the Account class from the SilverState, GoldState and RedState classes by introducing an interface named IAccountStateChanger.

public interface IAccountStateChanger
{
    void InstituteStateTo(State newState);    
}

 

This is now used by the state classes to change the state of the Account class without using a property setter in order to get rid of the false sense of encapsulation. The implementation of this interface by the Account class is where the fun begins.

void IAccountStateChanger.InstituteStateTo(State newState)
{
    _state = newState;
    _dynamicState = new DynamicObject(_state) + _missingStateMethodHandler;
}

 

Besides having a state we also introduced a dynamic state which is simply an instance of Linfu’s DynamicObject class. I’ll talk about the missing state method handler part shortly, but first let’s look what we can do with our dynamic state object.

public void Withdraw(Double amount)
{
    var canWithdraw = _dynamicState.CreateDuck<ICanWithdraw>();
    canWithdraw.Withdraw(amount);
    
    ...
}

 

Notice that we got rid of the type checking part. But what if a particular state doesn’t support withdrawing money? Here’s were the method missing piece of the puzzle falls in. Linfu provides an interface named IMethodMissingCallback which lets you decide what to do when the requested method call cannot be resolved.

public class MissingStateMethodHandler : IMethodMissingCallback
{
    public void MethodMissing(Object source, MethodMissingParameters missingParameters)
    {
        if(typeof(ICanWithdraw).GetMethods()[0].Name == missingParameters.MethodName)
        {
            Console.WriteLine("No funds available for withdrawal!");
        
            // Let Linfu know we're on top of things        
            missingParameters.Handled = true;
        }
    }

    public Boolean CanHandle(MethodInfo method)
    {
        return false;
    }
}

 

You can do pretty much anything in here like delegating the call to another method, but for demonstration purposes we just write a message to console. As shown earlier we literally add an instance of this handler to the dynamic object and we’re all set up. Using this approach yields the same results but without the type checking.

I’d like to mention that I’ve been using the DynamicObject class from Linfu 1.0 which you can download here. For some reason this class hasn’t been included in the 2.0 release and higher which is a bit sad because I really like some of the possibilities it has to offer. I’ll cover some of these in one of my next posts.

Don’t Give Up on the State Pattern Just Yet

Last week, Greg Young wrote a blog post about State Pattern Misuse. In this post he talks about how ugly the State pattern can become if some operations are not allowed when the context object is in a particular state. The solution he proposes is to use a separate domain class for each state in the model so that it contributes to the Ubiquitous Language.

Just to be clear, I agree and value this approach when it makes sense in the domain model. However, I do not like to entirely give up on the use of the State pattern either. We can eliminate some of the friction by using a very simple approach, namely role interfaces.

To show you a simple example, I took the code of one of the samples on the DoFactory web site and put in some refactoring. Please take a look at the original code before reading any further.

Now instead of having abstract methods on the State base class, I created three separate role interfaces:

public interface ICanDeposit
{
    void Deposit(Double amount);
}

public interface ICanWithdraw
{
    void Withdraw(Double amount);
}

public interface ICanPayInterest
{
    void PayInterest();   
}

 

Both the SilverState and the GoldState class implement all these interfaces, but the one we’re particularly interested in is the RedState class because only deposits should be allowed for this state.

class RedState : State, ICanDeposit
{
    private const Double UpperLimit = 0.0;

    public RedState(State state)
    {
        Balance = state.Balance;
        Account = state.Account;
    }

    public void Deposit(double amount)
    {
        Balance += amount;
        StateChangeCheck();
    }

    private void StateChangeCheck()
    {
        if(Balance > UpperLimit)
            Account.State = new SilverState(this);
    }
}

 

The RedState therefore only implements the ICanDeposit interface. Just for the record, the code of the State base class is now dramatically reduced.

abstract class State
{   
    public Account Account { get; protected set; }
    public Double Balance { get; protected set; }
}

 

With this setup we can use these role interfaces in the Account class to determine whether a particular operation is allowed for the current state.

public void Withdraw(double amount)
{
    // One can not always withdraw
    if(false == CanWithdraw())
    {
        // Should throw an exception or at least a towel
        Console.WriteLine("No funds available for withdrawal!");
        return;
    }

    var canWithdraw = (ICanWithdraw)State;
    canWithdraw.Withdraw(amount);
    
    ...
}

private Boolean CanWithdraw()
{
    return State is ICanWithdraw;
}

 

This way we’re able to eliminate all operations that don’t make sense for a particular state while still being able to determine all of its capabilities when needed.

Hope this helps.

Where to start a new program

Here as an interesting question that popped up at my user group meeting last night, when you are starting a new program (green field development), where do you get started?  I find these questions interesting because there really is no correct answer, but a persons answer will tell you something about how they problem solve.

Depending on who you ask you will likely get one of two answers.  If you are talking with a data guy, he will say to start with the database.  If you are dealing with a visual guy, he will say to start with the UI.  Historically, I did a conglomeration of those two ideas, creating both the UI and the database at the same time, letting the two drive each other.  But I’m weird, I’m a visual/data guy.

Lately though, I’ve started to thing about a third approach.  Starting in the middle.  No UI, no database, just the data classes.  This approach has been spurred on buy a couple of things.  Namely, test driven development (TDD), design patterns, and domain driven design.

TDD really is the glue that allows all of this to happen.  I can start in the middle because I can run the code in the middle any time I want.  I just have to write a test.  No having to wade through multiple layers of UI to test out some small chunk ok UI is a great productivity gain for me.

Next is design patterns.  This is what gives you a reference for how to approach your code.  That said, this isn’t about making everything absolutely perfect from the get go, but it is nice to know where you are going to made your comprises early on.

But all of that does not explain where I begin.  That is where Domain Driven Design (DDD) kicks in.  For those not familiar with the concept, you can read up on wikipedia, buy The Book, or buy one of the various other references.   One of the concepts in DDD (I’m still reading the book) is setting up something called a ubiquitous language.

The ubiquitous language is actually trying to solve a problem that I have seen happen on many projects I’ve been apart of (but not always my fault).  At some point there is a linguistic difference between the nouns that the customer uses and the nouns that the programmers use.  By focusing on the language first, you are attempting to head that off at the pass.

These nouns consist of your domain classes and your tables and columns, they move everywhere…but not always consistently.  Consistency does matter.  Inconsistency is what leads to rather confusing conversations with people and everyone scratching their heads about “what just happened”.  So, this is the middle that I start with.

But before you start…

One of the other guys in the group was an actual data guy.  The systems he has written worked with more data than yours does.  Trust me on that.  Historically, his biggest consideration was data input speed.  I don’t think I would start in the middle if that was my biggest concern.  In that case you do start with the database, you tune for speed.  You also don’t use as many domain classes, and you tend to throw away your ORM solution and just hit the database layer directly via Ado.Net.

But lets face it, that doesn’t happen very often.  Most business applications aren’t going to touch what the architecture can take.  It is amazing how many horribly written applications with very inefficient code run just fine.  Most of my speed issues could be solved by indexing tables and changing generic lists to generic dictionaries (more on that later).  Architect your applications for how they are going to be used.  Most of my web applications have a max usage of 100 simultaneous users.  If the data access is slightly slower I’ll take that hit for programmer efficiency.  If you are designing Amazon.com, you code for through-put.

OK, someone is going to disagree with this…I can already feel it.  Please take a moment to register your displeasure in the comments.  I would love to hear it.