for example if have a if else like below , i want to know if thi开发者_StackOverflow社区s falls under any design patern ,in daily life i come across something like this so many times and don't think its good to write so many if else blocks
any guidence is really appreciated
sample///
if(dotcom){
else if (frenc){}
else if (german){}
else if (brazil){}
else if (someothercountry){}
// and the else if block goes on
else {}
}
I'd lean towards the Strategy pattern, here's an example
http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx
You're definitely on to something. If it feels wrong or repetitive, there's probably a better way.
Your example seems like a localization problem. Since you're on .NET, you could take a look at the System.Globalization namespace for some hints at how things like UI localization are handled in an object-oriented way.
The exact pattern to follow instead of if/else for any given situation will depend on what's inside your curly braces -- do different countries have different values of properties like "Population" or "Url Suffix" or "Do I need to apply for a visa before I go There"? Let's assume the latter, which will probably be the case 99% of the time. Basically, if you have something like this:
public class Country
{
public string Name { get; set; }
public string DefaultLanguage { get; set; }
public bool NeedToApplyForAVisaFirst { get; set; }
public string DefaultWordForClickHere { get; set; }
}
Code can go from:
if ("france")
{
button.Text = "French(Fr) for 'Click Here'";
}
else if ("brazil")
{
button.Text = "Portuguese(Br) for 'Click Here'";
}
.....
to:
button.Text = User.Country.DefaultWordForClickHere;
In general, it's a code smell to have too many switch
statements and if-else if
like that. There are two possible solutions:
You should generally piggyback on virtual method dispatch mechanism offered by your object-oriented language to figure out the code snippet that's going to be executed. You'll need to have a class for each condition, with an
abstract
base class. In each class you'll override a method that customizes the behavior.Use lookup tables (in your specific question, I speculate this to be probably more relevant; this is more useful if you have similar code in all paths but they are going to depend on different values for some variables).
I believe there are legitimate use cases for such kind of blocks and a large object hierarchy is not always worth it. It's a code smell, not a hard rule.
精彩评论