Tag Archive for ASP.Net

Yet Another SOLID Principles Piece

Introduction

Barely a day goes by without someone mentioning SOLID principles these days.

“Hello colleagues,” I say, “I am going to the coffee machine to get some coffee. Would you also like some coffee?”
“That depends,” reply my colleagues, “on whether the coffee will made according to SOLID principles.”
I consider this for a moment before replying. “Don’t be ridiculous. It’s a cup of coffee not a software engineering project.”

And there the matter ends.

Although

As far as acronyms go, SOLID is towards the SPLINK end of the convolution spectrum. In this article I’m going to go through each of the five principles in a way that will hopefully make them more memorable.

S is for Single Responsibility

This one’s pretty straightforward, or at least initially appears to be so. A class should have a single responsibility, or in layman’s terms, should have only one job to do. But wait! Slavishly following the principle as described would lead to lots of classes with single methods inside, which will make your code somewhat obscure. There’s a qualifier to the Single Responsibility Principle, and it is that a class should have only a single reason to change. This is perhaps a little harder to understand, so let’s have an example.

Squirrel

Imagine we have a class called Squirrel. This contains two methods:

  • CountNuts() – Returns the number of nuts the squirrel currently has.
  • ClimbTree(Nuts nuts) – Checks the number of nuts with a call to CountNuts() and only climbs the tree if it is over a given threshold. Climbing trees requires squirrel fuel.

This violates the Single Responsibility Principle because there are two reasons for the Squirrel class to change:

  • The way that nuts are counted might change, eg different nuts may be given different weightings
  • The nut threshold to climb a tree might change

To fix this, as a bare minimum the ClimbTree(Nuts nuts) method should be moved to its own class, and given an additional Squirrel parameter so that the Squirrel object can be passed into it: ClimbTree(Squirrel squirrel, Nuts nuts).

O is for Open / Closed

Which is it, open or closed? Are we talking about a programming principle or a CD drawer here? This is definitely one of the more obscurely named parts of the acronym. It may as well be called Owls.

Owls

Owls, being very wise birds, are open to the idea of being extended but closed to modification. Ask a barn owl to change into a tawny owl it will quite rightly tell you to sling your hoo-k. However ask it nicely to hoot like a tawny owl and it will happily oblige.

Let’s say we have an Owl class containing a single method: Hoot(OwlType owlType)

This method takes the type of owl (barn or tawny) and returns the appropriate hoot. Logic within the Hoot method constructs the hoot depending on which type of owl is supplied.

There is a problem with this. If we want our owl to be able to hoot like a snowy owl, we will have to modify the Owl class. This breaks the Open / Close principle because our class should be closed to modifications. Instead, it should be open to being extended. In this case we should do this by changing our Hoot method to accept an interface instead of an owl type: Hoot(IOwl owl).

The interface IOwl has a method called Hoot, and it is this which is called by the Hoot(IOwl owl) method. We then have concrete implementations of IOwl for barn and tawny owls, each of which have their own implementation of Hoot. With this structure in place, adding the ability to hoot like a snowy owl is simply a matter of creating a new TawnyOwl class which inherits IOwl.

L is for Liskov Substitution

Professor Barbara Liskov is one of the first women in the US to receive a doctorate in computer science. She has been doing this shit since the ’60s and has probably forgotten more than I will ever know. Take a look at her website. Gosh, it looks like the 1990s doesn’t it? Don’t laugh, she has more important things to do than worry about that grey background. Look closer. Look at her CV. It’s 32 pages long but 30 of those pages are publications and academic contributions to computer science. It’s fair to say that she’s pretty awesome.

That’s all great, but L for Liskov doesn’t tell us much about what Liskov Substitution actually is. In Prof. Liskov’s paper with c-author Jeannette Wing summarises it as:

Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.

It’s not exactly plain English but this is from an academic paper. Give your head a good scratch and you can make sense of it. In the world of C# Liskov Substitution can be described more plainly like this:

A class derived from a base class, interface or similar structure must be interchangeable with its base class or interface, etc.

Llamas

Let’s say you have some Llamas. Everyone knows that Llamas love Libraries. They are nature’s most avid readers, with a strong penchant for Literature. Unfortunately being quite Large creatures there are only so many llamas that can fit inside a library at once. We can call our collection of Llamas from the Library class and get it return its count to control the number of llamas per library.

But wait – some alpacas want to join the library. They are nature’s second most avid reader and in many other ways are similar to llamas. In fact the only way in which they differ that matters to us is that they’re about half the size of a llama. This means that more alpacas can fit into a single library.

It’s tempting to simply create a new Alpaca class with derived from the existing Llama class, and give it a Size property. This is set to 0.5. However doing so would break the Liskov Substitution Principle. Although our Library class can access the Alpaca’s Size, it cannot do the same for a Llama because the Llama class doesn’t have a Size property. The base class (Llama) cannot be substituted for its derived class (Alpaca).

One way to fix this is to add Size to the Llama class and override it in Alpaca. However this may not be the ideal solution, particularly if the Library one day decides to admit Sheep, nature’s third most avid readers. They could have all sorts of things which are different to Llamas. In that case it makes more sense to make a new base class or interface which includes the Size property, and derive Llama, Alpaca and Sheep from that.

