Andy Crouch - Code, Technology & Obfuscation ...

Readable Code Part 2 - Comments

Photo: Unsplash

This post continues my series on code readability. In this post, I want to cover something that exists in all languages, comments.

All languages support single and multi-line comments. Lines marked with your languages comment characters are not executed by your compiler. Instead, they are used to provide a simple documentation mechanism within your code. While it would seem logical to use extensive comments in your code, it is almost always not the case. But, as I will cover further in the post, using comments for generating documentation can be a useful tool.

Standard code comments make reading code difficult. They extend the code height and add additional noise that makes reading the code much harder. Like prose, when you read code you want to follow the flow of the code like you would follow the text in paragraphs. With comments scattered throughout your code, you are they forced to context switch. It breaks your thinking and understanding through interruption.

Code that is extensively commented is usually always done so to support badly written code. This is what is commonly known as a code smell. The comments can usually be removed by following better naming conventions. Better structure and breaking your code up to be more readable will also reduce their need. This is something I plan to cover in the next post.

Let’s cover some examples of bad comments. First the obvious one. Never, ever repeat in the comment when it is obvious what the code is doing, such as:

// Initialise number to 99

int number = 99;

// Set isSomething to true

var isSomething = true

These comments add no value. The code’s intention is clear. Don’t do this. Also, don’t use comments to provide a running commentary on code such as

public string DoSomethingWith(Model data)
    // Get property value from data ....

    var propertyValue =;
    // ... apply transformation to property ...

    // ... return transformed property

    return propertyValue;

Again, this adds no value but does add the noise and height I mentioned earlier. I have seen code that has this throughout the whole project and it makes reading the code really hard. Not only is it hard to read but, and we come to the main issue with excessive comments, they are likely to be out of date.

When developers write code and add extensive comments they do so selfishly. It is for their own good. They think they are doing it to be good programmers and to aid whoever comes next to work on the code. But, if that was the case then they would have written well structured and logically named code. They would not need to fall back on comments. When someone new comes to the code they may not expect or have time to maintain the comments and the code. The priority is the code and once one comment becomes out of date then the Broken Window principle kicks in. The third developer will come along and see that a comment has not been updated. They will not bother to maintain the comments around the code they have modified. As time goes on the code changes. But the comments are left to rot until someone does the decent thing and deletes them. This is the only thing left to do as a wrong comment is of no value at all.

Before I move on, there is an excellent collection of funny and inappropriate comments on Stack Overflow. None of these should be seen in any production code base no matter how amusing they are.

So when should you add comments? Easy, when it explains a non-logical snippet of code. This usually relates to business logic and the meaning is not easy to convey in code. An example could be similar to:

public DateTime GetExpiryDateTimeFrom(Model model)
    var expiry = model.ExpiryDate;
        case HHType:
        case NHHType:
            // Power Market Prices Expire At 4pm

            return new DateTime(expiry.Year, expiry.Month, expiry.Day, 16, 0, 0);
        case GasType
            // Gas Market Prices Expire At 6pm

            return new DateTime(expiry.Year, expiry.Month, expiry.Day, 18, 0, 0);

The other main use for comments these days is for generating documentation. Python has PEP 257 and C# has XML documentation comments. Most modern languages have some form of these comments. They provide a mechanism to add comment blocks to your methods and functions. The languages then have tools or applications that use the comment blocks to create documentation. In C#’s case, the comments are extracted to an XML file on a build. There are a number of tools such as Sandcastle that can be used to build your documentation from the XML file. In fact, Visual Studio (and Code) will use the XML comments to provide Intellisense for your own code as do other editors. This can simplify the sharing of knowledge in a codebase for a team in a manner the developers already use.

So code comments can have a use when used sparingly. They should not be used to explain poorly written code, provide running commentary or berate other developers. Used wisely, like most tools, they can add value and even be used to extend your editors functionality. The main thing to remember as a good developer, if a comment is required and already exists then maintain it as if it was code. If it adds no value, remove it.

If you have any opinions around code comments or the points made here then please contact me via twitter or email.

The Importance Of Readable Code

Photo: John Schnobrich - Unsplash

