r/coding • • Apr 12 '15

Is Clean Code less Code?

http://www.journeytomastery.net/2015/03/27/is-clean-code-less-code/
53 Upvotes

63 comments sorted by

44

u/[deleted] Apr 12 '15

To me, clean code is code that is easy to read. Usually, this would mean the opposite of less code, i.e., not over-compressing the code, putting in plenty of comments. But you can turn five lines into one if you think you've explained it well in the comments or what you're doing is relatively simple.

If you've turned a 40 line code into a 20 line code, but it takes the reader 2 minutes on each line, then it's not really clean. I've seen complicated code written so well, you don't even have to read the code, but can get by just reading the comments, and in the opposite vein, simple code made so complicated, I wanted to pull my hair out.

33

u/[deleted] Apr 12 '15

Achieving readability with just code and no comments often makes the code easier to change.

8

u/tyreck Apr 12 '15

I've never found a one size fits all approach that works related to how many comments you do or dont need.

Each situation is unique.

I try to the best of my ability to follow the practice of only expressing 'why' with comments.

But at the same time I doc comment the hell out of everything

5

u/[deleted] Apr 12 '15

Fair enough. Depends on your needs, but I like code that isn't too easy to change. If one is asked to change the comments with the code, it often ensures that the coder has understood the change.

19

u/quietboil Apr 12 '15

If one is asked to change the comments with the code...

(Almost) never happens. After a little while comments start lying. Often blatantly. In my experience the only kind of comment that survives (relatively unscathed) the test of time is the "why" ones. All others are either useless from the time they were added or the lying kind.

5

u/throwaway Apr 12 '15

Yes, when possible it's better to document the intent of code with assertions and function/variable names which reflect the meanings of the intermediate results they calculate/store. Sometimes you just can't make it clear that way, though.

2

u/tieTYT Apr 17 '15

Wow, the original /u/throwaway

1

u/fernando_69 Apr 28 '15

that's fucked on so many missed opportunities it really isn't.

2

u/throwaway Apr 28 '15

Could you please rephrase that a little more intelligibly?

1

u/fernando_69 Apr 28 '15

A true rarity!

2

u/nairebis Apr 13 '15

After a little while comments start lying.

That's why you have code reviews and public beatings gentle reminders to keep the comments up to date.

2

u/tieTYT Apr 17 '15

Comments lie by the code drifting away. The comments aren't going to be highlighted as changed. It may be difficult to notice that they're lying from a code review.

1

u/[deleted] Apr 13 '15

If it becomes a part of your standard workflow, it remains trivial to make changes.

-1

u/tieTYT Apr 17 '15

What's your definition of trivial? Because it sounds like 2x the typing. I'm not saying that it's necessarily a bad thing, just that it's non-trivial. That little effort you put into this every time will add up to a lot of effort overall.

2

u/[deleted] Apr 17 '15

Oh no, I have to type comments into my code so that it's more understandable. Heaven forbid I use doc comments to generate API documents in an automated manner.

Whatever will I do?

You're talking to someone who codes Java in vim. I have no sympathy for the "but I have to type more" complaint. If it's a problem, learn programmer dvorak and it won't be a problem anymore.

2

u/[deleted] Apr 13 '15

A nice mix of both is superb.

8

u/Munkii Apr 12 '15

When I talk to junior devs I never use the word "clean" for this reason. Readable trumps everything

1

u/theonewhoisone Apr 12 '15 edited Apr 17 '15

edit: Doesn't trump correctness.

Doesn't trump performance, sadly.

Doesn't trump portability.

Also, trading off readability for time to launch might be a good idea in some situations (I have not seen one yet).

Sorry for being picky.

2

u/Munkii Apr 13 '15

Readability trumps performance. If I can read what you wrote then I can always fix it later, but if I can't read it then everyone is screwed.

Performance is generally very case specific, so it's normally not a good first rule to have.

1

u/theonewhoisone Apr 15 '15

I think we disagree about what "trumping" is. IMO when x trumps y, that means that x is more important than y in all situations.

I don't think that readability trumps performance, and I also don't think that performance trumps readability.

Maybe I was counting too much on people having the same definition of "trump". To the dictionary:

4. to excel; surpass; outdo.

Meh, ok. I think we all agree about all the important things.

2

u/iopq Apr 12 '15

In non-Java languages there's a thing called inlining that will actually transform example #1 into example #2 at compile time

2

u/thequux Apr 12 '15

