How important is it to reduce the number of lines in code?

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.");
    }
}

23

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.

9

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.

9

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.

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.

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.

4

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

1

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.

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

1

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.

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.

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.

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

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.

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

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.

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.

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.

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

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.

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.

3

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.

1

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.

3

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

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật