Monday, 12 October 2009

What does the M in MVC actually mean?

I was quite lucky when I first started my development career to be involved in a project where I spent a lot of time looking into presentation patterns. In retrospect this was very good experience which taught me a lot of the basics which I build on today.

There were two things in particular which I got out of it. Firstly I got to learn the patterns outside of any specific framework and secondly I had it drilled into me that the presentation part of the system is never the entire system.

The second point is quite important as often you can get into a mindset of “today I’m building an MVC application” when in reality you are putting an MVC presentation layer onto your application, even if that application is very simple. The importance of remembering this is relative to the complexity of the system but it’s a good way to think.

It’s great that Microsoft finally released an MVC framework for .Net but I can remember having a conversation (I think with Tim) in which we discussed if MVC just meant that all the poorly written code behind logic would become poorly written Controller code. Unfortunately this seems to be coming true.

The problem seems to me that a lot of people are confused about exactly what the Model in MVC means, or at least they are confused about what it’s practical implementation is. I’ve seen quite a few different definitions of what it is and what it isn’t and this makes things very confusing. It’s not that these definitions are wrong, it’s that they are often pushed as the definitive description of what the Model should be. In reality, at least in my opinion, the answer to the question is the same as the answer to most good questions in software development, it depends.

In a very simple application the Model is the rest of the system. It’s a simple object model that's probably persisted directly to the database and which the view is bound to without any abstraction. This is the kind of app Ruby on Rails is really good at (and ASP.Net MVC is not so good at, at least not out of the box anyway). This is also the kind of app that most of the demos, blogs, books and speakers seem to show when talking about MVC and if this is what you’re doing it’s pretty hard to go wrong.

Unfortunately most apps I’ve seen are more complex than this. Not massively complex but enough so that this approach shows it’s weaknesses. The same general rules apply in these systems, keep logic out of the View, keep the Controller very thin (very very thin actually) and keep business logic in your domain model.

In these apps you probably have a fair amount of logic that is just presentation logic. You keep this out of the View because that results in very messy code but if you put it in your Controller then it starts to become fat. You could push it into the Model but that means you are starting to mix presentation and business logic. It’s trying to resolve this kind of issue that tends to be the downfall of most of the apps using MVC I’ve seen.

In these situations the two lesson I talked about above become very useful. It’s good to step back from the ASP.Net MVC framework itself and just think in pure MVC terms. It’s also very important to remember that the MVC part is just the presentation stuff on top of the actual system. Solving these problems is always done by doing the right thing with your Model.

Like I said above the exact answer always depends on your situation but I generally find that your Model actually becomes a couple of models. Firstly your domain model sticks to containing business logic and remains the most important part of the system. But in addition to this adding a model specifically for the presentation layer is very useful. I think people often shy away from this because it feels like it adds more complexity but I find it often makes things much simpler.

A presentation specific model contains the information from the domain perfectly formatted for the View. This means all the logic that might have gone into the Controller to shape the data instead goes into the presentation model. Also any logic you might have been tempted to put in the View can be pulled into the Model. This also means you can use all of the cool features of MVC (model binders, using annotations for basic validation etc) without worryingly about polluting your domain model.

The only tricky part of this approach is mapping your domain model to your presentation model. There are plenty of different approaches to this and it really does depend on your context as to which one to use. Personally I stay away from using setters on my domain model so mapping for me is not about copying properties to properties but instead mapping incoming data to operations on an object.

This post is too long now so I should probably stop typing. The whole point of it was that the Model is the most important part. You should focus your efforts on getting this part of the system right for the context in which you are in and you should not restrict yourself to the specifics of the framework you are using when doing so.

Wednesday, 24 June 2009

Installing Cucumber on Windows

I had a great time on Tuesday giving an introduction talk on Cucumber, the Ruby BDD test runner at a London .Net User Group meeting. I promised I'd get a post up with some help on getting Cucumber set up and so here it is.

Setting up basic Ruby and Cucumber

Setting Cucumber up on the standard version of Ruby is fairly straight forward.

First head to the Ruby site and grab the latest one click installer from the download page. During the install make sure you check the "Enable Ruby Gems" option.

