More on Rust

Jim bitcirkel at yahoo.com
Fri Feb 11 05:28:14 PST 2011


spir Wrote:

> On 02/11/2011 08:39 AM, Jim wrote:
> > Jacob Carlborg Wrote:
> >
> >> On 2011-02-10 20:15, Walter Bright wrote:
> >>> Nick Sabalausky wrote:
> >>>> "bearophile"<bearophileHUGS at lycos.com>  wrote in message
> >>>> news:iivb5n$na3$1 at digitalmars.com...
> >>>>> auto x;
> >>>>> if (localtime().hours>= 8) {
> >>>>> x = "awake!"
> >>>>> } else {
> >>>>> x = "asleep, go away."
> >>>>> }
> >>>>> log "I'm " + x;
> >>>>>
> >>>>
> >>>> That would be really nice to have in D.
> >>>
> >>>
> >>> auto x = (localtime().hours>= 8) ? "awake!" : "asleep, go away.";
> >>
> >> For this simple if statement it works but as soon you have a few lines
> >> in the if statement it will become really ugly. But one could wrap the
> >> if statement in a function instead. In other languages where statements
> >> really are expressions this works:
> >>
> >> auto x = if (localtime().hours>= 8)
> >>               "awake!";
> >>            else
> >>               "asleep, go away.";
> >>
> >> log "I'm " + x;
> >
> >
> >
> > Other languages may have bloated syntaxes, with no particular benefit.
> >
> >
> > auto x = localtime().hours>= 8 ?
> > 	"awake!"
> > 	:
> > 	"asleep, go away.";
> >
> > log( "I'm " ~ x );
> >
> >
> > If the expressions are complex I put them in functions.
> > 1) It hides and isolates details, which allows you to focus on the more abstract aspects.
> > 2) It gives the expression a name and facilitates reuse.
> 
> Agreed.
> But in practice I often end up beeing dubious about seemingly nice features 
> like, precisely, the ternary operator. In languages that do not have such a 
> nicety people end up writng eg:
>      if (localtime().hours>= 8) x = awake;
>      else x = "asleep, go away.";
> Apart from the very mild annoyance, I guess, of writing twice "x =", this is 
> all gain: code is both more compact and legible.
> Precisely, because the ternary operator is a bit weird syntactically (and not 
> that commonly needed and used in real code), people feel, just like you, the 
> need to clarify it in code, finally using more vertical space. Note that the 
> case here is the simplest possible, expressions being plain literal constants. 
> I personly only consume 3 lines:
>      auto x = (localtime().hours>= 8)
>          ? "awake!"
>          : "asleep, go away.";
> What do you think?


I always make a conscious effort to write succinct expressions. My rule is to only use the ternary operator when it actually makes the code cleaner.

Why?

Branches should be conspicuous because they increase the number of code paths. Exceptions are the other big source of code paths. This is, btw, why I think that scope statements in D are just superb.


More information about the Digitalmars-d mailing list