Category Archives: OOP

Don’t Repeat Yourself

This week lets take a look at a(nother) useful principle, the Don’t Repeat Yourself (or DRY) principle. The goal here is to get an idea of how the principle works and then aim to incorporate it into your day to day development activities. Remember to try to combine it with the other principles we’ve looked at, for example the Single-Responsibility Principle from the SOLID principles.

So where’d this one come from?

Introduced by Andrew Hunt and David Thomas in their 2000 book “The Pragmatic Programmer” they define DRY as

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

What we are basically aiming for is don’t say (following Uncles Bobs tell a story advise) or do the same thing twice. If you have some logic that performs a useful job, or even if its not that useful, don’t repeat that code. Combined with Single-Responsibility you could wrap that it up behind a class or method and have a single definition (“authoritative representation”).

I read a quote once that is quite good, “The only bug free code is no code” another is “Code that doesn’t exist is code you don’t have to debug” (can’t remember the original authors). Essentially what both of these statements are telling us is, write as little code as you can to get the job done. By following DRY we can shrink our code base by reducing repetition and therefore reduce the chances of bugs or introducing bugs through changing the same piece of code found in multiples places.

Another benefit we get from DRY is if you have a block of code duplicated throughout your code base and you need to make a change to that block not only do you have to go and update all blocks but there’s a chance a bug can be introduced through this change (at the end of the day we’re only human). Now if that code block was held in one place, meaning only one update was required we save time and reduce the chance of introducing bugs.

One example is say we needed to modify a piece of data using the following steps:

const int TEMP = 10;
double x = 30;
double y = 5;

x = x * TEMP;
x + y;
x / 10;

Now instead of duplicating this “important” bit of code we can wrap it in a suitably Named class or method and simply call that.

That’s it really, if you find yourself writing the same piece of code more than once consider if it may be worth extracting all instances of that block.

SOLID Principles

I thought this week we’d check out the SOLID principles I touched on in previous posts (here and here). I’m thinking get a quick overview like we did with Design Patterns and may be we can then take another look at each principal again in more detail in the future.

So what exactly are the SOLID principles? They are really good guidance on how to design and develop highly maintainable, flexible, and easily understood software. Initially coined by Uncle Bob, if you read my previous post you know to check out one of his books, Clean Code, in a paper he wrote in 2000 called Design Principles and Design Patterns with the term SOLID coming later.

SOLID itself is made up of 5 principles, each a letter in the SOLID acronym, so lets get started…

Single Responsibility Principle

The first principle, and the ‘S’ in SOLID, is the Single Responsibility principle. This principle at its core means:

There should never be more than one reason for a class to change

In essence a class should only ever do one thing, it should have one responsibility. This allows us to know exactly what our class is doing and why.

One of the easiest ways to apply this principle is if the description of your class or method has the word ‘and’ in it you may well be doing more than one thing.

By following this principle we can reduce coupling between classes and improve the maintainability of our code.

Open-Closed Principle

Next up is ‘O’, that is the Open-Closed principle. The Open-Closed principle states:

Software Entities (Classes, Modules, Functions, etc) should be open for extension, but closed for modification’

So what does that mean? It means our goal is to ensure we can always extend the behaviour of an entity, lets say we have requirement changes or future developments but at the same time we do not modify the existing behaviour of an entity.

Personally I view this more from the perspective of the interface, we should always strive to maintain compatibility and, ideally, never introduce breaking changes by modifying existing entities but we can add modifications by extending it.

Liskov Substitution Principle

This one initially I found more confusing that the previous two but the more you use and understand these principles the better. Developed by Barbara Liskov in her keynote in 1987 called ‘Data Abstraction”, within the realm of SOLID it is defined as:

Functions that user pointers or references to base classes must be able to use objects of derived classes without knowing it”

This principal states that an object of a base class must be replaceable with an object that is of a child class (Polymorphism?).

As above I like to apply this by thinking interfaces, if I expect an interface within my code base, then any class than implements that interface and therefore fulfills the contract can be used.

Interface Segregation Principle

The ‘I’ in SOLID is for the Interface Segregation Principle, developed by Uncle Bob when he was consulting for Xerox. The principle is defined as:

Clients should not be forced to depend upon interfaces that they do not use.

Similar to the Single-Responsibility Principle mentioned above the goal here is to reduce the amount of “stuff” our code does and so reduce the complexities within the code base.

This one I like to think of as we should aim to define a lot of related interfaces instead of one massive ‘Jack of all Trades’ interface. The aim is to provide clients only with what they need instead of forcing them to use something “bloated”. The nice outcome of having multiple interfaces means a client can implement only those they require and are not forced to provide implementations for functionality they won’t or don’t need to use.