Once Ruby is installed on your machine we use the Gems package manager to install Cucumber. Firstly it's a good idea to check your gems are up to date so open up a command prompt and type "gem update --system", followed by "gem update". Once that completes we can install Cucumber by typing "gem install cucumber win32console". The win32console gem give us nice colours in our console output.

To check everything is good type "cucumber --version" and Cucumber should give you it's version information.

Installing Watir

With the standard version of Ruby Cucumber we can't interact with any .Net code directly. But it is still useful to us. Watir is one of the best uses of it I've found.

Put simply Watir automates browsers and has a nice Ruby API. If you put Cucumber on top of it you have yourself a very readable DSL for driving acceptance tests for a website

Watir can be installed by using gems again, this time using the command "gem install watir".

On Windows this will let you automate Internet Explorer and Firefox, though you will need to install an extension for Firefox. You can get more details on this from the Watir installation page

Cucumber and IronRuby

Ok so far so good. But now we get to IronRuby. Now this is an awesome project as it's bringing Ruby into the .Net world but it is still relatively new and under heavy development. As a result of this at the moment it's a little bit more involved to get going and Cucumber seems to work purely based on the current wind direction. Having said that the guys are doing a great job with it and the pace of improvement has been impressive so I expect things to get much more stable very soon

William Green (aka hotgazpacho) has a good post describing what you need to do to get Cucumber and IronRuby working together so I'll send you there for the details. But to summarise you want to be using the latest version of IronRuby which involves grabbing the source from GitHub, compiling the IronRuby code and then using the IronRuby version of Gem to get cucumber.

Good luck!

Monday, 1 June 2009

Why I love TDD/BDD

After watching Uncle Bob's presentation at RailsConf a couple of weeks ago I was reminded by one of the points he made of the reason I love TDD and more specifically BDD so much. Actually there are plenty of reasons I love it but one stands out above the rest as the main one.

Now this is something that plenty of people have already talked and blogged about before but I just wanted to get involved and say it myself.

TDD/BDD is great because it removes the fear from refactoring.

For me there is something that tends to be found in the best developers. Its not that they can always come up with the best design for every problem before they even touch the keyboard. Its not that they never write code that goes against the SOLID principles. It's not even that they have learnt every pattern in the book off by heart.

The best developers are those that continuously refine their code. They take something that is just a solution to the problem at hand and transform it into something which is clean and elegant. They craft a piece of code that is easily understandable by other developers and which can be easily maintained as the requirements of the system changes.

For me refactoring is the main technique I use when developing. I often describe my approach to it as 'aggressive refactoring', firstly because it sounds cools and secondly because it gets across how important I think it is. Refactoring lets me take my initial and often messy first stab at solving a problem and change it into something I can be proud of and which captures the insight I gain as I improve my understanding of the problem. If I just did what far too many of the developers I've met do and simply solved the problem the first way I could and then moved on, I'd leave behind me a trail of unmaintainable code.

To bring this post back to the subject of its title, what TDD and BDD give me is the safety net that tells me my code still does what I want it to do after I've refactored the hell out of it. This works just as well for code I wrote a minute ago as it does for code I wrote a year ago. In fact for any system that is going to last longer than five minutes the only way it can avoid becoming the unmaintainable mess that most legacy systems are is by being built in such a way as to support constant refactoring during its lifetime and that means having a good suite of tests or specs.

And so almost solely for that reason I love you TDD/BDD

Tuesday, 26 May 2009

The Information Expert Principle

During a conversation I had today I was reminded of one of the first principles of Object Orientated design I was ever taught that really clicked with me. It's something I use daily subconsciously but I never seem to talk about much. After all of the talk around SOLID recently I thought it was worth putting a post together on it.

One of the most important parts of OO design (at least in my opinion) is deciding which object a particular responsibility belongs to. Its fairly safe to say that with the right objects and more importantly with the right responsibilities assigned to those objects you're well on your way to having a design which is easy to understand, maintain and extend.

A lot of the time knowing where a responsibility sits is simple developer intuition and we do it without thinking. But it's worth being able to put some reasoning behind those decisions so that we can apply those same reasons in the cases that are not so obvious. It's also worth having these principles because sometimes it's easy to fall into common traps when building complex software.

One of my current projects involves taking a set of loan requirements and calculating the cost of various loans on offer. This is a good example of the kind of problem in which we can be guided by the Information Expert principle.

