Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should code be short/concise? [closed]

Tags:

math

proof

When writing a mathematical proof, one goal is to continue compressing the proof. The proof gets more elegant but not necessarily more readable. Compression translates to better understanding, as you weed out unnecessary characters and verbosity.

I often hear developers say you should make your code foot print as small as possible. This can very quickly yield unreadable code. In mathematics, it isn't such an issue since the exercise is purely academic. However, in production code where time is money, having people try to figure out what some very concise code is doing doesn't seem to make much sense. For a little more verbose code, you get readability and savings.

At what point do you stop compressing software code?

like image 852
4thSpace Avatar asked Jun 04 '09 18:06

4thSpace


3 Answers

I try to reach a level of verbosity where my program statements read like a sentence any programmer could understand. This does mean heavily refactoring my code such that it's all short pieces of a story, so each action would be described in a separate method (an even further level might be to another class).

Meaning I would not reduce my number of characters just because it can be expressed in fewer. That's what code-golf competitions are for.

like image 142
Davy Landman Avatar answered Oct 01 '22 18:10

Davy Landman


My rule is say what you mean. One common way I see people go wrong is "strength reduction." Basically, they replace the concept they are thinking with something that seems to skip steps. Unfortunately, they are leaving concepts out of their code, making it harder to read.

For example, changing

for (int i = 0; i < n; i++)
    foo[i] = ...

to

int * p = foo, q = foo+n;
while ( *p++ = ... < q );

is an example of a strength reduction that seems to save steps, but it leaves out the fact that foo is an array, making it harder to read.

Another common one is using bool instead of an enum.

enum {
    MouseDown,
    MouseUp
};

Having this be

bool IsMouseDown;

leaves out the fact that this is a state machine, making the code harder to maintain.

So my rule of thumb would be, in your implementation, don't dig down to a lower level than the concepts you are trying to express.

like image 30
Drew Hoskins Avatar answered Oct 01 '22 18:10

Drew Hoskins


You can make code smaller by seeing redundancy and eliminating it, or by being clever. Do the former and not the latter.

like image 39
Nosredna Avatar answered Oct 01 '22 19:10

Nosredna