请找到以下代码并帮助我编写更好的if...else
代码。我觉得这是一种非常低于平均水平的方式来写其他的。
{
Retrieve the number in focus.
string number= getnumber();
string zipcode;
int corporate;
bool bCoverageInBet = false;
try
{
//Get the address and zipcode of the number
GetAddress(number, out address);
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
if (zipcode.Equals(_loadedZipcode))
{
if (adress.Equals(_address ))
{
if (focusChanged)
{
return result;
}
}
else
{
if (bCoverageInBet)
{
// case 2: Different address and different coverage which is in between, make a call anf get new valus for result
//return the new result
}
else
{
return //current result value;
}
}
}
}
else
{
_loadedZipcode = zipcode;
_address = adress;
GetResponse( out resp)
{
if ((resp != null))
{
bool isCorporate = false;
corporate = getValues();
if (corporate .Equals(100))
{
result = true;
return result;
}
else if (corporate > 0 && corporate < 100)
{
//Make a call to get corporate
bCoverageInBet = true;
LocationResponse objResults;
if (GetAddressbycorporate(out objResults, out errMsg))
{
if (objResults != null)
{
isCorporate = objResults.located;
if (isCorporate )
{
result = true;
}
}
}
}
return result;
}
return result;
}
else
{
DisplayError("No response ");
return result;
}
}
}
else
{
//To do: What is address comes null
}
}
catch (System.Exception ex)
{
//some ccode
}
return result;
}
由于 ķ
答案 0 :(得分:4)
根据需要将方法重构为较小的单位。此外,从方法返回,而不是使用else子句。
E.g。而不是
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
}
else
{
return false;
}
}
else
{
return false;
}
执行:
if (adress == null)
{
return false;
}
if (string.IsNullOrEmpty(_loadedZipcode) || _address == null)
{
return false;
}
还有很多其他问题,但这应该使代码更清晰。
答案 1 :(得分:3)
我认为没有人会“帮助”你重写这段代码。但是,我可以提供一些建议。
我发现更容易追溯到最内层,如果并尝试重写并向后工作(向上链)。根据IF块,有时可以更容易地将它们分解为单独的方法。
另外,不要忘记条件运算符。使用它有时比使用整个if else块更清楚。
例如,property = (boolean expression) ? (true value) : (false value);
以下是MSDN上的链接:conditonal operator documentation