Why we comment code

6
Michael Geiser PhillyJUG June 24, 2015

Transcript of Why we comment code

Page 1: Why we comment code

Michael GeiserPhillyJUG

June 24, 2015

Page 2: Why we comment code

You are writing code that will be read and modified by people, including (especially) your future self. They/you will have to debug or modify the code.

Commenting is necessary because you need to tell people what you intended to do and why you chose to do it a specific way. While what the code does should be "self-evident" (too often an

oxymoron) from inspection of the code, you need to communicate what you INTENDED to do; it is possible (however unlikely) you made a logic error.

Comments also do NOT slow you down (as some people object) ; I’ve timed it. I spend at most 10 to 20 minutes commenting a class that with Unit Tests took 3 hours+ to write. It is impossible to argue that is not time well spent.

Comments are NOT counted as LOCs and absolutely do NOT add to maintainability costs; they do just the opposite.

Page 3: Why we comment code

Just as there are many ways to skin a cat (that is really an awful expression, isn't it?), there are many ways to implement the logic on how to fulfill a requirement. I’m sure you always have insightful and well-reasoned

thought processes behind why you implement a bit of logic in a certain way. You need to document in comments why you used that specific implementation.

Commenting will answer questions without future maintainers guessing (and second-guessing) your reasons and allow them to determine if the implementation is still the best implementation as the application evolves and business requirements are refined or changed over time

Page 4: Why we comment code

Not all classes need the same level of commenting

DTOs do not require much commenting

More complex implementations can have more bytes of comments than code – that’s a good thing!

Level of commenting will vary

Page 5: Why we comment code

Comment content should be What you intended to implement (the code

self documents what you did implement) Explanations of how tricky and clever bits of

code work (for people not as smart as you) What User Stories/documents have the

requirements you’re implementing Design Decisions (for example: why you

chose HashMap over TreeMap or LinkedHashMap)

Err on the side of too much commenting

Page 6: Why we comment code

I have a simple one class example that illustrates my point.

This is a quick “down and dirty” app that is meant to run from Eclipse.

Evaluate the MontyHallProblem_NoComments.java version of the class first and then evaluate the MontyHallProblem.java code.

GitHub Website: https://github.com/mgeiser/MontyHallProblem

https://xkcd.com/1282/