Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am a Software developer who works on J2SE (core java).
Often during our code reviews we are asked to reduce the number of lines in our code.

It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines.

What do you think is the right way of doing things?
If LOC (lines of code) is a small number, how does it affect the code? If LOC is a larger number, how does it affect the code?

example from the website : "javaranch" -

public static void happyBirthday(int age)
{  
    if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))        
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}

VS

public static void happyBirthday(int age)
{

    boolean sweet_sixteen = (age == 16);
    boolean majority = (age == 21);
    boolean adult = (age > 21);
    boolean decade = (age % 10) == 0;
    boolean quarter = (age % 25) == 0;

    if (sweet_sixteen || majority || (adult && (decade || quarter)))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
share|improve this question
53  
I can transform any java file to a single line of code (s/\n/ /g) it doesn't mean it will be even remotely readable –  ratchet freak Feb 5 '13 at 8:51
6  
Does your company use LOC to measure productivity , so they're trying to prevent you from 'gaming the system' with their coding standards? –  JeffO Feb 5 '13 at 11:21
26  
It would really help if you could provide a short example of each style (not cherry picked), so everyone's clear on what we're talking about. There are extremes in either direction; and the answer is going to be highly dependent on your context. –  Daniel B Feb 5 '13 at 13:14
3  
Ever clean your room, then your mother comes in and says "that's not clean" and points out 10 things you didn't put away. That's basically what they're telling you in the code review. –  Mathew Foscarini Feb 5 '13 at 15:53
11  
The example you've given is almost a textbook version of the Introduce Explaining Variable refactoring, which typically increases readability and intent (which is a good thing). Some would argue that you should refactor the variables further into short, one-line functions, but that's taking it to an extreme; I'd say your version is preferred over the short one recommended by the review. –  Daniel B Feb 6 '13 at 7:11

20 Answers 20

up vote 65 down vote accepted

The problem with measurements, no matter how well intended they are, is the very act of measuring the item makes it important, and the corollary, the act of not measuring an item makes it unimportant. It is absolutely essential to measure what is important, and not measure what is unimportant.

Measuring SLOC (Which is effectively what your reviews are doing), makes SLOC important.... Is SLOC important? - absolutely not, never has been (Outside Obfuscated programming contests), never will be in a commercial organization.

Ask yourself one simple question - how does "Reduce the SLOC of this routine" make anyones code better. What is probably happening in this case is SLOC is being used as a naive way to measure complexity. What you must avoid at all costs is counting the easy to count beans - objective measures such as SLOC, instead of counting the important, but hard to count ones - e.g. Readability, complexity etc.

share|improve this answer
31  
While OP's description of the review makes it sound a bit pointless, I'd say that lines of code are often related to the harder measures that you mention. Long functions are often less readable, and also often have higher cyclomatic complexity. So it really comes down to whether the review is actually recommending breaking up / shortening code that would benefit from this, or if it's just recommending inlining multiple, legitimate lines. –  Daniel B Feb 5 '13 at 13:25
3  
I would say that the reason it's important to reduce the number of lines of code is to be able to view more of a function on a single page. The easier it is to view a method or class without needing to scroll, the easier it is to maintain the context in your head. –  CLandry Feb 5 '13 at 14:14
2  
@DanielB Long functions are often harder to wrap one's head around not because they are long; but, because they attempt to do many things at once. For example, they generally start with validation of inputs, then some processing, followed by a check for alternate processing, followed by another check to see if something unrelated needs updating, followed by an inlined routine that has nothing to do with the main action (like date logic that checks for month overrun and adjusts) and so on. By the time you get to the end, you can't remember what the class's on responsibility was. –  Edwin Buck Feb 6 '13 at 21:07
1  
@CLandry : Maintaining context by making it fit on one page is a very bad reason to reduce SLOC. Surely it is easier to maintain context if the code is well laid out and easier to read. - Whats a "page" 2500 or 1000 pixels? I have a 2*30" Monitors in portrait, yet sometimes develop on a laptop. –  mattnz Feb 11 '13 at 3:48
2  
Studies that show (ref a)LOC===Bugs are a dime a dozen. Its a well known and accepted fact. What has not been shown (to my knowledge) is (ref b)"Reduce LOC in a code base === Reduce Bugs in that code base". Extrapolating (ref a) to claim (ref b) is unscientific. Publishing a paper that proves or disproves the relationship would be. –  mattnz Apr 17 '13 at 22:39

I agree with your code reviewers, but with an asterisk. Each statement that you write in your code is a technical liability -- it's a potential failure point. If you write a method with 10 statements and your coworker writes one that achieves the same functionality with 5 statements, his is likely to be 'better' as measured by likelihood of issues (there are twice as many places your code can be wrong, overly complex, or problematic).

Here's the asterisk, though. It's not about the actual number of lines of code in the idea because you can reduce the number of lines with something like:

void someMethod() {   
 someobject.doSomething(someSingleton.getInstance().with().a().lot().of().law().of().demeter().violations()).and().if().that().werent().enough().theres().more();
}

This is one line of code, but it's a place where an amazing amount of things can go wrong. So I'd say focus on doing the most with the fewest statements -- write as much code as you need to get things done and no more. At least, I think that's what your code reviewers are driving at.

Personally, I think there's a balance to be struck. As I said, each statement that you write is a liability, but if pulling out a local variable with a descriptive name makes your method a lot clearer and more readable, then there's a case to be made for that too. I think you can easily get into situations where people are quibbling over relatively minor aesthetic differences, but on the whole, I think your reviewers have the right idea -- favor minimizing the number of things that can go wrong.

share|improve this answer
4  
Agree - reducing the number of statement can be useful, to a limit, however, if the code review is wanting to reduce the number of statements, wouldn't they just say "lesser number of statements" rather than "lesser number of lines of code". –  mattnz Feb 5 '13 at 8:13
1  
@mattnz only for sure if they're being pedantic. –  Dan Neely Feb 5 '13 at 11:36
1  
In my experience someone that can write the same algorithm in less statements will a) use things that are not very common, or not very well understood, and b) introduce more edge-cases that need unit tests and may introduce bugs. This of course assumes that both programmers are approximately equally capable. –  Virtlink Feb 5 '13 at 15:20
9  
+1 for the humorously long function call chain, and the sneaky double bracket after violations(). –  Joe Z. Feb 5 '13 at 15:44
3  
100% +1, so many people don't understand the consequences of every additional bit of code they add to a code base, this is something people really need to know about. –  Jimmy Hoffa Feb 6 '13 at 14:39