I've seen variations of this problem pretty much everywhere I've worked and one of the common solutions is to create a class to represent the calculation involved. In our case lets call it the LoansCalculator class. This class takes a set of Loans and a LoanRequirement and asks each Loan for the relevant information which is used to calculate the results.

Now this approach is not evil in itself but it's probably not the best solution to the problem. For a start it's not great that the LoansCalculator has to ask the Loan for information about it's state. Tell, Dont Ask is another one of the great OO principles I try and stick to.

What's more important about the calculator approach though is that experience tells us that this approach doesn't age well. For example probably the most common problem I've seen occur is that a new Loan type comes along which has a different calculation. The developer dealing with this problem adds a LoanType enumeration to the Loan and a switch statement in the LoansCalculator and everything works just fine. Then the next new Loan type comes along and the next developer adds a value to the enumeration and extends the switch statement. Then yet another new Loan type comes along and before you know it we're in a mess.

If we we're to stop and think for a minute and consider the Information Expert principle we would probably come up with a different solution. Since the Loan has the information required to perform the calculation then it is the expert and so it makes sense to give it the responsibility of calculating the cost.

This is great firstly because now we don't have to expose the state of the Loan to anyone else. We tell the Loan to calculate it's cost based on the LoanRequirements and don't need to ask any of its details.

Secondly when a new Loan type comes along we can use the power of our OO language to solve the problem by applying polymorphism. We create derived class of Loan which encapsulates the new Loan type and calculation and the consuming code carries on as usual.

Personally I also find that this type of design is much easier to understand and thus maintain and it lets me use my OO know how to extend the system when required.

Of course as with all principles the Information Expert is not an absolute rule and does not apply in all situations. I find that using the Information Expert and Single Responsibility principles in conjunction with each other generally works well.

Craig Larman had a great example of this which I'm paraphrase here, mainly because I can't remember his exact example. We could say that the Loan class knows most about a specific instance of a loans details and so it is arguably an Information Expert when it comes to persisting a Loan. However if we consider SRP it probably makes more sense to have another class (or indeed a framework) deal with the persistence while our Loan class concentrates on encapsulating a loan.

So there you go. Information Expert seems like it's just stating the obvious thing that we all know as devs. But it is worth stepping back every now and again and justifying why we make these design decisions just to make sure that we really are doing the right thing.

Wednesday, 25 March 2009

Moving towards a leaner software development process

Lately I've been spending a lot of time thinking about software development processes and how to move from doing a SCRUM style agile to a much leaner style of development. I'm very interested in this area because I believe we can deliver more value to the business by being able to release frequently and use the feedback that follows from that to steer us more accurately.

I was recently at QCON and caught an excellent talk by Kris Lander and Gus Power from Energized Work titled Turning on a sixpence - No excuses: Concept To Cash Every Week which really helped to solidify some of the ideas I've been having.

I have been meaning to put together a post on this for a while but I seem to always be too busy at the moment. So in the meantime I figured I'd get something up here by posting up the bullet points I jotted down on the tube a couple of weeks ago which were meant to be the start of an actual post. I then plan to expand on some of the points over the next few posts.

These points are the ideas and aims my ideal team would be following. I should also mention more than a few of them are pretty much stolen from the Energized Work talk as those guys summed them up so well.

So without any more delay here we go.
  • Focus on throughput
  • Deliver frequently at a predictable pace
  • Your wall should have sections for backlog, in progress, inventory and done
  • Done is live and making us money
  • Inventory is developed and tested with the money spent but not yet
    earning us anything
  • Focus on small deliverable stories or chunks of work
  • Slice features up from the minimum deliverable amount to the full feature
  • Don't be afraid to put a partially complete feature (i.e. a feature that works but doesn't do everything initially specified) live as long as the business is happy
  • Use the feedback from live features to decide whether to continue to develop them or move onto new features
  • Use the inventory section as an indicator of how much we have completed but not yet live
  • The inventory is the indicator of when to go live, not the iteration
  • We always go live at least once an iteration, but we don't limit ourselves if our inventory indicates otherwise
  • Keep our iterations short, ideally weekly
  • Plan on demand. At the beginning of the iteration and then in short sessions during the iteration doing just enough to ensure we don't run out of work
  • Don't have too much in any one section of our wall to ensure our stream is manageable
  • Focus on going live from day one, bake quality in from the start. Don't separate testing from developing
  • Estimate technical debt even if it is not being fixed immediately. Make it visible to everyone