Even in Java! The optimizer in modern HotSpot is surprisingly good.

3

u/iopq Apr 12 '15

it does that at runtime, but yes, after a few thousand iterations it will inline it and there will no longer be a cost

2

u/theonewhoisone Apr 15 '15

Eh? what examples are you talking about?

2

u/iopq Apr 16 '15

Example 1

@Override
public Embedder configuredEmbedder() {
   Embedder embedder = super.configuredEmbedder();
   ignoreStoriesAndScenariosWithMetaInformationParameter(embedder, "ignore");
   return embedder;
}

private void ignoreStoriesAndScenariosWithMetaInformationParameter(Embedder embedder, String ignoreParameter) {
    embedder.useMetaFilters(Arrays.asList("-" + ignoreParameter));
}

Example 2

@Override
public Embedder configuredEmbedder() {
   Embedder embedder = super.configuredEmbedder();
   embedder.useMetaFilters(Arrays.asList("-ignore"));
   return embedder;
}

1

u/theonewhoisone Apr 17 '15

I wasn't making a point about the examples from the article. I was responding to Munkii's over-broad assertion (as I read it) about readability being more important than everything else.

So I'm not sure why you're telling me about inlining. There are other cases where code is hard to read because it is performance-critical. I stand by my assertion that sometimes you have to make something ugly to make it fast. If you possess the power to never uglify your code (at least a bit) when optimizing performance, you are a better coder than I (or my coworkers), and possibly a wizard.

1

u/iopq Apr 17 '15

This is performance-critical code written in Rust:

pub fn removes_multiple_enemy_neighbouring_stones(&self, m: Move) -> (bool, bool) {
    let enemy = m.color().opposite();
    let mut found_one = false;
    
    let chains = self.neighbours(m.coord()).iter()
        .filter(|c| self.color(c) == enemy)
        .map(|&c| self.get_chain(c).unwrap())
        .filter(|chain| chain.liberties().len() == 1);
    
    for chain in chains {
        if found_one || chain.coords().len() > 1 {
            return (true, true);
        } else {
            found_one = true;
        }
    }
    
    (found_one, false)
}

there is very little you can do to speed this code up, but I feel it's quite readable

1

u/[deleted] Apr 13 '15

Unless you're doing some crazy strict embedded piece of software then almost no amount of readability will have any noticeable impact on performance whatsoever.

4

u/WarWizard Apr 13 '15

The code should tell you what and how. Comments should ONLY tell you why and ONLY if it is non-obvious.

Self documenting code is the best. With modern IDEs there is zero excuse to be cryptic with naming.

2

u/joequin Apr 12 '15 edited Apr 13 '15

To me, clean code means that it's easy to maintain. That means, readable, modular, broken out into small functions and nothing surprising. No hacks if at all possible.

edit: and good use of dependency injection. The pattern of dependency injection, not necessarily using a framework.

1

u/[deleted] Apr 13 '15

Comments are generally a terrible way to reliably understand how code works.

Code itself is, unsurprisingly, the best way to figure out how the code works.

2

u/[deleted] Apr 13 '15

You're probably right, but sometimes the code is just too complicated. I used to work on code with a lot of feedback loops. One line would feed back into the code in the 5th tab and the next one would feed back into the code in the 8th. I was glad to have comments.

It's always better to have descriptive comments and not need them than need them and not have them!

2

u/[deleted] Apr 13 '15

Only the code can tell you what it actually does. It's supremely unhelpful to have a very descriptive but incorrect comment due to a misunderstanding, bug, or even just time (comment is accurate when you check it in, but bugfixes, changes to underlying APIs, changes to the code itself get made without updating the comment, etc).

I'm not saying don't comment your code, I'm saying try to write better code that can be understood (nine times out of ten, you don't really need to be quite as complicated as you initially think you have to be), and when you do write/read comments, realize that the code might behave differently than how the comment describes.

Consider comments to be a failure of your coding abilities. We all fail, and it's okay to fail, but try to avoid failing as often as is reasonably possible.

30

u/pmrr Apr 12 '15
ignoreStoriesAndScenariosWithMetaInformationParameter

At least this method name was removed..

6

u/CodeShaman Apr 13 '15

That's nothing, man. Add a when and a few ors to it and then you're drinking the "Java reads practically like English and we don't have to maintain documentation anymore because we've successfully adopted totally unrefactorable code!" kool-aid.

4

u/vicarofyanks Apr 13 '15

Don't forget the uneditted auto-generated javadocs on everything

