Please find the following code and help me write a better if...else
code. I feel this is a very below average way to write else if.
{
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;
}
Thanks K
Refactor the method into smaller units as appropriate. Also, return early from the method rather than using else clauses.
E.g. instead of
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;
}
Do:
if (adress == null)
{
return false;
}
if (string.IsNullOrEmpty(_loadedZipcode) || _address == null)
{
return false;
}
There are quite a few other problems, but that should make the code cleaner to start with.
I don't think anyone is going to "help" you rewrite this code. However, I can offer some suggestions.
I have found it easier to trace my way down to the inner most if and try to rewrite and work my way backwards (up the chain). Depending on the IF block, it is sometimes easier to break them out into separate methods where appropriate.
Also, don't forget about the conditional operator. It can sometimes be clearer to use that than a whole if else block.
For example, property = (boolean expression) ? (true value) : (false value);
Here is a link to MSDN on it: conditonal operator documentation
精彩评论