Monday, 16 February 2009

Testing isn't about tools

Hemal has just blogged about Developers talking about testing and he makes some very good points on how the focus can get lost when people concentrate too much on tools.

We are currently focusing very strongly on 'baking in quality' to our process. This involves moving away from having a designated part of our iteration where the developers pass the system over to QA and instead to try and have each member of the team take responsibility for the quality of the system throughout the development process.

We are already very good at unit testing our code and so we began to look at other tools to automate the verification of the quality of what we were producing. As part of this process we looked and Fitnesse and Selenium, both very good tools when applied to the right problems.

One of the specific problems Hemal discusses is how Fitnesse and Selenium became the focus of testing. I specifically had an issue with the usage of Selenium, which while being a great tool for front end testing, is not the solution to all or even most testing problems. More specifically I felt that we had lost sight of exaclty how much value we could get out of plain old integration testing using NUnit.

While you can argue that Selenium tests all the way from the front to back end in the same way the end user will, in reality there are a number of issues with them. Test suites can quickly become expensive to maintain, running the tests is not as fast as other methods and there are certain situations which we just cannot test properly using this kind of tool.

Contrasting this with just writing some integration tests in C# using NUnit we have a much more powerful and flexible language which produces tests which are more maintainable and more likely to be understood by future developers.

My point isn't that NUnit is a better testing tool than Selenium, but as Hemal points out that we have to be careful to keep our eye on what we are testing and choose the appropiate method at that time.

Monday, 2 February 2009

Its not what you are but what you can do that counts

When I was first taught about inheritance I was shown an example similar to the following.

We can categorise Cows and Horses as both being types of Animals. We can represent this by having a base class Animal and two derived classes Cow and Horse.

image

Now we can create an abstract method on Animal called MakeNoise() and then the derived classes implement their own versions to make the appropriate noise.

public abstract class Animal
{
public abstract void MakeNoise();
}

public class Cow : Animal
{
public override void MakeNoise()
{
Console.WriteLine("Moo");
}
}

public class Horse : Animal
{
public override void MakeNoise()
{
Console.WriteLine("Neigh");
}
}

This example is ok for showing some of the mechanics of inheritance but it can be misleading in terms of how we use inheritance for modelling.

I was lucky in that in my first real job after university I worked with people who really knew what they were doing and were eager to share that knowledge.



One of the first things I was taught was to think about objects more in terms of what they do than what they are. So if we take the example of the Horse from above rather than consider it as an Animal, we may instead model the fact that it can pull a cart as that is something we are more interested in.



We may also consider a Tractor object which can also pull a cart but is definitely not an Animal. So rather than try to model the Horse and the Tractor using inheritance we would probably instead create an interface ICanPullCart. Now if both objects implement the interface we don’t need a common base class which is great because it means our classes support more flexibility.



Now there are plenty of discussions on the web on inheritance vs interfaces and on favouring composition over inheritance and I don’t want to repeat too much of it here. I personally generally prefer composition as a way of creating useful objects but that doesn’t mean ruling out inheritance when it makes sense. A lot of these arguments centre around creating frameworks but I’m more interested in modelling a domain where I believe what something can do is more important than what it derives from.



So the reason I’m posting about this now is that I’m spending more and more of my time playing around with Ruby and I’m really interested in how these ideas apply in a dynamic language. Specifically I’m talking about Duck Typing which is nicely explained by the following phrase:




If it walks like a duck and quacks like a duck, I would call it a duck.




This can seem strange when you have been working in a statically typed language like C# for a while. In Ruby we don’t care that an object is an Animal, a Horse or a Tractor. All that matters is that the object can pull a cart. While in C# we mark the class with an interface in Ruby the fact that the object supports the method is enough.



This becomes even more interesting if you think in purer OO terms of objects sending message to other objects where we only care about what messages an object can understand.



While none of this may seem hugely ground breaking stuff I’ve found it interesting in the last couple of weeks. Shifting my focus from thinking about what something derives from to what roles it can play gave me a greater insight into modelling. In the same way shifting from thinking about interfaces, which are an implementation detail of statically types languages, to a purer OO model of objects and message has again helped me to think a little better about the systems I am building.