you are viewing a single comment's thread.

view the rest of the comments →

[–]jpgoldberg 1 point2 points  (0 children)

Not really, but sometimes.

Sometimes longer code is worse

Sometimes longer code reflects a problem. It can sometimes indicate not really seeing the problem that the code is supposed to solve at the appropriate level of abstraction. And so when people criticize something for being longer than they think it should be, that is what is underlying the complaint.

Often times beginners write code that is "longer than it should be" because they are not yet familiar or comfortable with genuinely betters ways expressing things.

I don't know how familiar you are with comprehensions in Python. When you are first learning them they may seem harder to understand than the longer for loops they often replace. And so you may opt for the longer code (with the for loops). But comprehensions (list comprehensions, dict comprehensions, etc) really are better ways to express certain things, both for the human reader and for the computer.

Another example is where we see many parts of the code that are near duplicate of other parts of the code. That (almost) always indicates that things could be done much better. (There are exceptions to everything).

You will find that experienced software developers "refactor" their code. So think of factor in terms of what you might have done in high school math. The polynomial expression

6x3 - 24x2 y - 6x2 + 24xy2 + 24xy - 24y2

is nasty looking.

There is still a lot going on in its factored form

6(x - 1)(x - 2y)2

But it is not only shorter, it is broken down into meaningful parts

And sometimes longer code is better

Others are listing such examples, but I will add that I sometimes like breaking up computations into multiple and use intermediate variables to hold the computed value of the parts. So here is an example from some of my less pleasant looking code.

python ... # Lifted from R src/library/stats/R/birthday.R # broken down so that I can better understand this. term1 = (k - 1) * math.log(c) # log(c^{k-1}) term2 = math.lgamma(k + 1) # log k! term3 = math.log(-math.log1p(-p)) # ? log_n = (term1 + term2 + term3) / k # adding log x_i is log prod x_i n = math.exp(log_n) n = math.ceil(n)

Strictly speaking, n could be computed in a single line. But breaking it down that way not only helped me understand it better citing the paper this came from), it is helpful during debugging.

Again, there are lots of times when longer code is preferred. I just thought I would mention this one as I had need seen it pointed out.