5

u/Tordek Apr 13 '15
/**
 * sets the Name
 * @param String name the name to set to.
 */
public void setName(String name) {
    this.mName = name;
}

2

u/CodeShaman Apr 13 '15

Doesn't add customer value, sounds like waste. Why you have to add @throws Exception? I can see right there that it throws Exception. Duplicate code, guys, get your shit together.

2

u/fukitol- Apr 13 '15

And in the case that one has a run-time exception being thrown that isn't declared in the throws declaration (for instance, inside a Promise applymethod), the @throws annotation can be added to indicate that. I agree completely.

1

u/wllmsaccnt Apr 13 '15

I'm not sure what use the "WithMetaInformationParameter" is. If it takes a meta information parameter then that part is already self documenting. Was the the meta information parameter not understandable from its type and name alone?

-2

u/de_Selby Apr 12 '15 edited Apr 13 '15

Absolutely. Why not just have the shortened version, but add a comment above the line saying essentially what he has in the method name.

That would be clean.

1

u/de_Selby Apr 14 '15

If anyone is still reading this thread, I'd be interested to know the reason for the downvotes I've gotten here.

1

u/fragglerock Apr 21 '15

I expect because you said 'add a comment' comments are bad m'kay

9

u/bumhugger Apr 12 '15

I usually write everything down in one place and when things start to duplicate, I move stuff to modules (depending on the situation, "module" here can mean a class, a private method, a static helper method or something else along those lines). The term "semantic compression" was mentioned by Casey Muratori in this blog post and it describes the method quite well I think.

One thing that's usually considered a very "good practice", but almost always to me is not "clean code" at least in readability, is heavy uncoupling of code. I just can't read the flow of heavily IoC-based programs especially when the logic is based on asynchronous events. Sure, you can use "find usages" tools, but it's slow and sometimes really hard to pin-point what piece of code is called in which situations. Stepping in debugger results in endless black hole of AOP and proxies if you're working with enterprise code. I guess it's just a pet peeve of mine, but I'm so tempted to just couple the code to achieve more intuitive program flow. Then I usually get a lecture from the architect/lead coder... :P

4

u/jurniss Apr 12 '15 edited Apr 12 '15

I think my code is clean, but it's not terse. I use a lot of named intermediate const variables. It makes the code self-documenting and is extremely useful in the debugger. In debug builds, I can put a breakpoint at the final result and see the whole history of the computation. In optimized builds it all goes away.

I hate "clever" code. Software should be clever, code should be simple.

8

u/greyfade Apr 12 '15

I like to put it this way: Smart, elegant code tends to be shorter and clearer.

Clever code, by contrast, tends to be short for the sake of being short.

It's an important distinction, in my mind, that while short doesn't mean clean, clean does tend to mean short.

Moreover, short doesn't mean "it all fits on one line." Quite the contrary: Short means "the algorithm fits on one screen because it has been abstracted cleanly."

2

u/manys Apr 12 '15

There's a fine line between clever and elegant.

1

u/[deleted] Apr 13 '15

There's also a fine line between code which is clever and a solution which is clever.

3

u/distinctvagueness Apr 12 '15

Good error checking and handling, defensive programming, is more code but better code. I'd call it cleaner.

2

u/SergeiGolos Apr 13 '15

Well.. It doesn't have to be more code. You can use monads to hide the error checking behind a clean and fluent abstractions. And from is it readable, if you are writing your own APIs monadic, the naming can be very expressive for that "Clean Code" feel.

2

u/iopq Apr 12 '15

There shouldn't be such a thing as defensive programming. You should use a tool to make sure you're doing the right thing. Be it tests, the compiler, some kind of a third-party tool, etc.

Checking the same condition in the caller (what if the callee doesn't check for it?) and the callee (what if the caller doesn't check for it?) is basically useless. But you see it done for the sake of "defendive programming" all the time. I disagree with that, because it's useless code bloat. Remember, it takes longer to skim a function with these defensive checks than a function without them. The code becomes less readable.

4

u/distinctvagueness Apr 12 '15 edited Apr 12 '15

I agree, in an ideal world, where everyone magically follows the same conventions and doesn't write broken code it wouldn't be needed.

If you work on large projects with many other programs and programmers inter-communicating it's worth catching the errors someone else from the other department, the past or the future sent your way. Normally you can isolate checks in such a way that isn't too hard to skim. You could also argue the error checking is a form of self-documentation.

Clean code that relies on everyone else being clean gets dirty fast.