Taking the reviewers' advice literally won't do any good, because the obvious direct result is promoting terse one-liners (line length limit notwithstanding). I believe the lesson to be learnt here, though, is to make your code do fewer things.

In other words, this is a call for simplicity. It is quite popular claim that code is a liability, not asset, so reducing its amount while preserving the functionality is a noble effort. This can be achieved by a direct, more down-to-earth approach that addresses the problem directly and prefers concise solutions.

Like Ken Thompson once said: One of my most productive days was throwing away 1000 lines of code.

share|improve this answer

I tend to agree with your position of "having clarity in code even if it means increasing the number of lines."

I've seen too many one-liners that are fairly terse, but it's not immediately apparent what they are doing. Readability is king since other developers will have to maintain your code.

I would argue that a better thing to aim for is short methods. Not short for the sake of few lines of code, but short because they do a single thing.

share|improve this answer

I currently work as a senior applications developer and project business analyst for a major company and never has the line count of my development been a center of interest. However, I believe that the more condensed a code can be, the better, BUT not at the cost of being able to quickly analyze and correct (or add on to) it. To me, when you are in charge of business critical application that MUST have a vast level of scalability and capable of on the fly alterations in a non-stop changing environment, concise, easy to read code is one of the most important elements in development. To the credit of Erik Dietrich's reply, this :

void someMethod() {   
someobject.doSomething(someSingleton.getInstance().with().a().lot().of().law().of().demeter().violations()).and().if().that().werent().enough().theres().more();
}

would be completely unacceptable to me, however, I found altering all the companies existing code from :

if (boolean == true){
value.prop = option1;
}
else{
value.prop = option2;
}

to:

value.prop =  boolean ? option1 : option2;

was an excellent code condensing choice that doesn't sacrifice readability.

