Tag Archives: programming

Identifying what is wrong with code

There are a number of head-nodding moments in Clean Code The book mentions many coding guidelines and good-code principles that aim to simplify code that is written.  Software development is definitely a career where you must continuously learn.  Even so, I’m somewhat disappointed to be this far along in my career before learning the names of certain concepts that until now I have only known as “common sense”. 

There have been times when I have identified “bad code”, but pressed to state what was so bad about it left me speechless…  This does not make the task of improving the code impossible, but can leave you with an inability to justify and/or quantify the changes you make. 

Here are some of the more common rules:

One level of abstraction per function.

This rule is not given a “trendy term”. Unlike the other rules I’ll introduce it is dealing with functions, rather than classes.  But it is still important.  This rule possibly came from “days of old” when top-down procedural programming was all the rage.  It’s still important and sans lengthy example is best summarised as:  Do not mix details with abstract concepts in the one function.  If you stick to the idea that each function should only do one thing, then you will be going a long way towards avoiding mixing abstract concepts and technical detail.

Single Responsibility Principle

The Single Responsibility Principle (SRP) states: There should never be more than one reason for a class to change.  The object mentors web-site has a series of PDFs discussing various aspects of Clean code, and has this (in part) to say of SRP:

“If a class has more than one responsibility, then the responsibilities become coupled.  Changes to one responsibility may impair or inhibit the class’ ability to meet the others.  This kind of coupling leads to fragile designs that break in unexpected ways when changed.”

In a rather circular fashion, the definition of a responsibility in SRP is “a reason for change”.  In other words, a class written to obey the SRP only has one responsibility.  If we were to develop an Object-Oriented “Space Invaders” game, we may end up with a class for the aliens, that looked like:

 public class Alien
{   
    public void Move()
    {
       
    }
    public void Render()
    {
       
    }
}
 

However, this is a violation of SRP.  We now have two reasons for changing this class.  If the AI model changed, the calculation of the Move method may require changes – likewise if there were changes to the Graphics subsystem, the Render method would alter.

  

Law of Demeter

This is also known as the Principle of Least Knowledge.

“The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).”

Object Oriented notation assists here, by having different scopes for the methods and member variables defined in a class. Clean Code points out that often you will see private member variables (good so far) exposed through public getters and setters methods (not so good).  This exposes the implementation details of a class allowing for other classes to violate the Law of Demeter.  Better (so the book argues) to expose the data through abstract concepts

“A class does not simple push its variables out through getters and setters.  Rather it exposes abstract interfaces that allow its users to manipulate the essence of the data, without having to know its implementation.”

The example given talks about a vehicle class that exposes the “percentage of fuel remaining” as opposed to “fuel tank capacity” and “gallons remaining”. 

 

This is by no means a definitive list of ideas presented in the book.  From my experience, violations of these principles represent the vast majority of “ugly code” that I have seen.  Once these coding techniques have been highlighted, it is possible to see where improvements can be made in existing code.  By refactoring code to utilise these principles, you can identify that tangible improvements have been made.

Comments revisited

About a year ago I wrote an article on comments.  That article left me feeling uncomfortable.  In it I made a point that people may think that their code is too simple to need comments.  Indeed, it is not beyond the realms of possibility that this is in fact the case.

I’ve been reading a book called “Clean Code – A Handbook of Agile Software Craftsmanship” by Robert C “Uncle Bob” Martin.  He devotes a whole chapter to comments – which is highly commendable.  His thoughts on comments can roughly be surmised by the following extract:

The proper use of comments is to compensate for our failure to express our-self in code. … We must have them because we cannot always figure out how to express ourselves without them. …  Every time you express yourself in code, you should pat yourself on the back. Every time you write a comment, you should grimace and feel the failure of your ability of expression.

Despite my earlier post, I have reached the conclusion that I agree with him!  Indeed, the argument “My code is too simple to need comments” should describe the code you are aiming to write.  Being objective in your analysis of your code is the hard part.  Martin’s main objection to comments is what I was alluding to in my earlier post:  they tend to “rot” by becoming less reflective of reality over time if not maintained along with the rest of the code base.

A lot of the early chapters of Clean Code revolve around the “common-sense” aspects of coding. 

  • Variables should be descriptively named (as should functions and classes)

  • Functions should do one thing and one thing only.

  • Functions should be short. (In fact, as Uncle Bob puts it: “Make a function short, then make it shorter”)

The second strategy I recommended for writing comments was to “pretend you were explaining the block of [complex] code to someone else”.  As Martin states, this is a failing of the code.  You would be better off refactoring the code so that it wasn’t so complex.  If you apply the “common-sense” aspects of coding, you will probably find that your complex code violates at least one of the rules.

I was pleased to see that Martin suggested that comments were okay when written to convey the intent of the author.   This is still my number one use for comments. 

It’s been an interesting read so far and I am sure there will be other topics that I wish to reflect on in blog form.  Expect to see more in the coming weeks!