tags:

views:

62

answers:

3

Hi,

Suppose you need to check some condition at multiple places in code. For ex. we have a configurable element in config file called System.

So if System = "A" do some work/show some screen else do other stuff

I dont think its a good idea to check at many places the same condition. what should be the approach ?

Thanks.

+1  A: 

It depends on your requirements. It might be a good candidate for refactoring to use the Command Pattern, but for simple cases this is probably overkill.

If you're talking about multiple times in the same scope and the system is unlikely to change within that scope, then you could just assign the result to a boolean and refer to that.

To explain the command pattern, what you would do is create a base class or interface with a method that does the actual work, and then call that:

interface ISystem
{
    void DoSomething();
}

class SystemA : ISystem
{
   public void DoSomething() { /* handle the system A case*/ }
}

class SystemB : ISystem
{
   public void DoSomething() { /* handle the system B case */ }
}

Then in your class that needs the system to do something, you would refer to it as an IDoSomething, and just call the method DoSomething:

publc void MethodThatDoesSomething(ISystem system)
{
    system.DoSomething();
}
Bennor McCarthy
+1  A: 

Make your configuration more object-oriented, instead of just key/value pairs - so your condition would become

if (config.IsSomeCondition)

where IsSomeCondition would wrap the underlying details.

Alternatively, you could potentially use polymorphism with virtual calls to do the right thing - create the appropriate instance (once) based on the configuration, and let polymorphism do the rest. It's very hard to say without knowing more details of what you're trying to do.

Jon Skeet
Uh oh... I'm going to get skeeted.
Bennor McCarthy
ok. I had read the config file in a class and a enum for values to compare. AND everywhere i check as if (config.systemID == Enum.systemtid). This needs to be done in each code file where the check is required. So this is fine.
ksa
A: 

Consider your config as an object(class) instead of a config file.

public class SysConfig
{
   [OptionalValidationAttributeHere]
   public static string SystemType {get;set;}
   public static Action DoSomethingDependsOnSystemType()
   {
      //return different actions
   }
}

Initialize the SysConfig class at the startup of your application and load configs into it.

Danny Chen