Are comments a code smell? Yes! No? It Depends.

Most people are either firmly on the “Yes!” or the “No!” side when it comes to discussing comments and their status as a code smell. But, as with most question worth asking the correct answer rather is an “It depends”.

I got to re-examine this topic lately triggered by a tweet and a discussion with Devon:

So, let’s start unwrapping these layers, shall we?

Important distinction: Comments vs. Documentation

One of the first points on the list is understanding what a comment is and what it is not. For me documentation isn’t a comment, in most languages (unfortunately) documentation happens to be represented as a comment. Thankfully some languages, such as elixir, Clojure and Rust, have a separate construct for documentation to make this obvious and facilitate working with documentation.

I don’t think everything should be documented. However, libraries definitely need documentation (if you want people using them that is). I’ve also grown increasingly fond of documentation in application code, especially as projects grow. At Liefery core modules have a top level “module” comment describing the business context, language, important collaborators etc. It has proven invaluable. One of my favorites is the description of the shipment state machine that for each state shortly summarizes what it means – keeping all those in your head has proven quite difficult. Plus, it’s a gift for new developers getting into the code base.

Of course documentation still suffers one of the major drawback of comments – it can become outdated. Much less so if documentation rather provides context than describing in detail what happens.

So, documentation for me isn’t a comment. Next up – what’s this code smell thing?

What’s a Code Smell?

In short a code smell is an indication that something could be wrong with this code. Or to let the creators of the term, Kent Beck (whose idea the term was) and Martin Fowler, tell it in Refactoring:

(…) describing the “when” of refactoring in terms of smells. (…) we have learned to look for certain structures in the code that suggest (sometimes they scream for) the possibility of refactoring.

Does this description fit comments? Well, comments made the “original” list of code smells, with the following reasoning:

(…) comments often are used as a deodorant. It’s surprising how often you look at thickly commented code and notice that the comments are there because the code is bad.

They go on to explain what should be done instead of comments:

When you feel the need to write a comment, first try to refactor the code so that any
comment becomes superfluous.

That is exactly in line with my view of code comments. There is so much more that you can do to make your code more readable instead of resorting to a comment. Comments should be a last resort.

To further explore this, let’s take a look at one of my favorite distinctions when it comes to “good” comments versus “bad” comments.

WHAT versus WHY comments

I like to think of comments in 2 categories:

  • WHAT comments describe what the code does, these can be high level but sometimes they also tell you every little thing the code does (“iterates over, then… uses result to”)
  • WHY comments clarify why some code is like it is giving you a peek into the past why a decision was made

Let’s start with the WHAT – what comments can almost always be replaced by more expressive code. Most of this has to do with proper naming and concepts, which is why it isn’t uncommon for me to spend an extended period of time on these. Hell, (coincidentally) Devon and I even spent hours on defining “Scenarios” in benchee.

Variables, methods, classes, modules… all of these communicate through their name. So spending a good time naming them helps a lot. Often it is also the right call to extract one of these to keep the line count small and manageable while naming the concept you just extracted to help the understanding of the overall code.

Let’s take a look at one of my favorite examples:

Let this stand in for every long method you ever came across where the method body was broken into sections by comments. Extract 3 methods, name them somewhat like the comments. Enjoy shorter methods, meaningful names, concepts and reusability.

I’ve even seen people advocating for this style of long methods with comments. Easy to say, I’m not a fan. The article says “The more complex the code, the more comments it should have.” and my colleague Tiago probably responded best to that:

You should make the code less complex not add more comments.

Another example I wish I made up, but it’s real (I only ported it from JavaScript to Ruby):

As a first step just rename your parameters to whatever understandable name was commented above (also how does l translate to time per step?). Afterwards, look for a bigger concept you might be missing and aggregate the needed data into it so you trim the number of parameters down.

All in all, a WHAT style comment to my mind is a declaration of defeat – it’s an “I tried everything but I can’t make this code be readable by itself” You can be sure, if I get there I first consult a colleague about it and if we can’t come up with something I’ll isolate the complexity and then be sad about my defeat.

With all of that about what comments, how about WHY comments?

They can help us with things that can hardly be expressed in code. Let’s take a little example from the great shoes project:

While the puts statements communicates some of it, it is important to emphasize how dangerous not rescuing here is. The comment also helps establish context and points to where one could find more information about this.

This is an excellent use case for a comment and thankfully Kent Beck and Martin Fowler agree (again from the Refactoring book):

A comment is a good place to say why you did something. This kind of information helps future modifiers, especially forgetful ones.