Something I am passionate about is readable code. I mean really passionate, opinionated if you will, about it. This does not mean following some code formatting recommendations. Nor linter’s or tools such as Resharper. (Although I would say use these tools from the outset of your project to support your efforts). I am talking about how you structure your code and what names you apply. I am also talking about consistency and I am definitely talking about removing obscurity.

Why am I so passionate?

Because you will read significantly more code in your career than you will write.

It’s a skill that often comes with experience, both career and technological. Most junior developers aren’t told to learn to read code. They work hard to learn the principles of programming and a given language. They are encouraged to play with the code and what they have learnt. Simple examples such as a Hello World application or a Todo list are shown. Most developers learn online these days and will copy, paste and run the code. Very few times in tutorials or courses do they say “Go to GitHub and read the code in repo x,y and z”. Most example code is exactly that, an example. It’s not the real world. As I shared on Twitter the other day, I am old enough to remember learning to code form books. I could not copy and paste the examples and just run them. I had to type them out. I would read endless examples to develop the answer to my problem.

When we learn English (or whatever your language is) you are taught to read and write. By doing so you enforce both actions and the impact one has on the other. It enforces what has been learnt and exposes us to more advanced syntax and different styles. This is the same for code. If you are learning a language, reading other developer’s code will benefit how you write code. You might read some bad code but you will also identify good code in your languages ecosystem. Just like reading books help to broaden and enhance your knowledge so will reading code.

The harder part of reading code is that it is not as structured as most spoken languages. This is ironic as most languages have very few keywords in their syntax. So they should be easy to read. The difference with programming languages is that they have limited rules around the syntax. This leads to infinite ways in which to use them.

This week I worked on fixing a page in our application that provides a forecast calculator. The page was an external, anonymous, page. Pure Html with posts to a server controller. It took about 4 hours reading through this small code base to work out what was going on. That was the time it took to unravel the code to understand what the problems where and how the feature worked. The reason was the way it was written made reading it extremely hard. Poor composition, inconsistent naming conventions and out of date comments all pilled up.

Take the following snippet of JavaScript

function isValidDate(s, prevYears, futureYears) {
    var d = getDateFromString(s);
    var bits = s.split('/');
    var validDate = d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]);
    // rest of function


Compared with the following with a few minor changes