As far as how it effects the code? I have never noticed a performance increase or decrease from, let's say, 100 lines of code. Simple fact is that it's more the process you utilize to arrive at the final product than the number of lines it takes to arrive there. I have seen some processes written very condensed, however inefficient, perform differently than longer codes with better code flow.

share|improve this answer

IMO, it's a bad idea to measure code effectiveness by a trivial LOC count. There's a lot more to what makes properly engineered and effective code.

In my experience, effective code:

  • doesn't break any of the SOLID principles
  • is readable and self-explanatory
  • passes Albert Einstein's test of simplicity: "Everything should be made as simple as possible, but not simpler."
share|improve this answer
1  
+1 for the Einstein quote. –  Justsalt Feb 6 '13 at 21:03

There's a lot of answers here that address the technical pros and cons of keeping LOC down and whether or not it's a meaningful quality software metric. That's not what this question is about. What it's about is how to deal with management that insists on a naive dogmatic adherence to a particular coding rule of thumb.

Sadly, it's fairly common for people to latch onto things that are good advice when used in the proper context and applied pragmatically, take them out of that context and apply them dogmatically while failing to appreciate the issues the advice exists to mitigate in the first place.

The intent of advice regarding keeping LOC down is to avoid the creation of methods that try to do too much in one go, and to discourage the creation of "god classes", which know too much about aspects of a design that aren't their direct responsibility and which all other classes in the system are dependant on. Another advantage of shorter code is that it's more readable, though as you've pointed out, you can overdo it to the point where readability actually starts to suffer.

There are obvious advantages to low LOC counts (small methods fit into your head more easily than big ones, fewer things in the code means fewer things to go wrong, etc), but it is also subject to the law of diminishing returns. Refactoring a 150 line method into a number of 20 line methods is a much bigger win than refactoring a 10 line method into a 7 line method.

When such refactoring comes at the expense of some other facet of good software design (such as readability) then you have reached a point where you can justify not doing it. Removing variables that give context to what the code means and replacing them with literals that don't is a very very bad thing to do. Good code has almost no literals in it. However, these variables (and named constants) are lines of code that don't directly contribute to the program and so if LOC is being worshipped as some kind of god then such clarification lines are in great peril of being pruned for a quick win and some misguided praise from management.

I believe you're smart enough to realise this, in fact that's pretty much the thrust of your original question. The problem isn't your understanding of when code reduction is good and when it's not, the problem is dogmatism in applying what is normally a reasonable practice indiscriminately.

I would recommend taking the time to chat with your management, explaining your position and why you feel that what you're being asked to do harms the code rather than helps it. Try to avoid being confrontational, but do try to remain rational and calm during such a discussion. It's important that your management understands that programming is a pragmatic activity, and best practice advice is only useful if it's applied in a pragmatic way. Best practice is written in a book, not carved in stone, and when it conflicts (short code versus readable code) then it's up to the programmer to apply their judgement as to which best practice to follow. Hopefully they are reasonable people who appreciate input such as this.

You also need to be a bit brave, because if you're being pressured to reduce LOC where you think it's unnecessary or inappropriate then it's only natural that you'd make the change anyway for the sake of a quiet life. You need to resist doing this, and you have to "own" that decision. In a situation where management are reasonable you shouldn't have to adhere to their guidelines exactly, but you should be able to justify any circumstances where you don't.

