Why are you not using Design by Contract?

by

When learning to program I distinctly remember coming across the concept of placing asserts within your code. Assert statements are primarily used for “things that cannot happen“, but in my early days I was too focused on the stuff that was supposed to happen!

Defensive programming” was also introduced. Principles such as “Never trust the user” and “80% of your code will be validation and verification” were highlighted. Despite these introductions many years ago, the concept of asserts never stuck with me. Yet I program defensively like there is no tomorrow.

The use of asserts can be extended into “Design by Contract” or DBC. In DBC the developer makes use of pre-conditions, post-conditions and invariants. Some languages such as Effiel have taken DBC as a core feature while other languages leave DBC up to libraries.

One of my favourite programming books is the Pragmatic Programmer. Having stood up to many re-reads I always found myself intrigued by the idea of DBC. Yet I never found myself following this interest through, at least in a production environment.

Our team recently came across a bug in which part of the system was using a component in a way which was deemed invalid. We had a suite of tests to accompany this feature, but these tests were unable to highlight the problem. When the object was sent across the wire, the Javascript front end was firing a null reference across, this was out of our control in the back end of the application. As the feature crossed a boundary and spoke to another system defensive programming would have been difficult. All we could do was error and inform the developer what was wrong. Even without defensive programming, the system was currently doing this anyway. We had little to gain.

Here I decided to experiment for the first time in my programming career with code contracts. A contract was applied that said the collection sent into the system must not be null or empty. If so, the second system would blow up informing the developer what was wrong. This contract was a very primitive example of a pre-condition – something that must be true in order for the rest of the following code to execute.

The benefit here came from just a few mere lines of code. Had we tried to program defensively the second systems’ code base would have suffered for little gain. We would need to report the error, add error codes, introduce exception handling and so on, all for a simple defect that could be fixed immediately and potentially never occur again once the developer integrating has configured the components correctly.

One important factor to consider with DBC is the contract violations should never be caught or handled. Every single contract that is violated is a bug. To stop the violation you need to fix the code that is breaking the contract. Likewise contracts make little sense when dealing with a public API. On the edge of the system you should presume your users will make mistakes and “do the wrong thing“, here you must use defensive programming.

Since this day I’ve liberally applied code contracts whenever we cross system boundaries or interact with the infrastructural aspects of our code, e.g. database helpers. This has increased my confidence that the system as a whole has been correctly “glued together”. Another benefit is several bugs have been thwarted thanks to the contracts as unlike unit tests, contracts are always present when enabled, meaning missed boundary conditions can easily be detected.

Hand in hand with our automated test suite, code contracts make a great companion. Never alone will one suffice, but when used in conjunction they can be extremely powerful. So the question is, why aren’t you using them?

3 years at Codeweavers

by

Having wrote about the top ten things I discovered in my first year at Codeweavers, I figured it would be time for a follow up after the past two years. In no particular order, a collection of the biggest lessons I have experienced.

  • Design by Contract
  • Test Driven Development (TDD) is a tool
  • Design is Important
  • Don’t tie yourself to a Framework
  • The Importance of Tools
  • Acceptance Testing need not use the Full Stack
  • Program for Change (Open/Closed Principle)
  • Reinvent the Wheel, Often
  • Do it right – violate YAGNI
  • Practice, Practice, Practice

I’ll expand on these topics over time in future posts.

The Anti If Campaign

by

Firstly if you are unaware of what the Anti If Campaign is, I advise you to take look before coming back. My first impression a few years ago was the site must have been some sort of spoof. Programming without “if” statements, this was crazy nonsense. After all the “if” statement is one of the core constructs of any language. If you look deeper however the campaign is not advocating the abolition of “if” statements, it is simply encouraging cleaner code by removing the likes of type checking and control coupling. This can be achieved by the use of Polymorphism and abiding by the Single Responsibility Principle (SRP).

The Anti If Campaign is relevant as I have recently had first hand experience of what the supporters are campaigning against. I was working on one of our greenfield projects where I had violated SRP for an easy win. We had a class which would look up a quote based on some input criteria. I allowed this input to control how the lookup was performed. In some scenarios the input would be in a different form, meaning the lookup would need to be carried out in a different manner. An “if” check was introduced to handle this logic. In pseudo code:

public Result Lookup(Request request)
{
    if (request.Id != null)
    {
        // look up an existing quote
        // code specific to an existing quote...
    }
    else
    {
        // look up a new quote
        // code specific to a new quote...
    }
}

The code in question had supporting methods for both paths.

Fast forward a few months and something terrible had happened. Like a plague, this simple conditional I had introduced was spreading. Code that was executed much later on was beginning to perform the same conditional check! At the same time I discovered this problem, I was asked to perform a trivial change as the requirements had evolved. What should have been a five minute job, turned into a few hours of paying back technical debt.

The fix was well overdue at this point. I had to push the conditional statements as high as I could. The closer they were to the edge of the system the better. The by product of this refactor is that the code is a lot clearer now. Each class and method did just one thing, and they did it well. It turned out I was actually able to push the conditional statement so far up that it effectively disappeared into the routing of the system. It was up to the caller to “do the right thing“.

After the refactor:

public Result LookupExisting(Request request)
{
    // lookup an existing quote
    // More code for an existing quote...
}
public Result LookupNew(Request requst)
{
    // Look up a new quote
    // More code for a new quote
}

As each part of the code complies with SRP, I know exactly where to go if there is a problem. For example, if we have any problems with the retrieval of new quotes, I can easily debug and fix the issue. Likewise if we wish to extend the lookup of existing quotes, I can confidently change the code without the fear of breaking the retrieval of new quotes. The other side effect is that I can easily reason about and test the code in question.

