views:

120

answers:

4

Hello. I have next code:

return this.AllowChooseAny.Value ?
       radioSpecific.Checked ?
          UserManager.CurrentUser.IsClient ? txtSubject.Text : subjectDropDownList.SelectedItem.Text :
          String.Empty :
       UserManager.CurrentUser.IsClient ? txtSubject.Text : subjectDropDownList.SelectedItem.Text;

or in less complex form:

return any ?
    specified ?
       isClient ? textbox : dropdown :
       empty :
    isClient ? textbox : dropdown;

or in schematic form:

                     |
                    any
              /            \
      specified             isClient
      /        \           /        \
  isClient    empty     textbox  dropdown
  /       \
textbox  dropdown

Evidently I have a duplicated block on two different levels. Is it possible to optimize this code to probably split them to one? Or something like that..

+6  A: 

You can simplify your expression to this:

if (any && !specified)
{
    return empty;
}
else
{
    return isClient ? textbox : dropdown;
}
dtb
+1 for readability
Michael Stum
+11  A: 

That block of code is nearly unreadable. Don't use the ternary operator just for the sake of the ternary operator; it's there to make thigs more readable by eliminating if blocks for very simple expressions. What you have is not.

Adam Robinson
+1 to compensate. :-)
David
although i agree with you, you didn't answer the question.
Andrey
Readable code is a form of optimization
PoweRoy
A: 

Put the isClient ? textbox : dropdown block in a method and make method calls from you original branch = no more code duplication.

Ando
+5  A: 
any && !specified ? 
   empty : 
   isClient ? textbox : dropdown;  
Andrey