I is for Interface Segregation

This one is more straightforward and at its heart is the idea that interfaces should contain the minimum required members. That way anything using that interface doesn’t need to concern itself with members it doesn’t use.

Insects

Let’s say with a class called Insect. This contains many members such as NumberOfWings and StingStrength. If we want to Sting() another object using our Insect class, we could just pass the whole Insect in as a parameter, like this: Sting(Insect insect). However, doing so exposes all the other members of the Insect class to the Sting method, when all we need to know about is StingStrength. We can reduce this exposure by creating an IStingable interface with a single member, StingStrength, and implementing it in the Insect class. We can then pass this into Sting like so: Sting(IStingable insect)

Similarly, if we have a Fly(Insect insect) method, we can create an IFlyable interface which contains the single member NumberOfWings, and use this like so: Fly(IFlyable insect)

Now we have two very tight interfaces for our Insect class which segregate its behaviour so that client code is only concerned with the parts it needs access to.

D is for Dependency Inversion

A common mistake is to construct high-level classes using concrete classes from further down the class hierarchy. What does this mean? Well, let’s look at everyone’s favourite seaborne scamp, the dolphin.

Dolphin

We have a higher-level class called Tricks which at the moment contains a single method, DoTrick(Dolphin dolphin). This will work, but becomes problematic if we want another animal to do a trick. As written, the high-level class is dependent on a low-level class. We need to redesign Tricks so that both it and the low-level class instead depend on an interface, ITrickable.

Now the DoTrick method is defined as DoTrick(ITrickable trick) and the Dolphin class inherits from ITrickable. Instead of the high-level class depending on a low-level class, both classes now depend on an interface. This is dependency inversion.

Summary

In conclusion then,

  • Squirrels
  • Owls
  • Llamas
  • Insects
  • Dolphins

I hope you’ve enjoyed this somewhat frivolous look at SOLID Principles. For a more in-depth look at the subject, I recommend these sites:

http://www.blackwasp.co.uk/SOLIDPrinciples.aspx
https://msdn.microsoft.com/en-us/magazine/dn683797.aspx

Enumerations, Bitwise Operators, Shiftiness

I like enumerations. They’re really useful for writing clear code and they’re also really easy to use. Like this:

public enum TvChannels
{
    BbcOne = 0,
    BbcTwo = 1,
    ItvOne = 2,
    ChannelFour = 3
}

Right?

Wrong. Enumerations can be decorated with the [Flags] attribute, which allows them to be combined. This allows them to be grouped together:

var BbcChannels = TvChannels.BbcOne | TvChannels.BbcTwo

The variable BbcChannels is defined as a bitwise OR between BbcOne and BbcTwo. The way we previously defined our enum values presents a problem however. The values must be multiples of two, otherwise the bitwise operations will yield incorrect results. The enumeration should instead be defined as follows:

public enum TvChannels
{
    None = 0
    BbcOne = 1,
    BbcTwo = 2,
    ItvOne = 4,
    ChannelFour = 8
}

There are two points to note here.

Firstly, the multiples of two allow the OR operations to work. In binary, the value of BbcOne is 0001, and that of BbcTwo is 0010. The result of an OR operation between the two (defining the variable BbcChannels) is then 0011.

This allows us to then check the BbcChannels for other enumeration values, eg

var IsBbcChannel = (BbcChannels & TvChannels.BbcOne) == TvChannels.BbcOne

This will be True, because the bitwise AND between BbcChannels (0011) and BbcOne (0001) is 0001 – ie equal to BbcOne.

The second point is that we have introduced a value of None = 0 at the start of the enumeration. This is because a value of zero cannot be tested for using a bitwise AND in the same way as in the example above; the result would always be zero.

Finally, a bitshift operator can be used to make the enumeration a bit nicer to look at. Because we’re assigning specific bits to each successive element in the enumeration, we can simply bit shift to the left by the appropriate number of times:

public enum TvChannels
{
    None = 0
    BbcOne = 1 << 0,
    BbcTwo = 1 << 1,
    ItvOne = 1 << 2,
    ChannelFour = 1 << 3
}

Lovely.

Here’s a photo of a rabbit with a cup on its head:

Test Driven Development – A Real world example

Test Driven Development (TDD to its friends) is a well-blogged topic. There are many examples of TDD around the blogosphere, crossing a multitude of technological frontiers. What follows is my own, slightly tongue-in-cheek overview of what TDD is.

Methodology

Death Star

This would never have happened with good test coverage.

TDD is essentially a process that states the acceptable criteria of something before building it. In code, this is typically the output of a method, but there are loosely analogous real world examples. It could be argued that examinations are tests that classify candidates as acceptable or unacceptable. A candidate with a perfect score is equivalent in this case to a method which satisfies all its unit tests. And anything with driven in its name is just begging for a car analogy. So instead of talking about either of those things, I’m going to build the Death Star.