Object Calisthenics

by

Recently I ran a session on Object Calisthenics. I was first exposed to this challenge a few years ago and personally found it a fun, yet difficult experience. This is intentional as the challenge is designed to push the boundaries of best practices. The instructions are simple, there are nine rules to follow that must be obeyed during a traditional kata. We chose the Checkout Kata as the backdrop for this session. The teams feedback is as follows.

Use only one level of indentation per method

The team found this easy, and we discussed that following this to some degree in day to day development would be beneficial. Limiting the amount of nested code you have can improve readability quite substantially.

Don’t use the else keyword

At first this seemed a no brainier, until people realised it meant to favour polymorphism and not simply relying on an early return (implicit else).

Wrap all primitives and strings

The team managed well with this, one example would be a pair introduced an SKU (Stock Keeping Unit) to encapsulate a string and price. We do this well in day to day development at Codeweavers for domain objects, however we tend to fail in other areas such as data access code. This is one concept we need to try and improve at.

Use only one dot per line

The Law of Demeter in action. Once we cleared up the ideas behind this it was pretty easy for the teams to follow. This is not a dot counting exercise, so it is worth being familiar with the “law”. Much of our code would satisfy this requirement.

Don’t abbreviate

One controversial point that came up from this was regarding the team who chose SKU as a class name. Some of the team disagreed with this naming, though in terms of the domain (a supermarket) this is a perfectly valid name, therefore this did not break the rule. On the whole our code is named well, though our legacy codebases have many abbreviations that can confuse and obfuscate the intent of the code.

Keep all entities small

For new code, this is not an issue, however we find legacy code is given less treatment in regards to the size of our entities. This is something we should try to improve, though the teams found this easy enough during the kata.

Don’t use any classes with more than two instance variables

Personally I find this an odd requirement, providing you keep your classes small as per the previous requirement this tends to be a less relevant task. Of all the rules to follow, this is the one I could not advocate during day to day development providing you keep your classes small.

Use first-class collections

My personal favourite of the rules to abide by, and one I have since adopted into day to day coding. First class collections can simplify, and make code easier to understand as well as maintain and optimize. We have numerous examples of this at play at Codeweavers, and we should try to increase the amount of custom collections we have, as opposed to relying on primitive collections. For example, quotes is a better object than a array of quote.

Don’t use any getters/setters/properties

The hardest of all the rules to follow. Most of the teams tried to get past this rule by simply naming their getters/setters slightly differently. At the end of the day, there were still exposing state unnecessarily. We would never try to enforce such a rule for general development, but for core business logic this principle actually makes sense. The areas where this falls down, is on the boundary of the system, for example user input or output would be such scenarios where getters/setters are the easiest, cleanest solutions. Each team found this requirement the hardest to work with, which mimics my first expose to the object calisthenics challenge.

MVC is Broken

by

Broken coffee

If you look up the definition of MVC or Model View Controller, it will hail the definition as being able to change your front end without affecting other parts of the application and vice versa. This sounds great in theory, however this claim is nothing more than a blatant lie.

A failing of the architectural pattern comes from the whole codebase being tied to a specific stack. Take ASP.NET MVC. The domain logic will most likely be in C#. Therefore your models will be in C#. Your controllers will be in C#. Your views will be a mixture of C# and some form of a templating language.

If you want to change your stack to the “next big thing” you are forced to take a big bang approach. ASP.NET MVC won’t be around forever. Being tied to a specific technology feels wrong. Therefore this coupling means your designers are forced to use the templating language that your framework supports. This should be a flexible option that should be easy to change, after all the MVC pattern states this as one of it’s benefits.

Being tied to a specific technology leads onto our most recent project. One of our biggest and most important projects is a legacy Flash application. Back in the early 2000′s it was a cutting edge application – consistent across all browsers, ajax style requests, responsive design, you name it.

That being said we all know Flash is on its way out, and there lies the problem. It took myself about two weeks to add a few text boxes to the app in my first year at Codeweavers, all because the UI code is so difficult to work with. The logic is mixed within the UI. Had the app been developed in a MVC style we would be in a position to replace the legacy UI with a modern alternative.

We make use of SOA or Service Oriented Architecture at Codeweavers, therefore it seemed a natural fit to apply this to our rewrite of our legacy application. I proposed a theory:

“for an application to be truly independent of the frontend and backend the code must be developed in different languages.”

For example, I taught myself enough PHP to make a JSON request, perform some conditional logic and loop over a collection. With this I was able to recreate one of our applications that was powered by our backend C# services. I would not want to create an application in PHP, but using PHP as a templating language was a great fit. Afterall this is one of the intentions of the language. Limiting myself to just three simple PHP constructs I was forced to put all logic on the service in question.

This complete separation of concerns is made possible due to the fact it is simply not possible for code to leak between the layers due to the different languages used in the implementation. This means I could easily spin up numerous front end views while the backend remains unchanged. Likewise we could change the back end implementation from C# to another language. Providing the endpoints and request/responses match, the front end will still be functional. This full separation of concerns is what MVC style frameworks have failed to achieve.

In ten years from now it is hard to say what the web will look like. What I can guarantee is that the web will still be here. We’ll still be making HTTP requests. We’ll still be making back end services that powers much of the apps on the internet. One thing no one can really comment on is what the web will look like. One point we all could agree on is that HTML5 should be wide spread and no doubt “the next big thing” will be on the horizon. The great thing by taking the approach discussed previously is that Codeweavers will be in the position to change either the front end or back end of our codebase at any time. Precisely what the MVC pattern has failed to deliver.

Image by lynnepet (Creative Commons)