This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Agile and Other Processes and the fly likes Self documenting code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » Agile and Other Processes
Bookmark "Self documenting code?" Watch "Self documenting code?" New topic
Author

Self documenting code?

Peter Kovac
Ranch Hand

Joined: Aug 08, 2010
Posts: 42
Hi Guys,

I hope you can answer some of my questions/rants about self-documenting code:

Names: names should describe the function but sometimes I feel it's overrated for example:
MergeListsFromResponseInputIfNeccessaryConditionsAreMet - especially if it's used in a call chain:

collectInputDataFromResponeThrowingExceptionIfNeeded (MergeListsFromResponseInputIfNeccessaryConditionsAreMet(.....))

Comments: yes, comments should be informative and terse but banning them is dubious. Why do I have to look through and understand 5 classes instead of reading 3 lines of comment? Besides a good IDE can show you the method comment while coding. Again I'm just saying the comments are not evil if used judiciously. Of course, if somebody modifies code they should modify comments as well - for 3-5 lines this shouldn't be a problem.

Small (3-5 lines) methods: method should be concise, but I don't know which is better:
∘ create a new method for every 3-5 lines OR
∘ using comments for code-blocks (for the same 3-5 lines) - still small methods (max. 20-25 lines)?

Creating a new method gives a higher overview when reading the code but

‣ sometimes it requires a lot of member variables just to store object state
‣ some code checkers report them as issues.
‣ some authors says that they're code smell.

Code is the documentation: my (somewhat limited) experience is that in some companies "agile" means no documentation "because there's the code", but If I have to make some changes into an unknown code base I think it's better to read some doc rather than to understand all the codes. Besides I don't really know how design decisions can be reflected in code, at all.
---
Am I too old schooled? What's your opinion and experience on self-documenting code?
Sorry if this is obvious, but I really want to hear your opinions.

Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4446
    
    5

Peter Kovac wrote:Hi Guys,

I hope you can answer some of my questions/rants about self-documenting code:

Challenge accepted

Peter Kovac wrote:Names: names should describe the function but sometimes I feel it's overrated for example:
MergeListsFromResponseInputIfNeccessaryConditionsAreMet - especially if it's used in a call chain:
collectInputDataFromResponeThrowingExceptionIfNeeded (MergeListsFromResponseInputIfNeccessaryConditionsAreMet(.....))

Your examples take the concept too far. They almost seem spiteful, like something my teenager would do when I tell him he's not paying attention--his response is to pay too much attention. The goal is to reveal the intent, to give the gist of what's being done at that point in the code, at the appropriate level of abstraction. It shouldn't give all the gory details.

Try: introduce explaining variable, mergeList(response), private List<Foo> getInput(response) throws InvalidInputException

Peter Kovac wrote:
Comments: yes, comments should be informative and terse but banning them is dubious. Why do I have to look through and understand 5 classes instead of reading 3 lines of comment? Besides a good IDE can show you the method comment while coding. Again I'm just saying the comments are not evil if used judiciously. Of course, if somebody modifies code they should modify comments as well - for 3-5 lines this shouldn't be a problem.

I have said this in other posts about self-documenting code but will repeat it here: Prefer to give good names that help reveal intent over writing comments. Key word is "prefer". Anyone who says otherwise is probably selling something. Any comments that supplement the self-documenting code should elaborate on the design intent, maybe add an "IMPLEMENTATION NOTE" to talk about thread-safety or security issues that need to be considered when using a class or implementing an interface. Again, the comments should avoid saying anything about the implementation details. If you give examples, I can give my opinion on whether it's appropriate or if it can be changed to a more useful comment. True, it shouldn't be a problem to update a comment along with code changes but it shouldn't be a problem for people to ignore text messages while they drive or give up smoking when they know that it can cause cancer; sometimes it happens, sometimes it doesn't. It works both ways but you should still prefer to use goods names.

Peter Kovac wrote:
Small (3-5 lines) methods: method should be concise, but I don't know which is better:
- create a new method for every 3-5 lines OR
- using comments for code-blocks (for the same 3-5 lines) - still small methods (max. 20-25 lines)?

My measure is the number of responsibilities, not lines. "Do one thing and do it well" is what I use to gauge if a method has too much going on or not.

Peter Kovac wrote:
Creating a new method gives a higher overview when reading the code but

- sometimes it requires a lot of member variables just to store object state
- some code checkers report them as issues.
- some authors says that they're code smell.

- use your professional judgement and have someone read the code to double check for clarity of intent
- suppress code checker warnings if you feel you know what you're doing
- everyone has an opinion; it all depends on what the actual situation is

Peter Kovac wrote:
Code is the documentation: my (somewhat limited) experience is that in some companies "agile" means no documentation "because there's the code", but If I have to make some changes into an unknown code base I think it's better to read some doc rather than to understand all the codes. Besides I don't really know how design decisions can be reflected in code, at all.

