views:

669

answers:

18

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?

+19  A: 

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.

Davy Landman
+1: Code has meaning. Software is knowledge capture. Software is a composition the way a proof depends on lemmas and axioms.
S.Lott
There's also something to be said of debugging. Shorter code can eliminate areas you'd like to place a breakpoint, which is a disadvantage.
4thSpace
If you are not building an API, don't worry about long function names. Have short (lines of code) functions with long, descriptive names and you'd be amazed at how "self-documenting" your code becomes. (If you're building an API, or anything that's not a "worker function", you need to also be respectful for people who have to type in your function name)
Matt
+12  A: 

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

Nosredna
A: 

There's no exact line that can be drawn to distinguish between code that is glib and code that is flowery. Use your best judgment. Have others look at your code and see how easily they can understand it. But remember, correctness is the number 1 goal.

Scottie T
+1  A: 

There needs to be a balance between short sweet source code and performance. If it is nice source and runs the fastest, then good, but for the sake of nice source it runs like a dog, then bad.

KM
A: 

The need for small code footprints is a throwback from the days of assembly language and the first slightly high level languages... there small code footprints where a real and pressing need. These days though, its not so much of a necessity.

That said, I hate verbose code. Where I work, we write code that reads as much as possible like a natural language, without any extra grammar or words. And we don't abbreviate anything unless its a very common abbreviation.

Company.get_by_name("ABC") 
makeHeaderTable()

is about as terse as we go.

Sudhir Jonathan
A: 

In general, I make things obvious and easy to work with. If concision/shortness serves me in that end, all the better. Often short answers are the clearest, so shortness is a byproduct of obvious.

Paul Nathan
Sorry but I completely disagree, as discussed in the OP. Concise code "can" be easier to understand but is often more difficult.
4thSpace
"Concise" means the removal of all that is superfluous. So, to me, concise implies clarity, as the only thing that's taken away is distracting excess.
Nosredna
My goal is obviousness. Often, obvious code is concise and short.
Paul Nathan
A: 

There are a couple points to my mind that determine when to stop optimizing:

  • Worth of spending time performing optimizations. If you have people spending weeks and not finding anything, are there better uses of those resources?

  • What is the order of optimization priority. There are a few different factors that one could care about when it comes to code: Execution time, execution space(both running and just the compiled code), scalability, stability, how many features are implemented, etc. Part of this is the trade off of time and space, but it can also be where does some code go, e.g. can middleware execute ad hoc SQL commands or should those be routed through stored procedures to improve performance?

I think the main point is that there is a moderation that most good solutions will have.

JB King
+12  A: 

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.

Drew Hoskins
I think that's a great answer and those are great examples.
Nosredna
A: 

You can make your code as short or compact as you like as long as you comment it. This way your code can be optimized but still make sence. I tend to stay in the middle somewhere with descriptive variables and methods and sparce comments if it is still unclear.

Scott
Comments rot fast. I've spent too many days reading comments that maybe described how the code worked once. Clear code doesn't rot.
Alun Harford
It goes both ways. I've read through pages of code only to find out that it was no longer used and was just gathering dust as something they were just afraid to remove. The code can only tell you so much and comments should be updated just like code.
Scott
How did a negative rated answer get selected as the answer? 4thSpace, the community obviously doesn't agree with you... Scott's answer isn't the best answer for your question...
Frank V
This approach leads to all sorts of unreadable code. You should be striving to write code that doesn't need comments at all, rather than making obfuscated nonsense with comments to explain it.
Xiong Chiamiov
+6  A: 

One way to find a balance is to seek for readability and not concise-ness. Programmers are constantly scanning code visually to see what is being done, and so the code should as much as possible flow nicely.

If the programmer is scanning code and hits a section that is hard to understand, or takes some effort to visually parse and understand, it is a bad thing. Using common well understood constructs is important, stay away from the vague and infrequently used unless necessary.

Humans are not compilers. Compilers can eat the stuff and keep moving on. Obscure code is not mentally consumed by humans as quickly as clearly understood code.

At times it is very hard to produce readable code in a complicated algorithm, but for the most part, human readability is what we should look for, and not cleverness. I don't think length of code is really a measure of clearness either, because sometimes a more verbose method is more readable than a concise method, and sometimes a concise method is more readable than a long one.

Also, comments should only supplement, and should not describe your code, your code should describe itself. If you have to comment a line because it isn't obvious what is done, that is bad. It takes longer for most experienced programmers to read an English explanation than it does to read the code itself. I think the book Code Complete hammers this one home.

Kekoa
A: 

Code should be short, concrete, and concentrated. You can always explain your ideas with many words in the comments.

Kensai
I'll disagree with you completely as well. Let the code explain itself. You aren't being as clever as you think.
4thSpace
How do you know how clever I am? There are many opinions regarding optimal coding practices. My suggestiong does not overload the compiler and takes advantage of the respective language's capabilities. Afterall, imo, coding is like writing math formulas. You can be as verbose as you like in your comments, afterall the compiler ignores them.
Kensai
+1  A: 