function isAValidDate(dateString, previousYears, futureYears) {
    var dateToValidate = createDateFrom(dateString);

    var dateElements = dateString.split('/');
    var isValidDate = dateToValidate && (dateToValidate.getMonth() + 1) == bits[1] && dateToValidate.getDate() == Number(bits[0]);

    // rest of function


What do you find easier to read? I accept that there are more characters but I will ignore comments on that. Today’s editors all come with Syntax highlighting, templating and autocomplete. That is no longer a real reason for variables names d.

So over the next couple of posts, I am going share how I write code to be readable for myself and others. Most of the tips are already available on the internet but I have a few ideas I find quite powerful. I will also address the cost to a project when you allow unreadable code to persist.

If you have any thoughts around code readability or topics that could be covered in the next couple of posts then please contact me via twitter or email.

The Trouble With Planning Poker

Photo: Unsplash

I am struggling to see the value of Planning Poker. There, I have said it publicly although I have struggled with the concept for some time.

My history with the technique started at a previous company. But we only tried it briefly before I left. That alone didn’t really help me see the value. One of my team suggested using it about a year ago, as the team grew. I was happy to trial it an see where we got with it. One year on and I am looking for a replacement for it.

The idea is a sensible one and if you have never used it then you can read about it in full here. In short:

  • Your team identifies a number of user stories to “point”.
  • You review a story and discuss it to the point that as a team you all agree with what is involved to complete it.
  • You then vote on the effort using planning poker cards. The cards have values that start at 0.5 and slide up the Fibonacci scale.
  • You discuss the points people have voted with and if anyone disagrees they are asked to clarify. You then go back to step 1 and repeat until you reach consensus.

There are many benefits including team collaboration. The idea is that you develop over time a team “velocity”. This is the average number of story points that you complete per sprint. Then the number of story points grouped into any planned sprint should not exceed what the team can deliver. This should allow you to plan when work is done. It all seems logical, doesn’t it?

The main problems I have discovered relate to effort and knowledge:

  • Effort - is relative to a given developer. It’s based on some variable factors. Most of the factors come down to experience. Development experience, language and stack experience and experience with your application’s code. My current team ranges from a first time developer to seniors with 10 years plus experience. That is a wide range of experience for the amount of effort to be relative to. The difference required in effort grows in line with the complexity of the story as well. Correcting a typo is the same effort regardless of experience. But we define a story that requires a whole change to a calculation engine. That will take the experienced developer less effort than the junior.

  • Knowledge - again development knowledge and experience as a developer all come into play here. A new developer will have less knowledge when they start on the team. That is obvious. It can be beneficial in other ways such as when they propose alternative approaches. But as they have grown their knowledge of your code base the effort they spend completing work reduces. This is the same for more experienced developers. They know patterns and approaches to solve problems. So the effort is reduced.

This is all highlighted in Planning Poker. It becomes clear that as you discuss a story there will be more dominant voices in the discussion. They are usually experienced developers who know the code. They never ask the interesting and usually thought-provoking questions. They come from the more junior developers who are trying to find out more about the story and any related code. So you end up not discussing the merits of the story. You end up with some of the team agreeing with what needs to be done. You then all vote and the difference between the team is clear. The more knowledgable team members ask those who voted different why. There is a discussion and while you try and drive the process fairly what tends to happen is the less knowledgeable developer’s fold. They agree with those “that know” and you get to an average pointing and move on. The process is not for less confident developers of that I am certain.

Now I put on my business hat. The process so far is about pointing stories with effort and building a velocity. The theory is that the velocity, combined with prioritisation and sprint planning, will provide an estimated delivery date. It never ever does. The reason is back to the relative effort it takes a developer to complete a task. I have run reports on this to discuss with the team. The developer who suggested the process wrote a supporting document to educate the team on points vs effort. In the document, a typo, for example, is 0.5. A change to a feature with some logic and a new DB column might be a 3 or a 5. When I report on delivered work and compare story points, the same points for the same task for different developers can vary by an hour or much more. The reports show that actually even after a year on a code base we are all familiar with, we can not point correctly.

Before you shout, I know that points are not time-related. But actually, they are. What use is a system of estimation to a business that will deliver in different periods of time based on who is doing it? Yes, I remember the agile manifesto and focusing on changes rather than plans. Businesses need to know when to expect a change. In my experience, you are better to give a far-out deliver date than be in the position of having to give a ballpark based on who is delivering the work. If they know it is coming then most times the business can adapt its plans.

The only thing the story points are useful for is guidance but not estimation. It can be useful to track developer and team effectiveness. The process hasn’t solved the development estimation problem. It is a problem that the entire industry suffers with and my theory around that lies with it being a creative task. No one asks a painter or a sculptor when their work will be ready? That’s not entirely a fair point but my thoughts around creativeness of development are for another blog post.

Right now with a big looming project to deliver, I am looking at alternatives to Planning Poker. I have briefly looked at Magic Estimation (it’s not) but have found nothing groundbreaking.

If you or your team have replaced Planning Poker I would love to hear more about what you have selected, why and how its working for you. If you have any thoughts around Planning Poker or think I am wrong about it (I am totally open to being wrong) then contact me via twitter or email.

Understanding The Implications Of The Code You Write

Photo: Unsplash

There is something I have noticed in developers recently. They do not always appreciate the implications of the code they write.

This may be the grumpy old git in me but I would actually suggest that the internet has made us lazy. Combine this with the typical pressure of delivering quickly and you have a lot of room for mistakes. Coding, after all, is a human, creative, process.

Sites like StackOverflow can be a source of solution and inspiration. But before they existed developers learnt from books. If you were taught how to achieve something it was by someone else who’d read the book. The books covered only very high-level topics. You couldn’t ctrl-c and ctrl-p from a site and have something working. You’d have to experiment and develop problem solutions yourself. There have been way too many occasions where I have looked at a problem with an odd solution. When I have then Googled the problem I’ve found the top answer is the code I am reviewing. Package managers have made this slightly worse. People grab packages that do what they think solve’s their need and then just work a solution using them.

Over the last couple of years, I have seen a few examples of code where the solution clearly didn’t fit the problem. My favourite was when I tasked one of my developers to add page caching to an application. We had been left with a part implemented solution which didn’t work. Instead of overhauling the code they turned off caching on the site totally. Their argument was that it fixed the problem. They didn’t appreciate the performance issue. I had another who decided to update the mechanism for sending alert emails from automated tasks. They decided that the class used to get the Database name from the config string wasn’t needed. Instead, they just added the string to the subject line of the emails. I received an email with the address and credentials for a test database in my inbox. When I asked why they had done this I was told: “it didn’t do that on my machine locally”. A recent example of this I have seen is when a fairly senior member of the team pasted the same Ninject mapping into multiple projects. These projects shared a common project which had a Ninject factory. The various projects only needed to implement mappings local to them. I had to make a change to the mapping and the 20 projects had to be updated.

Obviously, we are all human. We all have intense time pressures on us. We could blame laziness or someone else who wrote a package or library. The one thing we need to remember is that the code we write we are responsible for. Whether you are writing a piece of homework or software for industry there are consequences to your code. Your marks will suffer or a machine will fail to operate. While there are processes and testing teams to save you there is a cost to having to rework code. Estimates are shot, the cost of delivery goes up. This is something most developers do not consider. Nor is their professional reputation. So next time you create that pull request, make sure you understand and can defend your code in all environments it will run. Once you can, hit submit.

If you have any thoughts around this issue then contact me via twitter or email.

New York City Trip

Photo: Andy Crouch

A non-technical post this week as for the past week I have been in New York with my family. This was our first trip there but as I suspected, it did not disappoint.

We flew into JFK and had prearranged the Stewart Hotel on 7th Avenue. It turned out that this was an ideally placed hotel. Walk uptown along 7th Avenue 10 minutes and you are in Times Square. That walk takes you past Madison Square Gardens, the Pennsylvania hotel and Macy’s. The Pennsylvania is famous for being the place where the 1940 hit standard “Pennsylvania 6-5000” was written. Walk downtown on 7th Avenue and it will lead you down to Greenwich Village and Soho.

Right over the road from the hotel was Penn Station. This was convenient for getting the subway. The subway is really cheap. You can buy a 7 day pass for $31. I really recommend it as there is a station every couple of blocks. It makes getting around very easy.

We decided that there were a few things we wanted to see on this trip. On the whole, we got to see most of them. We were lucky with the weather. On our first main day, we hit lower Manhattan. We spent time walking around Battery Park and took the Staten Island ferry. This is free and allows good views of the Statue Of Liberty. We then walked up to Wall Street and had a look around the financial district. After stopping to see the Bull we headed over to the 9/11 Memorial & Museum. That is equally impressive and upsetting.

We already knew that the city was due some snow on the Wednesday. We decided that we would head to Central Park which we did and the snow came. It was great fun walking around the south end of the park and the surrounding areas in the snow. We decided to spend the rest of that day on one of the many sight-seeing bus tours. We lucked out and had a great guide.

The final big attraction we went to was the Top of the Rock Observatory. This is within Rockefeller plaza and provides stunning views of the city. We decided to get tickets for the early evening which allowed us to be around for sunset. Well worth the entry fee.

The rest of our time was spent walking around and soaking up the city. We didn’t have enough time to do a lot of the things we wanted. Tours of Harlem, Brooklyn and the Bronx were on our list but we will go back soon to see them.

A couple of food places stand out as worthy of a mention:

  • Browns Bagels at 132 W 31st Street. We tried a few different locations for bagels. This was by far the best as was their coffee.
  • The Tick Tock dinner at 481 8th Avenue. This was a great, old school, dinner. Top food at much better prices that anywhere near Times Square.

I would add that we did eat at Planet Hollywood on Times Square. It isn’t worth the cost and even as a film geek (as accused by my wife) the cost is associated with the name, not the exhibits.

We flew back from Newark. The ride out from the island via the Holland tunnel provide a contrasting set of views. I suspect that given half the chance I will explore New Jersey in the future. My only comment about Newark is that there is almost no shops or restaurants once you have gone through security. There are a small Duty-Free, a small Bar and a newsstand. So if you like to grab a full meal before a flight, get it before you go through security.

I loved NYC. It was everything I suspected and more. I feel like I have only seen a tiny part of what it has to offer. We are already planning a return trip.

If you have recommendations for our next trip for places to see or eat then message me via twitter or email.