85

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.");
    }
}
Jeff B
  • 838
  • 2
  • 9
  • 14
Ankit
  • 949
  • 4
  • 11
  • 15
  • 67
    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 05 '13 at 08:51
  • I'm curious, what "style" is it they are advocating? – Supr Feb 05 '13 at 10:09
  • 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 05 '13 at 11:21
  • Are you sure there is no redundancy in your code? an example might help – jk. Feb 05 '13 at 13:02
  • 29
    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 05 '13 at 13:14
  • @ratchetfreak unless you have an inline comment. – razpeitia Feb 05 '13 at 16:43
  • 1
    @razpeitia I'm sure I could regex my way out of that ;) `s/\/\/(.*?)\\n/\/\*$1\*\//g`, but don't start with inline comments with `*/` in them :P – ratchet freak Feb 05 '13 at 16:48
  • When you get paid by the line, that's a _bad_ idea... – Cole Tobin Feb 05 '13 at 18:32
  • 1
    Maybe people in your organization are writing really obtuse code which can be rewritten succinctly and clearly in much fewer lines of code. – Kaz Feb 05 '13 at 19:05
  • Seconding Daniel B, some examples would make this much clearer for everyone. – Sean Feb 05 '13 at 19:19
  • 13
    The example you've given is almost a textbook version of the [Introduce Explaining Variable](http://www.refactoring.com/catalog/introduceExplainingVariable.html) 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 06 '13 at 07:11
  • 4
    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. – Reactgular Feb 05 '13 at 15:53
  • 1
    The problem with introducing variables is that you need good names for them. For example I find it surprising that `adult && decade` isn't true for `age==20` since intuitively `adult = age >= 18` for me. And `quarter` for 25 years isn't the clearest name either, prefer `quarterCentury` or something similar. – CodesInChaos Feb 06 '13 at 13:13
  • 1
    You picked the wrong one as answer :P no offense to mattnz, he just wasn't looking between the lines on this one. – Jimmy Hoffa Feb 06 '13 at 14:38
  • I think there was a saying that "Your code should be short, but no shorter" :) – Songo Feb 06 '13 at 15:36
  • 3
    Your two code samples are not equivalent, BTW. The latter (more verbose) code requires that all of those expressions are evaluated, whereas the former takes advantage of lazy evaluation. – Alnitak Apr 06 '13 at 20:20
  • @Alnitak Since the expressions have no side effects the code is equivalent. The compiler may omit evaluation if it can guarantee that that change has no observable effect. I expect that modern c compilers can optimize out such a difference, not sure about the JVM. – CodesInChaos Apr 07 '13 at 18:07
  • 1
    @CodesInChaos lazy evaluation _guarantees_ non-evaluation in the first case. Only optimisation permits it in the latter. – Alnitak Apr 07 '13 at 19:41
  • 1
    The problem is measuring _lines_ when instead you should be measuring _operations_. – Donal Fellows Apr 08 '13 at 08:01
  • possible duplicate of [How do you use blank lines in your code?](http://programmers.stackexchange.com/questions/17305/how-do-you-use-blank-lines-in-your-code) – gnat May 23 '13 at 15:24
  • 1
    In college, the very first thing our OOP teached told us is "Write a program as short as possible, but not shorter" :) – Radu Murzea Dec 02 '13 at 13:38
  • A tangential bit showing how far the care about code terseness and simplicity may take you: [a story about kdb](http://archive.vector.org.uk/art10501320). – 9000 Oct 22 '14 at 21:02
  • 1
    Possible duplicate of [At what point is brevity no longer a virtue?](https://softwareengineering.stackexchange.com/questions/339495/at-what-point-is-brevity-no-longer-a-virtue) – Deduplicator Jul 08 '19 at 12:28

23 Answers23

87

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.

samthebrand
  • 368
  • 2
  • 12
  • 27
Erik Dietrich
  • 5,605
  • 4
  • 30
  • 34
  • 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 05 '13 at 08:13
  • 1
    @mattnz only for sure if they're being pedantic. – Dan Is Fiddling By Firelight Feb 05 '13 at 11:36
  • 3
    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. – Daniel A.A. Pelsmaeker Feb 05 '13 at 15:20
  • 1
    Pedanticness, LoD does not prohibit `BigDecimal.valueOf("2").add(foo).add(bar).toString()`. Just because something has many dots in int does not mean its a LoD violation. See also http://stackoverflow.com/questions/67561/do-fluent-interfaces-violate-the-law-of-demeter –  Feb 05 '13 at 15:33
  • 15
    +1 for the humorously long function call chain, and the sneaky double bracket after `violations()`. – Joe Z. Feb 05 '13 at 15:44
  • 1
    They should ask for code with fewer tokens, not lines. – Kaz Feb 05 '13 at 19:06
  • 5
    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 06 '13 at 14:39
  • The important thing to remember is that while adding a statement does increase the risk due to that statement, it can reduce the overall risk to the _function_ (or module) by making the complexity elsewhere more manageable. Piling all the risk into one hard-to-debug spot isn't a good winning strategy! – Donal Fellows Feb 07 '13 at 10:35
  • Not sure I really agree here.. While *more* statements might imply *more* errors, I firmly believe it should be *character* based. Just because someone manages to write 10 statements in 5 doesn't deem their code *less likely* to be a liability unless it uses *less characters*.. Nonetheless +1 for your().hilarious().func(); – Will Von Ullrich Apr 10 '18 at 18:43
81

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.

mattnz
  • 21,315
  • 5
  • 54
  • 83
  • 35
    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 05 '13 at 13:25
  • 4
    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 05 '13 at 14:14
  • 3
    @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 06 '13 at 21:07
  • 3
    @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 03:48
  • What is important and unimportant can be measured. E.g. by verifying that both metrics measure s.th. different. Well, turns out most OOP metrics are irrelevant if you take LOC into account. Here is a nice blog post with a background paper: http://blog.vivekhaldar.com/post/10669678292/size-is-the-best-predictor-of-code-quality ... Now could s.o. please fix the answer? – treffer Apr 07 '13 at 16:36
  • @treffer: You want me to revoke my answer based on one blog misinterpreting one 14 year old paper, yeh, na...... The problem with the blog is that the paper did not modify existing code (increase or decrease the size) and measure the effect of that on defects. Extrapolating the results of the paper to effectively make a statement "Reduce the number of lines of code in this class will reduce is bug count" is scientifically flawed. That, however, would be an interesting study. – mattnz Apr 07 '13 at 23:30
  • @mattnz This paper was strictly related to "LOC is bullshit, other metrics are more important". Regarding less code will have less bugs I'd have to pull papers regarding bugs / 1000 LOC (a quite common statistic, well researched, and yes, more LOC == more bugs). – treffer Apr 17 '13 at 12:17
  • 6
    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
  • Read "The Goal", by Eliahu Goldratt, who renders clear the problem of measures that do not produce the intended product. Your goal is to clear, correct, easy to understand and maintain code, quickly, that runs effiicently (memory and cpu). LOC is easy to measure, but does not have high correlation to that goal. – ChuckCottrill Oct 24 '14 at 00:19
33

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.

Glorfindel
  • 3,137
  • 6
  • 25
  • 33
Xion
  • 1,235
  • 9
  • 14
21

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.

jhewlett
  • 2,224
  • 1
  • 17
  • 15
13

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.

Joshua Volearix
  • 21
  • 1
  • 1
  • 6
  • You mean `value.prop = boolean ? option1 : option2;` – Christoffer Hammarström Feb 05 '13 at 18:49
  • I do! ...on the 'condensed code' anyway. – Joshua Volearix Feb 05 '13 at 21:12
  • 2
    Your second example is especially good, because it's not only simpler, it also makes it more clear this is an assignment of one of two options, with no side effects. The `if-then-else` obscures this; for example, it's all too easy to assign to a different variable in each branch of the `if` (which may or may not be a mistake, but it's hard to spot). – Andres F. Apr 06 '13 at 20:43
  • I have encountered environments where using the ternary operator was expressly forbidden. Usually they were environments in transition from PL/SQL or similar to Java where the people were afraid of tersity... As to your statement that there is no performance impact from writing more code, there may be depending on what the code is. If you replace an operator with a method call for example there definitely is an impact (and it may be a serious impact). – jwenting Jan 06 '16 at 10:16
8

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."
Adam
  • 103
  • 4
6

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.

GordonM
  • 6,295
  • 1
  • 21
  • 30
3

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 boolean 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").

Eduardo Scoz
  • 286
  • 1
  • 5
  • 2
    The significance of the sweet sixteen (and the age 21) is culture specific. The phrase "sweet sixteen" is more searchable than "age == 16". For __that__ reason, giving names to certain booleans might be useful. I agree with your general sentiment, though: don't waste time explaining self-explanatory code. – Jonas Kölker Jun 03 '13 at 06:29
2

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.

utnapistim
  • 5,285
  • 16
  • 25
1

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.

Vitim.us
  • 111
  • 5
1

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.

zhouji
  • 101
  • 2
1

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

IvoC
  • 129
  • 3
0

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.

James Jensen
  • 348
  • 1
  • 7
0

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).

0

You can improve code by reducing the number of lines, you can also make it worse. Your goal should not be to reduce the length, but to improve the code.

You should avoid code duplication. The same three lines of code, repeated 10 times, is worse than the same three lines put into a function and called ten times. In this case it happily makes the code shorter. If it was just one line, or three lines calling twice, the extra function could still be better, but not shorter. Do what makes the code better, not shorter.

It is better to avoid pointless formatting. Take

If (condition)
{
    Code 
}
Else
{
    Code
}

Is better changed to

If (condition) {
    Code
} else {
    Code
}

because more code fits on the screen. Empty lines can improve readability. Your second example takes more lines but is better because it explains what the tests are for. But I would save three lines by writing the brackets differently.

And the ternary operator ?: or ?? for nil checks in some languages is better because it is shorter.

gnasher729
  • 42,090
  • 4
  • 59
  • 119
0

In my opinion, "clarity is key," not metrics.

Kindly remember that any source-code that you write will in due time be viewed by a great many people, long after you are gone ... ("too bad about that bread truck, pal ...") ... and often under conditions of great stress.

These days, "optimizing compilers are very good, and hardware is very fast." It is no longer necessary to "bum code" as all of us once had to do. But the need for clarity, and simplicity, has not changed and never will. Because these are really human factors now.

Someone who has never seen your code before now, and who knows nor cares nothing about you, needs to be able to immediately understand what the code is saying, and to be correct. In so doing, (s)he may also very-much rely upon your comments, which I hope that you thought to include at the time to clarify your thoughts.

A great deal of "somebody else's money" can now depend on this.

Mike Robinson
  • 1,765
  • 4
  • 10
0

Lines of code in a program are as important as lines of text in a novel.

Novel writers can clearly suffer from vices such as being overly wordy or being too terse, and the length of any text can clearly be mismatched with the desire of the reader. So we do not completely deny the importance of line count.

The problem is when someone begins to measure the quality of a program (or the productivity of a programmer) by the lines of code.

Nobody intelligent would judge the quality of unread English text by length alone, knowing that both sense and gibberish can come in short and long forms.

What's more, any attempt at "doctoring" a novel by simple and unskilled transformations designed primarily to change the number of lines, almost invariably reduces quality.

That is, even when the main quality problem with an existing text is its length, actually altering the length in any naive way, does more damage to other aspects of its quality, than the improvement gained on length.

What exactly programmers do is an under-studied question in my view. The most common description is that it involves writing code, but I'd say I have always spent a relatively minor amount of time writing code - in fact reading and talking in English, and thinking, would easily exceed the time spent writing code. It is performance of these other activities that contributes to the quality of any code that gets written.

So in my view, the relative importance of measuring lines of code is actually quite low - too low to ever deserve any significant attention from staff who are being paid to do useful work.

Steve
  • 6,998
  • 1
  • 14
  • 24
-1

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. :)

johnfound
  • 318
  • 1
  • 11
-1

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.

-2

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.

MatthieuW
  • 101
  • 2
  • 5
    As far as I know, comments do not count towards the LOC. – mhr Feb 05 '13 at 11:08
  • 1
    It doesn't count or it counts, according to definition you use. – MatthieuW Feb 05 '13 at 12:50
  • 1
    Comments are comments. They're not code. Therefore they don't apply to LOC counts. While self-documenting code is better than well-commented code, removing comments from code that's less obvious isn't helpful to anybody. – GordonM Apr 07 '13 at 07:30
-2

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.

Maximus Minimus
  • 1,498
  • 10
  • 11
  • 1
    _By definition_, if a task absolutely requires N lines of code to accomplish (which is something hard to determine in the first place), then it cannot be done in less than N lines. So your 10,000-line task cannot be done in 2,000, period. I guess the OP is talking about the cases where there is some leeway, i.e. "the requirement can be fully accomplished either way, so which one is better?" – Andres F. Apr 06 '13 at 20:47
-3

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.

Infin8Loop
  • 1,459
  • 2
  • 11
  • 16
  • 1
    Why all the downvotes? – Marko Feb 06 '13 at 22:33
  • Yes, why was a perfectly sensible answer downvoted? Why were other perfectly sensible answers, all of which challenged the idea that reduced lines of code is an end in itself, also downvoted? – Maximus Minimus Feb 07 '13 at 00:06
  • 1
    @mh01 I'm guessing because most of this one is wrong? Specifically, `in most cases, it is more important to increase the number of lines of code by breaking out complex operations into more readable steps` is not my experience at all. Complex code can more often be made more readable and less buggy by making it smaller and simpler, because it got to be complex from being written by someone who was new to the language/new to the problem/not sure what they were doing. – Izkata Apr 07 '13 at 18:19
-5

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
Balog Pal
  • 1,711
  • 9
  • 16
  • 5
    -1: Wow! I think you need to reduce the LOC in your answer! It hurts my eyes to read it! – Jim G. Feb 06 '13 at 07: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 06 '13 at 02:36
  • It was fault of the autoformatter, inserting a single blank line before the list cured the situatuion – Balog Pal Jun 02 '13 at 01:35