Sadly, people can be irrational, especially when it comes to people lower on the pecking order questioning their decisions and the rules they've imposed on you. They may choose not to be reasonable. You need to be prepared for that too. If you can demonstrate cases where the LOC best practice comes into direct conflict with other best practice and why that's hurting the product, and if you can do it in portions of the code base for which they had little or no personal involvement (so it doesn't seem like a personal attack on their work or work they supervised) then this may help bolster your argument. Again, you have to be prepared to justify yourself in a calm, rational way and be able to "own" the arguments you're making.

Provided your management are reasonable people then they must appreciate that what you're saying has merit if you can provide evidence to back your claims up.

share|improve this answer

I think you should indeed strive to have functions with a small number of SLOC.

If LOC (lines of code) is a small number, how does it effect the code and if LOC is a larger number, how does it effect the code ?

Ideally, it should be easier to understand 8 lines of code at a glance than it should be to understand 30.

That doesn't mean that 30 LOC compressed in 8 lines will be easier to understand.

What do you think is the right way of doing things.

Normally in a function, I try to group it by levels of abstraction ("IO code here", "validation here", "computation here" and so on).

Then, I split it up in blocks, separated by a blank line. If the code is more than around ten lines, I extract each block into a different function (I do that anyway for code that appears more than once). I've heard an argument about breaking performance this way (unnecessary function calls) but in practice I've never had a performance bottleneck caused by this.

That said, I've had functions with this extraction done, and after it the function was ~40 lines long (C code). If the code is as grouped as possible, I don't see a problem with longer functions.

share|improve this answer

I think fewer lines of code = more readable code

But of course, there is some limit, when you start to minify/obscure your code just to get fewer lines.

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

This is minification the logic remains the same, just less readable. This shouldn't be done by humans, this minification is done by machine to be read by a machine.

function zP(e,t){var n=e+"";while(n.length<t){n="0"+n}return n}

If you can remove some piece of code, and the algorithm still doing what it is supposed to do, ok go ahead. Just don't minify your code, there are better tools for doing that.

share|improve this answer

I don't think fewer lines of code == more readable code. However, the reality, which is very different from the theory, is that the code with large number of lines are often written without a proper design. Consequently, requirement of fewer lines MAY force some programmers to come up with better design if they are capable. The twist is that many programmers are not, then the requirement does not help much.

share|improve this answer

I wouldn't see the number of lines as an issue in normal circumstances, but it can point to issues. If some-one shows you a class with 1000 lines of code, then something must be wrong with the way the class was done or designed.

Your example does point to a case where a larger number of lines of code makes sense. But that is that example. Every day I see examples where the number of lines is attached to lack of planning

share|improve this answer

I think it's more important to focus on clean, auto-documented code, than LOC. I don't really like your example, though, because it explains what the code is doing, without saying why. For example, this:

boolean sweet_sixteen = (age == 16);

is pretty redundant. Anybody reading "age == 16" knows that. I would rather write the code like this:

public static void companyShouldThrowABigParty(int age) {
    return (age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))); 
}

public static void happyBirthday(int age)
{  
    System.out.println(companyShouldThrowABigParty(age) ? "Super special party, this year!" : "One year older. Again.");
}

The logic about deciding when to throw the party is separate from the System.out, can be tested ,and it is easy to understand. More importantly, though, somebody reading the code can understand the reason it was written that way ("company wants to throw a big party for some of the people").

share|improve this answer

LOC is a way more useful metric at the beginning of a project than during actual implementation, I think. Knowing the LOC per function point allows you to estimate project effort, and from that how long the project will take and the optimal number of developers.

It can also influence design and language choice: reducing function points or switching to a language with a lower LOC/FP should reduce project effort, all else being equal.

share|improve this answer

Lines of code themselves are not very important. One way to look at it is to compare it with prose. The first realization is that an important property of both code and prose (assuming correctness) is readability. Readability (and understandability) helps with other properties such as maintainability and correctness.

There are advantages to being able to fit a function in a small number of lines. But having text without paragraphs reduces its legibility. Using difficult concepts, difficult(rare) words and complex ways of expression does generally reduce the amount of words needed to express an idea, but at the same time moves the reading level of the text from secondary school level up to professional academics (in the case of prose).

In general it is helpful to add abstractions in your code and use helpers etc. but again, those abstractions can become too numerous. What can also happen is that the move the complexity to another part of the code. Sometimes, like when you as an expert are designing a framework/library for use by junior programmers (or students), it is a good idea to do this. But don't expect the juniors to be able to make sense of how your code works, just make it very hard for them to use it incorrectly.

When writing code, especially do not shy away from adding empty lines in your code. They function as paragraphs and help you separate different parts of your function (even if they should not be put into helpers yet).

share|improve this answer

To be perfectly honest, I don't give a hoot about LOC measurement. Sure, it is nice for a function or procedure to be as short as possible, but I take readable code over short any time of day.

share|improve this answer

The great problem with every formal method of code evaluation is that it will surely fail on some code. This is because the programming is a kind of art and as such, there can not exists clear standards for evaluation. Of course there are different kind of arts - mass production of paintings also exists, and maybe in this business is important how many paint is spend on one painting. :)

share|improve this answer

I agree that always requiring reduction of LOC would lead to a code difficult to read.