Strive to refactor until the code itself reads well. You'll discover your own mistakes in the process, the code will be easier to grok for the "next guy", and you won't be burdened by maintaining (and later forgetting to change) in comments what you're already expressed in code.

When that fails... sure, leave me a comment.

And don't tell me "what" in the comment (that's what the code is for), tell me "why".

lance
A: 

The code optimizations have little to do with the coding style. The fact that the file contains x spaces or new lines less than at the beginning does not make it better or faster, at least at the execution stage - you format the code with white characters that are unsually ignored by the compiler. It even makes the code worse, because it becomes unreadable for the other programmers and yourself.

It is much more important for the code to be short and clean in its logical structure, such as testing conditions, control flow, assumptions, error handling or the overall programming interface. Of course, I would also include here smart and useful comments + the documentation.

Zyx
A: 

There is not necessarily a correlation between concise code and performance. This is a myth. In mature languages like C/C++ the compilers are capable of optimizing the code very effectively. There is cause need in such languages to assume that the more concise code is the better performing code. Newer, less performance-optimized languages like Ruby lack the compiler optimization features of C/C++ compilers, but there is still little reason to believe that concise code is better performing. The reality is that we never know how well code will perform in production until it gets into production and is profiled. Simple, innocuous, functions can be huge performance bottlenecks if called from enough locations within the code. In highly concurrent systems the biggest bottlenecks are generally caused by poor concurrency algorithms or excessive locking. These issues are rarely solved by writing "concise" code.

The bottom line is this: Code that performs poorly can always be refactored once profiling determines it is the bottleneck. Code can only be effectively refactored if it is easy to understand. Code that is written to be "concise" or "clever" is often more difficult to refactor and maintain.

Write your code for human readability then refactor for performance when necessary.

My two cents...

Jerry
+6  A: 

Here's a good article by Steve McConnell - Best Practices http://www.stevemcconnell.com/ieeesoftware/bp06.htm

I think short/concise are two results from well written code. There are many aspects to make code good and many results from well written code, realize the two are different. You don't plan for a small foot print, you plan for a function that is concise and does a single thing extremely well - this SHOULD lead to a small foot print (but may not). Here's a short list of what I would focus on when writing code:

  • single focused functions - a function should do only one thing, a simple delivery, multi featured functions are buggy and not easily reusable
  • loosely coupled - don't reach out from inside one function to global data and don't rely heavily on other functions
  • precise naming - use meaningful precise variable names, cryptic names are just that
  • keep the code simple and not complex - don't over use language specific technical wow's, good for impressing others, difficult to easily understand and maintain - if you do add something 'special' comment it so at least people can appreciate it prior to cursing you out
  • evenly comment - to many comments will be ignored and outdated to few have no meaning
  • formatting - take pride in how the code looks, properly indented code helps
  • work with the mind of a code maintenance person - think what it would be like to maintain the code you're writting
  • do be afraid or to lazy to refactor - nothing is perfect the first time, clean up your own mess
meade
These are good guidelines. However, when you come across someone using something because it's cool and you ask them to rewrite so the code is more readable, you are in an endless battle.
4thSpace
just ask them to comment it - so they can show how smart they are to everyone else
meade
+1 I think this is the best answer here. Thanks.
Frank V
+1  A: 

As opposed to long/rambling? Sure!

But it gets to the point where it's so short and so concise that it's hard to understand, then you've gone too far.

John at CashCommons
"...then you've gone too far." It's to subjective to really know.
4thSpace
The whole question is subjective, isn't it? If you're looking for a rule of thumb, I'm not sure I can give you one, but whether you can understand your own code a while after you've written it, or whether your colleagues can or not, is a good sniff test to see if you've compressed it too much. It all depends on how hard you want to work figuring out what you wrote, I guess.
John at CashCommons
A: 

Yes. Always.

Mark Ransom
For those of you missing a humor gene - this is a joke! That's why I made it Wiki.
Mark Ransom
+3  A: 

As far as object names go, the thinking on this has gone through an evolution with the introduction of new programming languages.

If you take the "curly brace" languages, for instance, starting with C, brevity was considered the soul of wit. So, you would have a variable to hold a loan value named "lv", for instance. The idea was that you were typing a lot of code, so keep the keystrokes to a minimum.

Then along came the Microsoft-sanctioned "Hungarian notation", where the first letters of a variable name were meant to indicate its underlying type. One might use "fLV", or some such, to indicate that the loan value was represented by a float variable.

With Java, and then C#, the paradigm has become one of clarity. A good name for a loan value variable would be "loanValue". I believe part of the reason for this is the command-completion feature in most modern editors. Since its not necessary to type an entire name anymore, you might as well use as many characters as is needed to be descriptive.

This is a good trend. Code needs to be intelligible. Comments are often added as an afterthought, if at all. They are also not updated as code is updated, so they become out of date. Descriptive, well-chosen, variable names are the first, best and easiest way to let others know what you were coding about.

I had a computer science professor who said "As engineers, we are constantly creating types of things that never existed before. The names that we give them will stick, so we should be careful to name things meaningfully."

Buggieboy

related questions