views:

628

answers:

15

Is it cool?

IMO one-liners reduces the readability and makes debugging/understanding more difficult.

+4  A: 

Oneliners can be useful in some situations

int value = bool ? 1 : 0;

But for the most part they make the code harder to follow. I think you only should put things on one line when it is easy to follow, the intent is clear, and it won't affect debugging.

Bob
I would just use !!bool in the remained of the code, assuming you're doing C(++) there.
+1  A: 

That's true in most cases, but in some cases where one-liners are common idioms, then it's acceptable. ? : might be an example. Closure might be another one.

Khnle
+10  A: 

If there is a simple way of expressing something in a single line of code, that's great. If it's just a case of stuffing in lots of expressions into a single line, that's not so good.

To explain what I mean - LINQ allows you to express quite complicated transformations in relative simplicity. That's great - but I wouldn't try to fit a huge LINQ expression onto a single line. For instance:

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

is more readable than:

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

It's also more readabe than doing all the filtering, ordering and projection manually. It's a nice sweet-spot.

Trying to be "clever" is rarely a good idea - but if you can express something simply and concisely, that's good.

Jon Skeet
I think this example is unfortunate, this question is about "putting as much logic as possible in a minimum piece of code", not about where to use carriage returns.
Steph Thirion
Both of your examples are one line of code, just formatted differently.
Jason
@Jon: This might be a better example of the one liner comparison: var emps = employees.Where(p => p.Salary > 10000).OrderBy(p => p.Name).Select(p => new {Name = p.Name, Department = p.Department});I'm in agreement though - it's far less readable than the multiline version.
BenAlabaster
@Steph: It's not clear to me from the question whether the OP really was talking about lines of code or not.
Jon Skeet
Jason: They're both one *statement*, but the first version is clearly on four *lines*. There's an obvious distinction between "statement" and "line" - why conflate the two?
Jon Skeet
I understand the distinction, but I think the OPs use of "line" here was getting at complex statements as he mentioned the difficulty of debugging and understanding "oneliners."
Jason
Debugging suggests statements - understanding doesn't. I'd say my multiline code sample is much easier to understand than the single line version, for example.
Jon Skeet
Regarding your last statement (intended), we are in agreement.
Jason
+1  A: 

No, it is annoying.

IceHeat
+1: One-liners -- for the sake of coolness -- are annoying. If something happens to work out that way, fine. Striving for one-liners is annoying,
S.Lott
Whoever gave you a downer on this did so because they disagree, not because you were wrong. So, I gave you a thumbs up as compensation.
Richard T
+12  A: 

Maximize understandability of the code.

Sometimes that means putting (simple, easily understood) expressions on one line in order to get more code in a given amount of screen real-estate (i.e. the source code editor).

Other times that means taking small steps to make it obvious what the code means.

One-liners should be a side-effect, not a goal (nor something to be avoided).

joel.neely
+1: It's about semantics.
S.Lott
Word, Joel, word!
PEZ
+1  A: 

One liners can be more readable and they can be less readable. You'll have to judge from case to case.

And, of course, on the prompt one-liners rule.

PEZ
+4  A: 

This is by definition subjective, and due to the vagueness of the question, you'll likely get answers all over the map. Are you referring to a single physical line or logical line? EG, are you talking about:

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

or

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

One-liners, to me, are a matter of "what feels right." In the case above, I'd probably break that into both physical and logic lines, getting the instance of BigHonkinClassName, then pulling the full path to .TheOther. But that's just me. Other people will disagree. (And there's room for that. Like I said, subjective.)

Regarding readability, bear in mind that, for many languages, even "one-liners" can be broken out into multiple lines. If you have a long set of conditions for the conditional ternary operator (? :), for example, it might behoove you to break it into multiple 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 frameworks (such as many DAL generators, EG SubSonic) almost require obscenely long one-liners to get any real work done. Othertimes, breaking that into multiple lines is quite preferable.

Given concrete examples, the community can provide better, more practical advice.

In general, I definitely don't think you should ever "squeeze" a bunch of code onto a single physical line. That doesn't just hurt legibility, it smacks of someone who has outright disdain for the maintenance programmer. As I used to teach my students: always code for the maintenance programmer, because it will often be you.

:)

John Rudy
A: 

One rule of thumb is if you can express the concept of the one line in plain language in a very short sentence. "If it's true, set it to this, otherwise set it to that"

