Bla*_*man 3 refactoring nested-if
好的,我想要一些意见,我怎么能解决这个方法的混乱!
它与许多嵌套的'if'语句有关.
但是我意识到我必须确切地知道方法失败的地方,目前在每个相应的'else'子句中我都记录错误(失败的'if'条件').
注意:忽略事物背后的任何逻辑,请关注样式和结构,因为我已经使所有的功能名称等等.
这是骨架结构:
public void MyMethod()
{
try
{
bool tryAgain = false;
string filename = DownloadFile();
if( IsFileFormatOk(filename) )
{
blah = GetBlah(filename);
if(blah.ID > 0)
{
if(ImportFile(filename)
{
string username = GetUserFromFile(filename);
if(isValidUser(username))
{
// few more levels to go
//
//
//
}
else
{
LogError(filename, ...); // specific to this if statement
tryAgain = true;
}
}
else
{
LogError(filename, ...); // specific to this if statement
tryAgain = true;
}
}
else
{
LogError(filename, ...); // specific to this if statement
tryAgain = true;
}
}
else
{
LogError(filename, ...); // specific to this if statement
tryAgain = true;
}
}
catch
{
}
finally
{
if(tryAgain)
{
// blah
}
}
}
Run Code Online (Sandbox Code Playgroud)
我会努力改变你的逻辑,这样你就可以尽快从方法中返回,而不是嵌套更多的逻辑.例如:
// GOOD
if (!file.exists())
return;
// Rest of the code
// BAD
if (file.exists()){
// Code goes here
}
return;
Run Code Online (Sandbox Code Playgroud)
这可能有助于删除一些嵌套并使事情变得简单.