However, maybe your coding style is too verbose and your reviewer thinks a more concise way is better. For example a comment that only explains one statement that is fairly obvious thanks to clear choice of variable names is useless.

share|improve this answer
4  
As far as I know, comments do not count towards the LOC. –  mri Feb 5 '13 at 11:08
1  
It doesn't count or it counts, according to definition you use. –  MatthieuW Feb 5 '13 at 12:50

How important is it to reduce the number of lines in code? In most cases, not at all. In fact, in most cases, it is more important to increase the number of lines of code by breaking out complex operations into more readable steps, and commenting each step as well as adding comments in general to make the code more readable and extensible by other developers who come after you.

share|improve this answer
1  
Why all the downvotes? –  Marko Feb 6 '13 at 22:33

There's only one thing that lines of code measures and that's the number of lines of code you have. Everything else is hot air, speculation and prejudice.

There are a lot of great examples in the other answers of how having fewer lines of code can make something worse, not better, but one core point seems to have been missed, and that's: how many lines do you actually need to do this job?

If accomplishing your task needs 10 lines of code, so be it, you do it in 10 lines. If accomplishing it needs 10,000 lines, then likewise so be it, you do it in 10,000 lines. The cult of "fewer lines of code" will not make the latter example any better if you do it in 1,000 or 2,000 or whatever. The job needed 10,000 lines and those 10,000 lines may include layers of validation, error checking, security, etc that would be missed if you did it in fewer.

Edit

Since this has garnered a few downvotes I think I need to be more specific about what I'm saying here. The first thing anyone should do is read this - the point that I'm asking you to take away from it is that the high-level code you write may bear little or no resemblance to the machine code that actually gets executed. The relevance of this point is that a focus on high-level code without an understanding of what actually goes on underneath is misguided.

Now consider the following:

  • It's possible to write really bad, slow code with just a single line - note the comment on the ternary operator at the end of the link I provided.

  • If a line of code makes an API call (or other call into an external library) then you have by definition little in the way of direct control over what gets executed or how efficient it is.

  • Error checking, cleanup, etc all add extra lines of code and I'm quite certain that even the most ardent fan of fewer lines of code wouldn't argue against those.

So - lines of code is a broken metric. Fewer lines of code doesn't guarantee extra performance - that API or library call is one line and can be outside of your control. Fewer lines of code doesn't guarantee extra robustness - error checking and cleanup will always require extra lines. Fewer lines of code doesn't even guarantee extra readability or maintainability - you only need to look at the IOCCC to know that.

So what does fewer lines of code guarantee? Fewer lines of code, that's all.

It's deeply wrong to focus on doing the same job in 2,000 lines versus in 10,000. Instead focus on code that works, that is robust, that performs within accepted tolerances, and that is easier to read and maintain going forward. Sometimes that means you can do it in a low LoC count, sometimes it means you have to do it in a higher LoC count, but the LoC count should not be what's important here.

share|improve this answer

In earlier period it was assumed that if the number of lines of code that is loc is large then the code is effective and it accomplishes all the tasks that it is used to do but it was realized after some time that less is the loc more it has the efficiency as the cost incurred by the system in executing the code is very less.Thus for the betterment of the system loc was to be made less.Since then it was assumed that the loc shoul be less.To reduce it the following factors should be taken into account.

  1. Make a flowchart of your problem
  2. Try to use less number of loops as you can
  3. The function calls should not be much
  4. New data structures like TRIE should be used in the case where stack or queue is used for storing the relevant information.
  5. And do try to solve the problem with a realistic approach rather than imaginative one where you are storing a huge amount of numbers in a very large array and then trying to access it through the array.]
  6. Use as many macros as possible Further the approach to use also depend upon the problem.If it is really complex then sometimes using the simple approach is also equivalent to the complex one
share|improve this answer
5  
-1: Wow! I think you need to reduce the LOC in your answer! It hurts my eyes to read it! –  Jim G. Feb 6 '13 at 7:40
1  
@JimG.: I agree that the answer hurts my eyes, but think this is best resolved by increasing LOC (e.g., by using a separate line for each numbered item) . –  Brian Apr 6 '13 at 2:36

protected by maple_shaft Feb 6 '13 at 10:51

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.