简体   繁体   中英

Best approach when same condition needs to be checked at multiple places in code

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.

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();
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM