What are the pros and cons of the maximum possible logic in the minimum (single-line) code fragment?

That's cool?

Single-line IMOs reduce readability and make debugging / understanding difficult.

+4
source share
15 answers

Increase code comprehensibility.

Sometimes this means laying out (simple, understandable) expressions in one line to get more code in a given amount of screen real estate (i.e., source code editor).

In other cases, this means taking small steps to make obvious what the code means.

Single line players should be a side effect, not a goal (and what should be avoided).

+13
source

If there is an easy way to express something in one line of code, that's great. If this is just a case of filling out multiple expressions on one line, this is not so good.

To explain what I mean, LINQ allows you to express fairly complex transformations in relative simplicity. This is great - but I would not try to fine-tune the huge LINQ expression to one line. For instance:

var query = from person in employees where person.Salary > 10000m orderby person.Name select new { person.Name, person.Deparment }; 

more read than:

 var query = from person in employees where person.Salary > 10000m orderby person.Name select new { person.Name, person.Deparment }; 

It is also more readable than performing all filtering, organizing, and projecting manually. This is a nice sweet spot.

Trying to be smart is rarely a good idea, but if you can put it simply and concisely, that's good.

+11
source

Single liners, when used correctly, clearly convey your intentions and simplify understanding of the structure of your code.

A python example is a list of concepts:

 new_lst = [i for i in lst if some_condition] 

instead:

 new_lst = [] for i in lst: if some_condition: new_lst.append(i) 

This is a commonly used idiom that makes your code more readable and compact. Thus, the best of both worlds can be achieved in certain cases.

+6
source

Oneliners may be useful in some situations.

 int value = bool ? 1 : 0; 

But for the most part, they make the code harder to follow. I think that you only need to put things on one line when it is easy to understand, the intention is clear, and this will not affect debugging.

+4
source

This is subjective by definition, and due to the uncertainty of the question, you are likely to get answers all over the map. Do you mean one physical line or logical line? EG, you say:

 int x = BigHonkinClassName.GetInstance().MyObjectProperty.PropertyX.IntValue.This.That.TheOther; 

or

 int x = BigHonkinClassName.GetInstance(). MyObjectProperty.PropertyX.IntValue. This.That.TheOther; 

Single liners, for me, are the question of "what is right." In the above case, I would probably break this down to both physical and logical lines, getting an instance of BigHonkinClassName, and then pulling the full path to. But that's just me. Other people will not agree. (And there is a place for this. As I said, subjective.)

With regard to readability, keep in mind that for many languages ​​even “single-line” can be broken down into several lines. If you have a long set of conditions for a conditional ternary operator ( ? : , For example, you may need to split it into several physical lines for readability:

 int x = (/* some long condition */) ? /* some long method/property name returning an int */ : /* some long method/property name returning an int */ ; 

At the end of the day, the answer is always: "It depends." Some structures (for example, many DAL, EG SubSonic generators) almost require indecently long single-line lines to do any real work. Other times, breaking it down into several lines, are highly preferred.

Based on specific examples, the community can provide more practical advice.

In general, I definitely don't think you should “squeeze” a bunch of code into one physical line. This doesn’t just hurt readability, it brings pleasure to someone who is completely disdainful of a service programmer. As I used to educate my students: always code for the maintenance programmer, because it will often be for you.

:)

+4
source

Single inserts should be considered in each case. Sometimes this can damage readability, and a more detailed (readable: easy to use) version should be used.

There are times when a single-line layer seems more natural. Take the following:

 int Total = (Something ? 1 : 2) + (SomethingElse ? (AnotherThing ? x : y) : z); 

Or the equivalent (a little less readable?):

 int Total = Something ? 1 : 2; Total += SomethingElse ? (AnotherThing ? x : y) : z; 

IMHO, I would prefer one of the following:

 int Total; if (Something) Total = 1; else Total = 2; if (SomethingElse) if (AnotherThing) Total += x; else Total += y; else Total += z 

With nested if statements, it’s more difficult for me to determine the final result without tracing it. The one-liner is more like the mathematical formula it should have been, and therefore easier to follow.

As for the cool factor, in "Look Ma, I wrote a whole program in one line!" there is a certain feeling of success / show factor! ". But I would not use it in any other context than the game; I certainly would not want to come back and debug it!

Ultimately, with real (production) projects, the best that is easiest to understand is the best. Because there will be a time when you or someone else will look at the code again. What they say is true: time is precious.

+3
source

This is true in most cases, but in some cases, when single-liners are common idioms, then this is acceptable.?: May be an example. Closing may be different.

+1
source

No, this is annoying.

+1
source

One liner may be more readable, and it may be less readable. You will have to judge the case.

And, of course, the prompt is single-line.

+1
source

VASTLY is more important in developing and adhering to a consistent style.

You will find errors much faster, you can better share codes with others and even faster than code if you simply develop and adhere to the template.

One aspect of this is single-line decision making. Here is one example from my store (I launched a small coding department) - how we handle IFs:

  • Ifs will never be on the same line if they overflow the visible length of the line, including any indentation.
  • You will never have else clauses on the same line as if even if it matches the line length rule.

Design your own style and STICK WITH IT (or reformat all the code in the same project if you change the style).

.

+1
source

The main drawback of the "one liner", in my opinion, is that it makes it difficult to break down the code and debug. For example, pretend you have the following code:

 a().b().c(d() + e()) 

If this does not work, it is difficult to verify the intermediate values. However, it is trivial to break with gdb (or any other tool that you can use) in the following, and check every single variable and see exactly what is happening:

 A = a(); B = Ab(); D = d(); E = e(); // here i can query ABD and E BC(d + e); 
+1
source

One rule: if you can express the concept of one line in a simple language in a very short sentence. "If it is true, set it for this, otherwise set it to"

0
source

For a code construction where the ultimate goal of the whole structure is to determine what value needs to be set for one variable, with appropriate formatting it is almost always easier to set several conditonals in one statement. With a few nested if the end, if elses, the common goal, set a variable ...

" variableName = "

it is necessary to repeat in each nested sentence, and the eye must read all of them to see it .. with the expression singlr, it is much clearer, and with appropriate formatting, complexity is also easier to manage ..

 decimal cost = usePriority? PriorityRate * weight: useAirFreight? AirRate * weight: crossMultRegions? MultRegionRate: SingleRegionRate; 
0
source

prose is an easy to understand one liner that works.

cons is the concatenation of tangled gibberish on one line.

0
source

Actually, I would call it a bad idea (although I do it myself on occasion) - it strikes me as something that did more to impress an intelligent person than to make good code. Smart tricks of this kind are usually very bad.

However, I personally strive to have one “idea” per line of code; if this burst of logic is easily encapsulated in one thought, then go ahead. If you need to stop and figure it out a bit, it's best to break it down.

0
source

All Articles