So our goal is to have a number of interfaces that can be used to make up the whole but can also be split and implemented on a smaller scale.

Dependency Inversion Principle

So the last principal, ‘D’; the Dependency Inversion Principal. Again developed by Uncle Bob, in a report he produce in 1996 called ‘The Dependency Inversion Principal’ (certainly worth a read). Interestingly this principal actually comes in two parts, defined as:

‘ A. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW
LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
B. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS
SHOULD DEPEND UPON ABSTRACTIONS.’

What this principal is trying to enforce is that changes at the low-level do not cause cascading effects to the high-level. Our high-level modules contain the business logic of our applications, now if these modules depend on our low-level modules changes to the low-level may have direct consequences for our high-level and vice versa. Our goal should be to decouple the high-level modules from the low-level (again vice versa).

Why? Mainly re-usability and less fragility, by decoupling our code we increase the portability of our classes or modules (don’t reinvent the wheel) and we make our code less prone to breaking when changes are made.

Conclusion

Well there we go, this has been a short introduction to the SOLID principals and hopefully has given you some information on what they are and how they may be used day to day. I may produce a post for each principal and provide examples in C#, if the interest is there.

One thing I have found is that the principals play well with each other and so as we try to apply them more and more each day to our development practices they quite easily become habit.

As usual feel free to get in touch either by the comments or the contact us page.

Names

My posts up to now have been some general introduction the Software Development and I wanted to continue that trend (and do so for a while longer). This time I thought we’d take a look at something I think is very important, Names.

As Software developers we name a lot of things; methods, functions, data members, properties, variables, arguments, packages, and of course classes. One thing I have aimed to do since reading ‘Clean Code’ by Robert Martin (also known as Uncle Bob), is to give EVERYTHING I name decent intention-revealing names. That is, I try to name things in such a way that anyone (including myself) who reads this code can have a clue what my intention was when I originally wrote it.

One of the main goals of intention-revealing names is it should result in an almost comment free code base, granted you will have some comments in there (and as I like to try to use the StyleCop style guide for Visual Studio I don’t fully adhere to this rule myself). Lets check out an example to see what I mean.

Lets say you’re reviewing code trying to find a bug (the code is what you wrote 6 months ago) and you come across this.

int T; // time

It is not unreasonable to think, what is time, time since when, why is this time important and why is it named T? In reality if it had just been given a more intention-revealing name there wouldn’t be the need for the reader to go hunting what it is and what it’s for. Instead it could be

int TimeSincePlayerLastMadeMove;

The above code gives far more information that ‘T’, (although if I’m honest I’d say we’d want to go one step further and apply the Single-Responsibility Principle and wrap this up in a class, but I’ll go over that in more details in another post).

We also want to avoid adding unnecessary information that just added to the confusion, so for example if we started off with

List<GamePiece> PieceList; // Players Game Pieces

We’ve included the collection type in the name but what if we change it from a list to something else, say an ICollection? Whilst the name infers its a collection of some sort any future user may well try to make use of it as if it were a list, as mentioned leading to confusion. Instead we could use

List<GamePiece> GamePieces;

An obvious issue Uncle Bob raised was that we should make meaningful distinctions within our code and not just code to make the compiler happy and we should avoid what he calls ‘noise’ words like, a, an, and the, that again may add confusion where there just isn’t any need to have it.

The book explains that we should strive to use pronounceable names, things that when we are in a meeting people know what it is we are talking about. Unfortunately I don’t have a personal example of this (though I would say acronyms are one of my biggest pet peeves in meetings), however he does have one he explains that he had come across ‘genymdhms’ which stood for ‘generation date, year, month, day, hour, minute, and second), not ideal really.

I won’t run through the entire section from the book there’s just a few more points I’d like to mention.

Class and method names, now class names should be a noun such as Customer or Account, they are names of things and so we should be using naming words. Method names should be a verb such as DeleteAccount, GetUserName, or SaveGame, they are things that do something so we should be using doing words. We’re very lucky today that if we name something and decide it’s not the right name we can quite easily refactor our code and have a name change ripple throughout the code base.

A key point that I think Uncle Bob raises that is spot on is the reason people use shorter less meaningful names is to ensure it shortens the code for that line or it means the required coding standard. Two of the coding standards I’ve come across in the past was MISRA and Google C++ Style, and they have a line length limit. I can’t recall the MISRA length I think it was between 80 and 95 lines but the Google Style limit was 80 with additional rules when 120 and 150 was broken (though in all honesty I think 150 is a bit much). The main reason for both of these limits was a throwback to when screen sizes were limited and if code was going to be printed. Now for the printed code issue I have not and I don’t know anyone who has had to print code out (at least in the past few years). For the former as our monitors are continuously progressing this just seems like a poor reason and I can’t see how it will continue as a rule. Though to be fair Google themselves state it is a throwback to the 1960s (link here).

