views:

733

answers:

17

I really really like the conditional operator in C#. It makes my life very much easier in writing logic such as this:

public  string FormattedFileName
    {
        get
        {
            return string.Format("{0}_{1}_{2}_{3}.xls", 
            DateTime.Now.Month.ToString().Length == 1 
             ? "0" + DateTime.Now.Month.ToString()
             : DateTime.Now.Month.ToString(), 
            DateTime.Now.Day.ToString().Length == 1 
             ? "0" + DateTime.Now.Day.ToString()
             : DateTime.Now.Day.ToString(), 
            DateTime.Now.Year.ToString(), 
            "DownLoaded_From_Clients");
        }
    }

Of course, that means I lose the readability of the code. Anyway, I am just curious what opinion other fellow developers have on this approach of writing code. Thanks. I appreciate both negative and positive comments equally.

+1  A: 

Comment your code if you're worried about readability, otherwise I see no reason not to use it.

Dave Swersky
+10  A: 

If you wanted to make it more readble you could always factor out the calls into getCurrentMonth(), getCurrentYear, getCurrentDay calls....

Visage
This. Readability is considerably improved by reducing the terms to descriptively named helper methods.
annakata
+2  A: 

I love the tertiary operator. It is only a problem when you are not familiar with the notation. It is difficult at times to find documentation on the lonely operator, but if it were used more in documentation and books I believe that it would gain much more popularity.

Brandon Stewart
+5  A: 

Readability may be achieved through use of indentation, whitespace, and, as Dave said, comments.

Jamie
A: 

It's called ternary operator (we don't call binary code the secondary code, after all), and it has been asked before:

http://stackoverflow.com/questions/522919/is-this-a-reasonable-use-of-the-ternary-operator

cdonner
No, it's called the conditional operator. It's *a* ternary operator, but its *name* is the conditional operator. See the C# 3.0 spec section 7.13.
Jon Skeet
Oh Damn. You just got Skeeted.
Neil N
To quote section 7.13:"The ?: operator is called the conditional operator. It is at times also called the ternary operator." Very funny, indeed.
cdonner
You're right about the cardinal number, but wrong about the operator name.
xtofl
I guess John Skeet is always right, even when he is not right ...
cdonner
+3  A: 

I only use it for simple if statements, two at most. Any more than that and I'd rather write it out the long way than to have it look like what you posted. Then again I try not to have more than two levels of nested if statements in the first place, so its never really come up.

Brandon
+1  A: 

A few parenthesis help readability immensly.

Consider adding them to help clarify exactly what your alternation operator is doing, and you should be fine. :)

John Gietzen
+48  A: 

Like it ? Use it : Don't

// if (Like it) then (Use it) else (Don't)
Daniel Daranas
sharp and concise.
xtofl
I'd +1 for humour alone, but consideration for others is an important part of coding.
annakata
@annakata, I agree that setting coding standards guidelines is important. Of course, I would vote against including the rule "don't use the ternary operator" in them.
Daniel Daranas
Teehee - v.good :-)
Gordon Mackie JoanMiro
I like your answer so tremendously. Thank you
Shiva
(Like it) ? Use it : Don't
Joe Philllips
i can't even easily read what the answer is saying. If i come across that is any code i'm working on: i'm taking it out. i do not like the conditional operator, and i'm not going to use it - that includes trying to decipher or debug it.
Ian Boyd
@Ian: Nice explanatory edit. About your comment, I think the conditional operator is widely known and I wouldn't ban it in my coding standards. If we were in the same team that would have to be discussed and an agreement reached, but I'd be sad to renounce using this useful construct.
Daniel Daranas
Oh i wouldn't ban it, but team members shouldn't be surprised if it ends up being converted. At the very least they should add a comment that is the "if..then..else" form.
Ian Boyd
+3  A: 

I'm all for using the conditional operator but you don't need it here...

return string.Format("{0}_{1}_{2}_{3}.xls", 
    DateTime.Now.Month.ToString("00"), 
    DateTime.Now.Day.ToString("00"), 
    DateTime.Now.Year, 
    "DownLoaded_From_Clients");
Austin Salonen
+20  A: 

When you need it, the ternary operator is invaluable. However, I think that there are often better ways to express yourself. In the example you gave, why not use a format string that will do exactly what you want: "{0:00}_{1:00}_{2}_{3}.xls", allowing you to simplify your code significantly?

kvb
+2  A: 

When taking a look in the 'functional' world, where you can't 'do' things conditionally, the conditional operator is very common. In one way or another, I have the impression that the functional paradigm is gaining interest, because it takes out the temporal control flow caused by "if (this) dothis else dothat" statements. It makes it easier to really define what you mean instead of telling the computer what to do.

Readability is one issue, though, in languages that don't fully support this.

Debuggeability is another: in e.g. C++, you can't put a breakpoint on just one of the branches.

xtofl
+3  A: 

My personal rule of thumb is that if it's blatantly obvious what the ternary does, then it's ok. If it's crammed into one line just so the coder could use a ternary, then it should be a bracketed if statement.

Neil N
why the downvote? Don't downvote and run!
Neil N
+1  A: 

Why not do something more like this?

public  string FormattedFileName
{
    get
    {
        return string.Format(
            "{0}_{1}_{2}_{3}.xls", 
            DateTime.Now.Month.ToString().Length == 1 ?
                "0" + DateTime.Now.Month.ToString() :
                DateTime.Now.Month.ToString(), 
            DateTime.Now.Day.ToString().Length == 1 ?
                "0" + DateTime.Now.Day.ToString() :
                DateTime.Now.Day.ToString(), 
            DateTime.Now.Year.ToString(), 
            "DownLoaded_From_Clients");
    }
}

Note I didn't change the code at all, just the formatting. As noted, you don't need to use the conditional operator here, but a little care with your indentation can improve readability immensely. I love the conditional operator, but if you run all your code together in a dense block with no indentation, it's going to be unreadable no matter what operators you are using.

Adam Jaskiewicz
Yes, and it is still terrible, unreadable code.
Richard Ev
Terrible? Yes. Unreadable? Well, it's at least sort of almost semi-readable now.
Adam Jaskiewicz
+10  A: 

Comic book guy says. "Worst use of ternary operator ever."

jms
I could not agree more...
Richard Ev
I dont know about "worst" but +1 for answering in the form of a Simpsons character.
Neil N
+1 for the Comic Book Guy reference
Gordon Mackie JoanMiro
+3  A: 

I really don't like how you've used it. I use it when I can easily fit it on one line rather than using a multiline if-statement.

Joe Philllips
+1  A: 

I don´t like the ternary operator at all - it is not very readable and I get really grumpy when I do bugfixes and find stuff like that.

zzzuperfly
+9  A: 

The example you have is an abuse of the conditional operator,

It can be expressed much more clearly in this way:

public string FormattedFileName
{
    get {
       return DateTime.Now.ToString("MM_dd_yyyy") +
          "_DownLoaded_From_Clients.xls";
    }
}

I find the conditional operator quite useful and use it often. When used correctly it can help simplify code by making it more concise.

In general, I will avoid chaining multiple conditionals in the same statement, it quickly gets very confusing, resulting in code that can not be maintained.

I also find the ?? very useful and quite often find ternaries that can easily be replaced with ??.

For example:

a == null? "empty" : a

can be replaced with:

a ?? "empty"

Sam Saffron