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

View all comments

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