So there we go, one of our many aims of writing code should be to make the things we name far less confusing than they need to be. Granted I am cherry picking things here and I do highly recommend any and every one interested in writing software pick up Uncle Bobs book and give it a read.

Four Pillars of Object Oriented Programming

Introduction

This week we’re going to look at the Four Pillars of Object Oriented Programming as a nice follow on from the last post, Procedural and Object Oriented Programming, the plan here is we’re going to expand on what was mentioned and get more information on what the Four Pillars actually are, in a simple and to the point way. So first off, lets name them:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

As a side note there is also the term Three Pillars of Object Oriented Programming, this version however does not include Abstraction. So I went for doing a post on the ‘Four Pillars’ as it would literally give the best of both worlds.

Abstraction

The first Pillar we are going to look at is ‘Abstraction’, also called ‘Data Abstraction’, this is the means by which we only show (externally to our class) what is absolutely necessary and we hide all other aspects of the class. This is where the access modifiers I mentioned in Procedural and Object Oriented Programming come in, that is public and private (there is also protected and for C# internal but we’ll just concentrate on public and private). So, in a class those parts (data members and methods) we want other entities to see we make them public and the parts we want to keep hidden we make private.

A good example of this would be the consider a car. When we want a car to turn left we use the steering wheel. How exactly the wheels move in the correct direction we don’t really need to know, just how we move the steering wheel (our public method) ensures all the actions ‘under the hood’ (our private methods) makes the wheels turn in our desired direction.

So Abstraction, also called Data Abstraction, is the process of hiding data and information.

Encapsulation

Encapsulation is the process of containing or ‘encapsulating’ our state and behaviour, that is our data members and methods within a self contained entity, for example a class (check out my Procedural and Object Oriented Programming post for a bit more info). When applying our Access Modifiers (see Abstraction above) we can limit who has access to that state and behaviour. Encapsulation is a very useful mechanism as it allows us to place all the related ‘stuff’ of a class (data members and methods) within one nicely contained and well named package, i.e. class (I’ve made a point of well named because after reading a book by Robert Martin called ‘Clean Code’ it is a must, I recommend you read this but I’ll be giving you some details in the future).

And that’s it encapsulation is that simple, wrapping up state and behaviour within a single class.

Inheritance

Similar to how we consider the term in the real world when applied to parentage. It is the process in which we allow our classes to get data members and methods, state and behaviour, from other classes. Why would we want this? Why not write each class individually? Well the biggest answer is code reuse, the more code we write the more bugs we bring into a system and the more code we have to maintain. If we can write a class then allow other classes to take that functionality and use the content without having to write it that is very helpful. It’s similar to how a child gets some characteristics from their parents. We call the class providing the members and methods the parent or base class and the class inheriting the members and methods the child or sub class.

Different languages have different versions of inheritance, so C++ allows a child class to have multiple parent classes, there are pros and cons to this, one of the most well know cons is the diamond problem (to avoid getting side tracked I’ll do a post on this in the future). Another form of inheritance is single parent inheritance (from classes), in this case we can only ever have one parent class and of course this can go up the chain, so our parent class can have one parent class and so on, this is the case in C#. In C# however we concentrate more on the use of interfaces, which is where we define a contract and leave it up the the inheriting classes to provide the implementation (again this will definitely be a future post, very important).

So the easiest way to know if you need inheritance is think can I apply the ‘is-a’ relationship, i.e. a car is a vehicle, so in this circumstance we may have a vehicle class and a car class where we may, and probably should, have our car inherit the characteristics of vehicle.

Polymorphism

The final pillar we’re going to look at is Polymorphism, ‘poly’ means ‘many’ and ‘morph’ means ‘forms’ so ‘Polymorphism’ means ‘many forms’. It allows use to define, say, a method in our base class and allow our child classes to provide their own implementation of that method. A good example is if we have an Animal base class with a method called ‘MakeSound’, now the result of ‘MakeSound’ would be different for pretty much every animal we created, for example a Dog would bark, a Cat would meow, a Lion would roar, and a (male) Grasshopper makes their noise by rubbing a hind leg on their wings.

It essentially allows for a contract to be agreed, so in terms of our animal example every animal that inherits from the Animal class are essentially saying I will provide you with my own ‘MakeSound’ implementation.

This one tends to be a bit trickier than the other pillars but it is quite that simple, if there is any interest in some more information please free feel to ask.

 

And there we go a quick view on the Four Pillars of  Object Oriented Programming. Hopefully that has given you some insight however if you have any questions please feel free to ask.