Ok I want some opinions how I can fix this mess of a method!
It has WAY to many nested ‘if’ statements.
But realize I have to know exactly where the method fails, currently in each of the respective ‘else’ clause I am logging the error (the failed ‘if’ condition’).
Note: ignore any logic behind the things, please focus on the style and structure as I have made all the function names up etc.
Here is the skeleton structure:
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 } } }
I would work on changing your logic so you can return from the method as soon as possible instead of nesting more logic. Fore example:
This may help remove some nesting and make things less complicated.