Optimize conditional operators branching in C#
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 dupl开发者_运维知识库icated block on two different levels. Is it possible to optimize this code to probably split them to one? Or something like that..
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.
You can simplify your expression to this:
if (any && !specified)
{
return empty;
}
else
{
return isClient ? textbox : dropdown;
}
any && !specified ?
empty :
isClient ? textbox : dropdown;
Put the isClient ? textbox : dropdown
block in a method and make method calls from you original branch = no more code duplication.
精彩评论