Hacker News new | ask | show | jobs
by rootlocus 1148 days ago
Simple anecdote: A colleague of mine had a really hard time getting some topologic sort to work. I kept finding issues with his implementations and he was getting frustrated so we aggreed to have a pair programming session. He wanted to put all the code in a single method (not terribly long, maybe 30, 40 lines), but the conditions kept nesting and no matter how much he tried to figure them out, he couldn't get them to work. I convinced him to extract two methods which would only be used once and only inside this sorting method. He was vehemently against it. After he finally agreed he realized the code was so easy to read, it was basically self-explanatory and obviously correct. No ammount of fiddling with the if statements could've produced that.

I don't impose fixed line counts for my methods. But when it makes sense, the readability improves a lot.

2 comments

Yeah line count is a hard metric to evaluate. Is your code 100 lines of code like this:

    let foo = Foo::new()
        .with_bar()
        .with_baz(bak, bat)
        .listen();
Or code like this:

    for f in in foo.iter() {
        if f == 1 || f > 9 || f % 2 == 0 || is_edge_case(f) {
            ret.push((f * 100).to_string());
        }
    }
Makes a big difference for readability. If you have a complicated conditional, go ahead and give it a name!
I have essentially the same story, so I won't repeat it. The big win was when my colleague seized on the idea of self documenting code. That was all he needed to write better structured code.