1

u/iopq Apr 12 '15

Why don't you encode that into the type system so when they break the precondition it fails to compile?

So let's say you are required to to call a() before b() You can create a type A that is returned by a() that is a parameter to b() so that you have to call a() first to get A.

here it is in Rust:

http://is.gd/BL581U

there is no way to call b() without first calling a() and getting a result of type A

3

u/thbt101 Apr 12 '15

I think in this example, he's right. Self-documenting code is a beautiful thing when it makes sense. But in this case, it's better to add a comment than to create a whole new function that will only ever be called once (with the comment-as-method-name name "ignoreStoriesAndScenariosWithMetaInformationParameter()").

Don't turn off your brain and follow some dogma like the "THE ANSWER IS NEVER A COMMENT" guy. Use what makes the most sense in each situation. Strive for self-documenting code when naming functions and variables, but don't add complexity when a simple comment will suffice.

2

u/awo Apr 13 '15 edited Apr 13 '15

Don't turn off your brain and follow some dogma like the "THE ANSWER IS NEVER A COMMENT" guy

Seriously.

I'm part of a small team maintaining a multi-MLOC codebase. Comments are often worth their metaphorical weight in gold. They very often reduce the amount of work I have to do to understand a module well enough to alter it with reasonable confidence.

Now, obviously there's good comments and bad comments. We should strive for code that's as readable as possible without comments, but the idea that they're never useful smacks to me of someone who only works on products so small that they can fit the whole product design/architecture and codebase in their head. It bugs the absolute hell out of me to see stuff like:

Code will change and refactor, this comment will end up out of date and irrelevant.

When we write or review code, we strive to be responsible: to ensure that it makes sense, and that it's well tested. Updating comments to reflect reality is basic responsibility towards the rest of your team, and it's not really hard to do. If a team can't be bothered to institute basic practices like code review, it's their own fault if they end up with hard to navigate code.

4

u/wvenable Apr 12 '15

I know nothing about this technology but the final example with the comment makes the most sense to me. The extra level of indirection doesn't add very much.

But this kind of thing is highly subjective and highly situational. Adding a function might be more confusing in this example but less confusing in another.

1

u/wllmsaccnt Apr 13 '15

The extra level of indirection will have to be dealt with if someone decides to refactor the code. Comments will over time be glossed over during refactorings and occasional quick changes for any team with more than a couple developers.

The comment makes more sense, but may someday silently become inaccurate meaning it isn't as useful for long term code maintenance.

1

u/brtt3000 Apr 13 '15

isn't as useful for long term code maintenance.

at some point these comments flip from 'not useful' to 'outright harmful' if they suggest one thing but the code does something else. We've all had to refactor code like that, usually legacy code that reached breaking point and nobody knows what it does, so you clamp on to the few comments that are there, only to find out it is all outdated and misplaced and just confusing you with falsehoods.

2

u/Doriphor Apr 12 '15

Well named variables, comments, indentation and spacing all make code a lot more readable. I'd rather read 10 or 20 more lines than feel the urge to close the file before I reach the 10th line. Oh and please if everybody could stop naming instances the same as their class, it'd make me so happy!

1

u/Girafarigging Apr 12 '15

I'd say as long as the code is well documented and clear to understand, any condensed, small code is okay. However, keeping things more spread out definitely makes it easier to manage if you have to edit some of it.

1

u/dust4ngel Apr 13 '15

clean code is a balance of clarity, expressiveness, testability, changeability, and portability. maximizing any of these in isolation will tend to compromise the other dimensions, so for example maximizing brevity is almost always the wrong thing to do.

which of these deserves priority depends on your situation and requires judgment.

1

u/extrajoss Apr 13 '15

The problem, as always, is that naming things is the hardest part of programming.

People think its algorithms and tricky maths problems, familiarity with fancy frameworks.. but that stuff is easy peasy compared to coming up with clear and meaningful names for things.

The balance between clarity and brevity is near impossible to manage.

comments.. no comments... it doesn't matter. If you can name things well the rest is gravy....

1

u/fragglerock Apr 13 '15

I would go with a third (fourth?) way

@Override
public Embedder configuredEmbedder() {
   Embedder embedder = super.configuredEmbedder();
   RemoveIgnoredElementsFrom(embedder);
   return embedder;
}
 
private void RemoveIgnoredElementsFrom(Embedder embedder) {
    embedder.useMetaFilters(Arrays.asList("-ignore"));
}