There is an argument to be made that such information should be kept in the version control system and not in a comment. It is true: the commit message should definitely reflect this, ideally with an easy to produce link both to the ticket and pull request. However, a commit message alone is not enough to my mind. Tracking down a commit that introduced a change in an older code base can be quite hard (ever tried changing all strings from single quotes to double quotes? 😉 ) and you can’t expect everyone to always look at the history of every line of code they change. A comment acts a warning sign in places like these.

In short: WHY comments “yay“! WHAT comments “nay“!

Context matters

Before we get to the final “verdict” there’s one more aspect I’d like to examine: the context of your application. That context might greatly influence the need for comments. Another CRUD application like the ones you built before? Probably doesn’t need many comments. That new machine learning micro service written in Python and deployed with docker while no one in your team has done any of these things before? Yup, that probably needs a couple of more comments.

New business domain, new framework, new language, something out of your comfort zone, experience level of developers – all of these can justify more comments to be written. Those can give context, link to resources, WHAT comments describing on a high level what’s going on and so on. For instance, our route planning code has quite a few more comments explaining the used algorithms and data structures on a high level than the rest of the code base.

Yadda yadda – are comments a code smell or not?

As already established – it’s not as black and white as some people make it seem. To get back to the original twitter conversation that started all this:

For a shorter answer, I think Robert Martin also puts it quite well and succinct in Clean Code:

The proper use of comments is to compensate for our failure to express ourself in
code.

What about me? Well, if you asked me “Are comments a code smell?” on the street the answer would probably be “Yes”, the better answer would be “It depends.” and the good answer short of this blog post would be something along the lines of:

There’s a difference between documentation, which is often good, and comments. WHY comments highlighting reasoning are valuable. WHAT comments explaining the code itself can often be replaced by more expressive code. Only when I admit defeat will I write a WHAT comment.

(these days this even fits in a single tweet 😉 )

edit: As friends happily pointed out, documentation is also a construct different from code comments in clojure and rust. Added that in.

Advertisements

Slides: Optimizing For Readability (Codemotion Berlin 2015)

Yesterday I gave a talk at Codemotion Berlin, it was “Optimizing For Readability” – an updated version of my “Code is read many more times than written”. It features new insights and new organizational practices to keep the code base clean and nice. Abstract:

What do software engineers do all day long? Write code? Of course! But what about reading code, about understanding what’s happening? Aren’t we doing that even more? I believe we do. Because of that code should be as readable as possible! But what does that even mean? How do we achieve readable code? This talk will introduce you to coding principles and techniques that will help you write more readable code, be more productive and have more fun!