DGM
If it's true, set it to this. Otherwise, set it to that
Greg Dean
+6  A: 

One-liners, when used properly, transmit your intent clearly and make the structure of your code easier to grasp.

A python example is list comprehensions:

new_lst = [i for i in lst if some_condition]

instead of:

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

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

Algorias
+3  A: 

One-liners should be treated on a case-by-case basis. Sometimes it can really hurt readability and a more verbose (read: easy-to-follow) version should be used.

There are times, however when a one-liner seems more natural. Take the following:

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

Or the equivalent (slightly less readable?):

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

IMHO, I would prefer either of the above to the following:

int Total;

if (Something)
  Total = 1;
else
  Total = 2;

if (SomethingElse)
  if (AnotherThing)
    Total += x;
  else
    Total += y;
else
  Total += z

With the nested if-statements, I have a harder time figuring out the final result without tracing through it. The one-liner feels more like the math formula it was intended to be, and consequently easier to follow.

As far as the cool factor, there is a certain feeling of accomplishment / show-off factor in "Look Ma, I wrote a whole program in one line!". But I wouldn't use it in any context other than playing around; I certainly wouldn't want to have to go back and debug it!

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

lc
Not only treated on case-by-case basis, but you can also combine the approaches. Taking your example, an option is to write:int Total = (Something ? 1 : 2);if (SomethingElse) Total += (AnotherThing ? x : y);else Total += z;Readability level is really subjective, in some cases.
Dan C.
A: 

For a code construct where the ultimate objective of the entire structure is to decide what value to set a single variable, With appropriate formatting, it is almost always clearer to put multiple conditonals into a single statement. With multiple nested if end if elses, the overall objective, to set the variable...

" variableName = "

must be repeated in every nested clause, and the eye must read all of them to see this.. with a singlr statement, it is much clearer, and with the appropriate formatting, the complexity is more easily managed as well...

decimal cost =
      usePriority?        PriorityRate * weight:
      useAirFreight?      AirRate * weight:
      crossMultRegions?   MultRegionRate:
                          SingleRegionRate;
Charles Bretana
In the real world, you'll soon have some change in business rules that makes these decisions more complicated. If you implement this in a Strategy, you'll probably be in a better position to handle that change.
Jay Bazuzi
YAGNI tells us that we too often over-estimate the difference between 'x' and 'y', and the probability that we will actually need the thing. Chances are that later, even if we do need it, it will be completely different because of how it must interact with other additions to the system.
Charles Bretana
Correct: YAGNI does tell us that. Maybe I should try a different argument, like "I'd rather use objects than statements to express my program" or "This code requires me to keep track of many ideas at once."
Jay Bazuzi
In general I agree with that, but would add that there's a complexity threshold below which the use of objects instead of code statements adds more obfuscation than clarity... If there's an application-required paradigm or abstraction that can be represented by a set of properly structured classes,
Charles Bretana
then great, that approach increases clarity and IS needed... But if you're just doing it cause it's the latest kewl design pattern you learned, or cause you "might" need it in the next release, then I'd say leave it out.
Charles Bretana
+1  A: 

VASTLY more important is developing and sticking to a consistent style.

You'll find bugs MUCH faster, be better able to share code with others, and even code faster if you merely develop and stick to a pattern.

One aspect of this is to make a decision on one-liners. Here's one example from my shop (I run a small coding department) - how we handle IFs:

  • Ifs shall never be all on one line if they overflow the visible line length, including any indentation.
  • Thou shalt never have else clauses on the same line as the if even if it comports with the line-length rule.

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

.

Richard T
A: 

The prose is an easily understood one liner that works.

The cons is the concatenation of obfuscated gibberish on one line.

Mark Stock
+1  A: 

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

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

If this isn't working, its hard to inspect the intermediate values. However, it's trivial to break with gdb (or whatever other tool you may be using) in the following, and check each individual variable and see precisely what is failing:

A = a();
B = A.b();
D = d();
E = e(); // here i can query A B D and E

B.C(d + e);
Francisco Ryan Tolmasky I
A: 

Generally, I'd call it a bad idea (although I do it myself on occasion) -- it strikes me as something that's done more to impress on how clever someone is than it is to make good code. "Clever tricks" of that sort are generally very bad.

That said, I personally aim to have one "idea" per line of code; if this burst of logic is easily encapsulated in a single thought, then go ahead. If you have to stop and puzzle it out a bit, best to break it up.

Trevel