patterncsharpModerate
Switch case statement refactoring
Viewed 0 times
caseswitchrefactoringstatement
Problem
I have the following code with switch case statement:
How should I refactor this code to be more clear and readable or how could I otherwise improve this code snippet?
UPDATE
According to valuable answers
I have updated the code in the following way,
What do you think about this? Is it readable or not?
public string IrregularCouponLabel
{
get
{
switch ((ctrl.IrregularCouponFirst ? 10 : 0) + (ctrl.IrregularCouponLast ? 1 : 0))
{
case 11: return LocalString.Evaluate("label.Both");
case 10: return LocalString.Evaluate("label.First");
case 1: return LocalString.Evaluate("label.Last");
default: return LocalString.Evaluate("label.None");
}
}
}How should I refactor this code to be more clear and readable or how could I otherwise improve this code snippet?
UPDATE
According to valuable answers
I have updated the code in the following way,
public string IrregularCouponLabel
{
get
{
return LocalString.Evaluate("label." + GetIrregularCouponValue());
}
}
private string GetIrregularCouponValue()
{
bool first = ctrl.IrregularCouponFirst;
bool last = ctrl.IrregularCouponLast;
bool both = first && last;
return both ? "Both" :
first ? "First" :
last ? "Last" :
"None";
}What do you think about this? Is it readable or not?
Solution
You can use an
You can also use only conditional operators. This way of chaining conditional operators checks take a bit of work to grasp the first time, but it's very compact:
if statement and the conditional operator:string label;
if (ctrl.IrregularCouponFirst) {
label = ctrl.IrregularCouponLast ? "label.Both" : "label.First";
} else {
label = ctrl.IrregularCouponLast ? "label.Last" : "label.None";
}
return LocalString.Evaluate(label);You can also use only conditional operators. This way of chaining conditional operators checks take a bit of work to grasp the first time, but it's very compact:
return LocalString.Evaluate(
ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast ? "label.Both" :
ctrl.IrregularCouponFirst ? "label.First" :
ctrl.IrregularCouponLast ? "label.Last" :
"label.None"
);Code Snippets
string label;
if (ctrl.IrregularCouponFirst) {
label = ctrl.IrregularCouponLast ? "label.Both" : "label.First";
} else {
label = ctrl.IrregularCouponLast ? "label.Last" : "label.None";
}
return LocalString.Evaluate(label);return LocalString.Evaluate(
ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast ? "label.Both" :
ctrl.IrregularCouponFirst ? "label.First" :
ctrl.IrregularCouponLast ? "label.Last" :
"label.None"
);Context
StackExchange Code Review Q#7991, answer score: 17
Revisions (0)
No revisions yet.