CS5j0v_WEAAm7S9.jpg:large
(pictures by Raluca Badoi

And here you can see the slides, sadly there is no video 😦 Slides are CC BY-NC-SA.

Hope you like the code, please leave some feedback. I’d especially love suggestions for a better talk title 🙂

I love Software Development, because it’s very collaborative and communicative

I often have the feeling that programming and software development is largely misunderstood. Many people seem to still have ancient believes about how software development works. Believes potentially scaring them away from pursuing a career in software development. Let’s fix this.

In this blog post I’ll show why the mental image of one person sitting in a cellar all by him-/herself is as wrong as it can be. I’ll explain why I believe that the most important ability of a software developer is his/her ability to communicate.  And I’ll highlight why I enjoy software development so much. (hint: there are also slides about this)

The typical misunderstanding

Let me take you through a somewhat normal conversation for me with strangers at a party:

misunderstanding
A rather typical conversation at a party.
(Note for clarity: the depicted conversation wasn’t about this and those people are actually dear friends of mine, not strangers)

Bingo! You’ve just won yourself a speech of how that is basically the opposite of what I do. My work is filled with lots and lots of communication. Let me walk you through some of the most important and most frequent communication activities in Software Development.

Communication within the team

Team Spirit, December 2006
Team Spirit, December 2006 (Photo credit: JF Schmitz)

Most software isn’t built by a single developer. It’s developed by a team or even multiple teams. I mean does anyone really believe that a single nerd in a cellar builds Facebook and another one builds Windows?

This software is built by large collaborative teams. In a team you have to work together to achieve something.The parts developed by members of the team have to interact and play nice with each other. To Facilitate this the authors have to communicate. As software often solves complex problems, these systems also have to be carefully designed. This is best done in a group of people in front of a whiteboard – not in front of a monitor.

Modern software development actually focuses a lot on the team developing software and how they work together. Let’s take a look at the Manifesto for Agile Software Development, the foundation of most modern software development processes. It values:

Individuals and interactions over processes and tools

This is the very first point made highlighting that good software development is about people and how they work together. It’s not only communicating about the project, solving difficult problems together – of course the normal small talk and “grab a drink together after work” is included as well 😉 Motivation is very important.

It doesn’t stop here though. Often software projects are big enough that multiple teams have to collaborate to realize them. There is a lot of communication going on there as well. But there are still other people developers should communicate with like the system administrators and the customers. Wait, what – the customers?

Communication with the customers

Yep the customer. The ones ultimately using the applications. Or the client wanting the application.

Unfortunately that thought might seem alienating at first, but think about it. Those are the people who ultimately know what the application should do. They are the ones that will be using it, it should fit their purposes. The only way to know if the application reaches its highest goal, satisfying the customer, is through frequent communication and thereby feedback. That starts with asking them what the application should do and how it will be used. It doesn’t stop there though, it is enhanced through demos of a prototype of the application to verify understanding.

Some people take this even one step further. In one of the all time classic books about programming, The Pragmatic Programmer, it is recommended that you spend as much as one week working with the your users before writing an application. This way you should get to know what their work is like.

All of this generates invaluable insights and builds trust.

Look, there are two of them in front of just one monitor!

A friend and me doing some Pair Programming

Yep that’s two developers in front of just one monitor. Actually it’s me and a good friend of mine. So what do we do? Well naturally we are working. We are doing Pair Programming. That is one of us is actually writing the code while the other one observers. We both design the code and talk about it. We work together.

Some people think that this is a waste of time. Hell those are 2 programmers, give them 2 PCs so they can write twice as much code!

It’s not as simple as that. In software development we constantly solve problems. Solving them together leads to a solution sooner, higher quality code and more knowledge spread across the team. The benefits of Pair Programming are worthy of a whole blog post of their own.

Despite the benefits Pair Programming is still a pretty debated topic. Some people despise it. Some people only apply it to difficult problems. Some people say that all production code must be written in Pair Programming.

For me I love Pair Programming: It makes programming a lot more enjoyable, at least to me. When you try to solve a complex problem sometimes you hit the wall. You just don’t know how to solve this problem. You’ve run out of options. It can be really frustrating. That never happens to me when I’m Pair Programming. We, as a team, never seem to run out of ideas on how to solve a given problem until we find one that works. On top of that I can communicate and collaborate with someone all the time. How much more awesome can it get?

And what’s my point with this? During a good normal work day, I actually communicate and collaborate with at least one person almost all the time. Sweet.

Communicating through code

Now I really gotta be kidding right? What does code have to do with communication?

A lot actually. Let’s see what Kent Beck says in his book “Smalltalk Best Practice Patterns” in the Introduction chapter:

“(…) when you program, you have to think about how someone will read your code, not just how a computer will interpret it.”

Kent Beck

And that someone refers to the people in your team as well as yourself. As a team you work together meaning that you have to be able to understand and extend the work of your colleagues. And of course you must be able to understand what you wrote some months ago or even just some weeks ago. You might be surprised how difficult this can get with poorly written code.

Good code must communicate well. The best code, in my eyes, is the code that is the easiest to understand. Code that pretty much speaks to its readers. Writing such code can be very challenging. You can find me discussing with my Pair Programming partner about naming questions for like 2 minutes – it is important.

(Taken from OSNews)

Does everyone work like that?

Not every company empowers their teams. Not everyone loves pair programming. Not every company cherishes communication. Not every company works Agile. There are people out there still following the Waterfall process, which has been a misunderstanding from the beginning, where at first rigorous documents are made and then the programmers are locked away to “just code it”. Why do people keep doing this? I have no idea. I just know that there are enough tech companies looking for developers out there so you don’t have to end up at an old-school command & control enterprise.

So with all this talk about communication one might ask: “What about the introverts? What about people who don’t like to talk as much?”

Well I’ve worked with some people who might qualify as introverts. Let me tell you this: I’d love to work with each and every one of them again.

See communication is not a one-way street. It’s not just about talking, it’s at least as much about listening. People who just talk but don’t listen are bad communicators. Maybe more introverted people don’t talk as much. However with the ones I know I found that if they say something it is of immense value. And they are very good listeners as well. Plus they enjoyed Pair Programming as much as I did. I would say they are good communicators and collaborators. To me bad communicators and collaborators are those that don’t work together with the team and spend most of their time simply criticizing others.

Wrapping up

stickies
Look we got post-its too! (Thanks for the photo to Andreas!)

So what’s the lesson here? Well today’s Software Development is a lot different from what many people think it is. You work together as a team. You talk. You draw on white boards. You have those funny little post-its to coordinate work. Some people work together all day long. You have fun. You actually communicate with he people using your product.

As I hinted at first all this makes me believe that the ability of developer to communicate is more important than his/her technical ability. Developers are part of a team. If they excel technically but don’t know how to share their expertise with the team then they’re not helping much. Even worse, people who spend meetings just criticizing ideas can easily kill the motivation of a team and slow them down significantly. Luckily I haven’t met many of them.

Good communicators and collaborators on the other hand do everything for the team. They help and motivate each other. They happily share their knowledge and are always ready to learn new things.

So my point is this: Do you like solving problems? Do you like to work in a team? Would you like to work in a continuously evolving field with lots of new technologies and opportunities? Do you like to build something awesome helping many people?

Congratulations, software development might be just the thing for you!

Meet 5 software projects making the world a better place

betterplace.org logo

I was at an event two days ago where the topic was teaching programming. During this event attendees raised the problem, that there aren’t enough software developers. During the following discussion it was suggested that if you could show the positive social impact you can have through software development, it could be more attractive for people to get into. “If there were any such projects.”

There are tons of those projects and initiatives. Let’s meet five of them right now!

1. Ushahidi

A screen shot of the original Ushahidi web mashup taken form their about page.

Ushahidi means “testimony” in Swahili. It is a project that a group of programmers started in the aftermath of the 2007 presidential election in Kenia. There was a major outbreak of violence and it was simply too hard for bloggers and other people to report all the incidents of violence that eye witnesses reported to them.

Enter Ushahidi. It was an application build quickly by a group of programmers to map out reports of violence on google maps, a so called “mashup”. This way they made it easy for people to report incidents of violence and made it accessible to everyone. Well everyone with an Internet connection.

Ushahidi has since become a platform. Anyone can download Ushahidi and deploy it for their own purposes. For instance Ushahidi was used after the 2010 earth quake in Haiti to report events. Also Ushahidi is open source, so feel free to help improve this awesome project.

You can hear more about it in this highly recommended TED Talk: Clay Shirky: How cognitive surplus will change the world

2. betterplace.org

betterplace.org logo
The betterplace.org logo

betterplace.org is a platform where people can donate for social projects or raise funds for a social project. You may think of it as kickstarter for social projects. Betterplace.org focusses a lot on direct and transparent support of projects. The platform is free to use and they pass on 100% of all the donations. You can see a more thorough explanation of what they do and how this is more effective than conventional funding here.

So how do they finance themselves? Well short answer: Some sponsors and friends help them. Moreover donators are free to give a little extra money to support betterplace. There is also a longer answer.

On a little side note: They are based in Berlin and very nice people 🙂

3. Random hacks of Kindness (RHOK)

hacking at RHoK Berlin
hacking at RHoK Berlin (Photo credit: @anked)

The motto of Random Hacks of Kindness is “Hacking for Humanity”. It is a global community building open technology to help make the world a better place. As such it is a prime example of an organization trying to improve the world through the use of software. You can find a list of projects developed in their wiki.

Random Hacks of Kindness hosts global events, also called hackathons, where people meet and work on solutions for problems together. The next global event will take place on the first and second December 2012. You can check if there is an event organized near you here. I’ll be attending the event in Berlin, so go ahead and join lots of other people and me. Let’s have fun together hacking and doing socially good.

4. Mission of Mercy

Mission of Mercy logo taken from their github page.

Mission of Mercy is a clinic management application for free dental clinics and is used in the United States. This application helps these free dental clinics tremendously by supporting the clinc flow. It was created and is mainly maintained by the awesome Jordan Byron, a co-founder of the Mendicant University.

5. Stadt Land Code

Stadt Land Code Logo
Stadt Land Code Logo taken from their home page.

A German initiative (English: “city country code”)  to support the development of more digital tools for citizens to improve social life. Fields of interest include, but are not limited to: public transport, infrastructure and politics. In general the tools should make it easier to participate and really make a difference. FixMyStreet is a good example of such a digital tool. The initiative includes a work shop and the possibility to win a project funding of 2500€.

Conclusion

See there are lots of software projects or initiatives having a social impact or aiming to have a social impact. Do you know any other social projects? Please feel free to leave a comment!

Many of the projects are open source, so go ahead and contribute or join the next Random hacks of Kindness event near you. Start your own project. Host your own event. It’s up to you.