patterncsharpMinor
Nested if statements dependant on nulls
Viewed 0 times
nullsnesteddependantstatements
Problem
As far as readability and best practises go I am not sure how best to write this helper method:
Here are two options I have tried:
Alternatively,
Which of these are better? Any other alternatives?
Here are two options I have tried:
private decimal? selectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
if(localTolerance == null)
{
if(globalTolerance == null){
return null;
}else{
return globalTolerance;
}
}
else
{
if(globalTolerance == null){
return localTolerance;
}else{
if(globalTolerance < localTolerance){
return globalTolerance;
}else{
return localTolerance;
}
}
}
}Alternatively,
private decimal? selectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
if (localTolerance == null && globalTolerance == null)
{
return null;
}
if (localTolerance != null && globalTolerance == null)
{
return localTolerance;
}
if (localTolerance == null && globalTolerance != null)
{
return globalTolerance;
}
if (globalTolerance < localTolerance)
{
return globalTolerance;
}
else
{
return localTolerance;
}
}Which of these are better? Any other alternatives?
Solution
Methods should always be named in
You can condense the logic to the following:
PascalCase.You can condense the logic to the following:
private decimal? SelectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
if (localTolerance == null || globalTolerance == null)
{
return localTolerance ?? globalTolerance;
}
return Math.Min(globalTolerance.Value, localTolerance.Value);
}Code Snippets
private decimal? SelectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
if (localTolerance == null || globalTolerance == null)
{
return localTolerance ?? globalTolerance;
}
return Math.Min(globalTolerance.Value, localTolerance.Value);
}Context
StackExchange Code Review Q#84194, answer score: 4
Revisions (0)
No revisions yet.