Code and automated tests should help document the detailed design. I also prefer to have high-level design and architecture documents that give me a picture of the lay of the land. The problems about updating documentation that's out-of-phase with the code still applies though so I always read documentation with a little skepticism about its state of maintenance. Automated tests are better as detailed design documentation and Automated Acceptance Tests are really good when it comes to higher level documentation; I recommend using them as much as you can. Lately, Robert "Uncle Bob" Martin has been going around talking about "intention-revealing architectures" (not his words, just my interpretation of what he's saying).

Peter Kovac wrote:
Am I too old schooled? What's your opinion and experience on self-documenting code?
Sorry if this is obvious, but I really want to hear your opinions.

Maybe you just haven't seen the "rules" applied judiciously and effectively. Or maybe you're just an ornery old codger who likes his old way of writing comments too much. IMO, writing self-documenting code paired with the right amount of additional JavaDoc comments requires much more discipline and skill than it does to just write comments the "old-school" way. The question now is: Are you up to the challenge?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

I was going to make a number of comments, but it's faster to say "I agree with everything Junilu said".

To expand on one of his points, I do think that unit tests can be one of the best forms of documentation. They are guaranteed to stay up to date (assuming you never allow failing tests), and if well written can be much better at expressing the intent of the code that the code itself. As a result I try and make my tests at least as readable as the rest of the code. And it's the one place I'll allow myself to have really long method names (not using camel case, for readability), because I'm never going to actually be calling them myself.
Peter Kovac
Ranch Hand

Joined: Aug 08, 2010
Posts: 42
First of all thanks for your "essay" I appreciate it..

Junilu Lacar wrote:
Your examples take the concept too far. They almost seem spiteful, like something my teenager would do when I tell him he's not paying attention--his response is to pay too much attention. The goal is to reveal the intent, to give the gist of what's being done at that point in the code, at the appropriate level of abstraction. It shouldn't give all the gory details.


Unfortunately the codebase I'm working with uses those long names that's why I might be a little furious..

Junilu Lacar wrote:
Maybe you just haven't seen the "rules" applied judiciously and effectively.


Yes that might be the case... but sometimes I feel that If a company uses agile it means forget everything that worked before...

Do you know any real project that uses self-commenting code effectively?

Junilu Lacar wrote:
The question now is: Are you up to the challenge?


Yup I hope so

--

On the intent-side.. What do you think using asserts for clarifying the goal e.g:

Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4446
    
    5

Peter Kovac wrote:Unfortunately the codebase I'm working with uses those long names that's why I might be a little furious..

Up until a few days ago, I too would probably react the same way. However, some very wise old-timers here at the ranch helped me realize that a more productive reaction is to show them examples of how it can be made better. Sure, allow yourself the indignant "WTF!" when you see it but try to keep it to yourself--unless of course you and your teammates are comfortable enough with each other that you can say "WTF!" without malice intended or taken--but rather than leaving it at that, give suggestions for, or help your teammates figure out, a better name.

Peter Kovac wrote:
Yes that might be the case... but sometimes I feel that If a company uses agile it means forget everything that worked before...

Then you have the honor of reminding them that "no documentation" is about as Agile as "no design" and "no planning": it's NOT. Rather, it's making sure that there is APPROPRIATE documentation every level of development.

Peter Kovac wrote:Do you know any real project that uses self-commenting code effectively?

Yes, there are many out there. You can start by studying what Kent Beck does with code for JUnit itself.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4446
    
    5

Something that I thought about earlier today after I posted my initial "essay"

That "Do one thing and do it well" thing, there will be those who argue that there are some methods where it is impossible to make it do just one thing. For example, what about the dispatch method in a controller class? These methods are delegating to other classes, gathering results, making decisions about the flow of execution, etc. What do you do with these methods?

I have my ideas on how to effectively answer that but I'm curious to see what others might have to say.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4446
    
    5

Peter Kovac wrote:
On the intent-side.. What do you think using asserts for clarifying the goal e.g:


Interesting question; had to take a second to think about that because I don't use them myself. I suppose using assert is fine if you don't do something like Test-Driven Development. I do TDD so I'm not very familiar with the recommendations for programming with assertions using the assert keyword. I do see that Sun/Oracle says that you SHOULD NOT use assertions for argument checking in public methods. I would go over the recommendations for the proper use of assert with my team and make sure we all understand when and when not to use them or if we want to use them at all given that there are other ways, like TDD and ATDD. The only other thing I can say is that given the kind of code you gave as an example, I would probably do an extract method refactoring to clarify the intent of the condition even further.
Peter Kovac
Ranch Hand

Joined: Aug 08, 2010
Posts: 42
Junilu Lacar wrote:
Peter Kovac wrote:
On the intent-side.. What do you think using asserts for clarifying the goal e.g:
....