The first thing we need to do is describe the Death Star. What should it look like? What should it do? What are its essential features? We describe it with a series of questions. Anything we subsequently build which can give satisfactory answers to those questions is to all intents and purposes the Death Star.

These questions are unit tests. They test a single scenario for a particular method. Methods can have more than one unit test depending on their complexity, but where possible it is best to break complex methods into smaller, more easily testable components.

Below are two basic requirements of the Death Star, along with the unit tests which would need writing before implementation.

That’s no moon

How big should the Death Star be? The only acceptable answer here is as big as a moon. Our test should be to measure the diameter of our object, in Imperial Moons.

Fully operational

The Death Star should be fully operational. We can test this by attempting to destroy Alderaan.

Implementation

When the unit tests are first written, they will fail because we have no implementation. The next step is to build the Death Star itself, in such a way that it satisfies each test.

One immediate problem that presents itself is the requirement for it to be fully operational. The test involves destroying Alderaan, something which we can only do once. To get around this, we require a mock Alderaan, which we can create in our unit test with the intention of using it to test the Death Star’s destructive function. This removes the test’s dependency on an external resource, and the same approach is taken when testing methods dependent on, say, database operations.

Stay on target

Although TDD can give developers confidence that the code they write will satisfy requirements and can be refactored with confidence, it does not guarantee that the final code is problem-free. It can only test what has been anticipated.

However if the input and output of each method is covered by tests, we can be confident that the system as a whole will work as designed. In out Death Star example, the reactor core would also have unit tests, as would all the components it interacts with. The situation where an unexpected input (such as a proton torpedo) causes an unexpected output, which is then input into the next component until a chain reaction destroys the whole system would never arise with good test coverage.

Conclusion

I hope this brief overview of TDD demonstrates that as a methodology it isn’t that difficult a concept. The actual implementation of unit tests themselves is a much wider topic however, with a rich selection of frameworks to choose from. As primarily a C# developer, I have no serious complaints about NUnit, which is more or less the de facto standard now, although Microsoft does ship Visual Studio with its own unit testing framework, which may work well enough for yourself.

Conditional method attributes

Sometimes I like to include some code which will only run when complied in Debug config. This is simple enough, just add some preprocessor commands like so:

#if DEBUG
  //Do some debug-only stuff here.
#endif

However this always looks a bit ugly to me. A much tidier way of achieving the same is to use conditional method attribute like so:

[Conditional("DEBUG")]
private void DoSomething()
{   
  //Do some debug-only stuff here.
}

The only catch with this is that the method must return void. This is necessary to allow it to be included/excluded depending on the compilation config used. It can be worked around by using reference parameters on the method itself.

Anyway, here’s a photo of a skiing penguin.

Skiing Penguin

RESTful WCF services without .svc file and with very little configuration

WCF is, on the whole, pretty neat. It’s a doddle to decorate methods with UriTemplates and specify DataMembers. Building the actual meat of a web service is made very easy by the wealth of functionality available in WCF4, and this is the bit I usually happily chip together whenever I need to write a RESTful web service.

Then I get to the part where I have to add the service’s endpoint to web.config. It’s usually been several months since I last did it. I look it up on google, but the results don’t quite seem to apply to me. I open up an old project where I last did this ridiculous dance, but evidently I’m missing something because the damned thing still won’t work. The problem is most likely a subtly mis-set attribute. Or may web.config is just a monster which will eat us all.

With that in mind, I was recently delighted to find this blog post by Steve Michelotti. It’s a little old, but the knowledge within was new to me, so it may be new to you too.

In a nutshell, it leverages the WebServiceHostFactory class to allow a ServiceRoute to your WCF service to be defined. The advantages of this are two-fold:

  • No service-specific entries are needed in web.config
  • The WCF service can be defined in a plain C# class rather than a .svc file.

Steve covers this in much more detail in his blog post, so what follows is a quick summary of the steps required to get a service up and running:

  • Define your service in a C# class (implementing an interface is recommended but not required).
  • Decorate your class with
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    This is required for the service to operate over HTTP.

  • A teensy bit of web.config tweaking is required. This is the other half of the configuration above.
    
      
    
  • Add a reference to System.ServiceModel.Activation. This is not to be confused with System.ServiceModel.Activision.
  • To add the ServiceRoute, add a line similar to the one below to Application_Start in Global.asax.cs:
    RouteTable.Routes.Add(new ServiceRoute("Services", new WebServiceHostFactory(), typeof(Your_Service_Class)));

    Where Your_Service_Class is the name of the class you previously wrote for your service. Leaving the first parameter of ServiceRoute blank results in all requests to the service being relative to the site route. Services in the example above is the route prefix of your service url. You can leave it blank, but I prefer to specify a path to keep my services tidily organised.  You should decorate your service methods with a suitable UriTemplate, eg

    [WebGet(UriTemplate = "MyService", ResponseFormat = WebMessageFormat.Json)]

    In the above case the service can be called via a browser on http://my_hostname/services/myservice

That’s it! I can now get on with the meaty business of writing code instead of wrestling with the beast that is web.config.

In the meantime, here are some goats in a tree.

Goats in a tree