According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also
Here goes mine. Using LINQ and Factory Pattern :D
class FactoryString
{
static FactoryString()
{
private static Dictionary<string, string> dictionary = new Dictionary<string, string>
{
{"foo", "some logic here"},
{"bar", "something else here"},
{"raboof", "of course I need more than just Writeln"},
};
}
public static string getString(string s)
{
return dictionary.Single(x => x.Key.Equals(s)).Value;
}
}
static void main()
{
Console.WriteLine(FactoryString.getString("foo"));
}
write classes with virtual methods which is derived from your abstract base class SomeThingWriter.
then every class which are derived from base class should implement a function like writeSomething or whatever you want.
abstract class MyBaseClass
{
public abstract void writeSomething();
}
class DerivedClass1 : MyBaseClass
{
public override void writeSomething()
{
Writeln("something else here 1");
}
}
class DerivedClass2 : MyBaseClass
{
public override void writeSomething()
{
Writeln("something else here 2");
}
}
than just call like
MyBaseClass c = new DeriveClass1();
c.writeSomething();
c = new DerivedClass2();
c.writeSomething();
The example you have given I would not change (though I guess you realise it wouldn't need changing)- I'm guessing you are using it as a representational example.
In Fowler's Refactoring book, he discusses the Replace Conditional with Polymorphism. That's what I see as a good use to replace if/switch statements (where appropriate).
I think you are looking for Factory Patterns.
In some cases it might be legit to avoid the if structure
in others its just plain idiocy to try to avoid if.
While the examples provided to avoid the if structure are valid alternatives you should ask yourself this:
Why am i making my code unnecessarly complicated to avoid a simple if structure ? If the only reason is that you have to because of the anti-if campaign then its bad reason
Looking at the campaign, it's very poorly explained. There's nothing wrong with ifs, but in certain cases they can indicate that you're not using OOP to its full potential.
What the campaign is trying to promote is increased use of polymorphism in order to decouple calling code from the type of object it is looking at.
You would use some smarter object instead of s being a string:
interface I {
public String getName();
public void doSomething();
}
class A implements I {
public String getName() { return "one"; }
public void doSomething() { ...; }
}
class B implements I {
public String getName() { return "two"; }
public void doSomething() { ...; }
}
Then you can replace the ifs with:
I obj = ...get an A or B from somewhere...;
obj.doSomething();