Interesting question; .....

Hi,

Just to clarify.. In this case assert is used as a documentation mark and not necessarily in a test context - it might not even be turned on. It's something like using the @NonNull and other annotations to define the contract of a method..see: details1, details2

As a "challenge" what do you think renaming invalidateSessionToEliminateSesionFixation to eliminateSesionFixation?

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

How about this?
Peter Kovac
Ranch Hand

Joined: Aug 08, 2010
Posts: 42
Matthew Brown wrote:How about this?


I like it.. but it doesn't state why session was invalidated.. (session fixation elimination)
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4446
    
    5

Just one more word about documentation on Agile projects then I'll be done. Probably.

I've been re-reading "Software Craftsmanship: The New Imperative" by Pete McBreen, published in 2002 and early on in the book, he writes about Paul MacCready's talk at OOPSLA 1998. Paul MacCready was part of the team that won the first Kremer prize for human-powered flight. At one point [in the OOPSLA talk] MacCready mentioned how the blueprints for the Gossamer Condor were created after the team had won the Kramer prize. The Smithsonian Institute wanted detailed engineering drawings of the winning aircraft but apparently, the team had none besides the drawings that they had scratched in the dust on the ground, because "they got paid for flying a figure eight, not drawing blueprints."

While this level of detail may be good enough while development is going on, while the overriding goal is to get working software out the door, I have seen and experienced enough to know that it is prudent for good developers to at least give some thought to eventually having written documentation that can be used in the future to remind yourself and to educate others about key decisions that the team made during development. On my projects, we have a checkbox for design and architecture documentation on our DONE checklist. When we do our story acceptance review, we call out any actions that need to be completed before we check this box. That way, the team explicitly chooses whether or not to write additional documentation for future use.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2274
    
  28

Junilu Lacar wrote:
That "Do one thing and do it well" thing, there will be those who argue that there are some methods where it is impossible to make it do just one thing. For example, what about the dispatch method in a controller class? These methods are delegating to other classes, gathering results, making decisions about the flow of execution, etc. What do you do with these methods?

I have my ideas on how to effectively answer that but I'm curious to see what others might have to say.


Right!!! This is where it's helpful to design your code in layers. As you go lower (or rather deeper) into your layers, the responsibility of each component should reduce, cohesion should increase, and coupling should be low. At the same time, the density of classes in each layer should increase as you go down. Take 2 extremes:- Java util classes and controller classes. Java util classes (let's say java.lang.Math) are very highly cohesive, they do one thing (basic math), and do it well, but at the same time each of them don't do much; and there a lots of them . They are the rock bottom foundation of any program written in Java. Controller layer , OTH, forms the upper stratosphere of a well designed application. Controller classes do a lot of things (even if they don't do it themseleves). Also, in a well designed app there shouldn't be too many controllers, atleast compared to the lower layers. In between these 2 extremes, cohesion and coupling should be in a continuum.

Your upper layers is where a lot of jujitsu should happen. As requirements change, your upper layers should flow with them. Whereas your foundation layers should be rock solid, and should ideally never change. You might add to your foundation, but generally speaking, never change. Having a lower density of code in the upper layer makes it easy to change the upper layer. Having highly cohesive modules in the lower layers is what makes them solid.
Jeff Langr
author
Ranch Hand

Joined: May 14, 2003
Posts: 762
Great comments above on the use of TDD to bolster high-quality code.

If we try, the tests built via TDD can do a great job at documenting all the behaviors a class exhibits; this means that they can be used to understand how bits of code sequence together during execution. Without the tests, it's hard to understand how everything fits together (this is why javadoc is only so useful--its focus is on a single method).

Re: comments, the goal is to obviate their need with better code. I have a few "why" comments in my code, but they remain rare.

Junilu Lacar wrote:That "Do one thing and do it well" thing, there will be those who argue that there are some methods where it is impossible to make it do just one thing. For example, what about the dispatch method in a controller class? These methods are delegating to other classes, gathering results, making decisions about the flow of execution, etc. What do you do with these methods?


This is where I like Uncle Bob's statement of the single responsibility principle (SRP): "methods should have one reason to change," because it's a bit more specific. The SRP says to extract all implementation details from a dispatch method so that it simply delegates, which means that the dispatch method needs to change only if you add (or remove) a feature. It doesn't have to change if you alter how a feature behaves, because those implementation details are in another method.

Jeff


Books: Agile Java, Modern C++ Programming with TDD, Essential Java Style, Agile in a Flash. Contributor, Clean Code.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Self documenting code?
 
Similar Threads
Multiplication Table
Does your company require documentation? If so, what kind?
Javadoc of private/protected methods/variables
What's your commenting strategy?
Javadoc private state and methods.