Replace conditional with polymorphism - nice in theory but not practical

后端 未结 9 1543
时光说笑
时光说笑 2020-12-24 01:52

\"Replace conditional with polymorphism\" is elegant only when type of object you\'re doing switch/if statement for is already selected for you. As an example, I have a web

9条回答
  •  误落风尘
    2020-12-24 02:35

    I've been thinking about this problem probably more than the rest developers that I met. Most of them are totally unaware cost of maintaining long nested if-else statement or switch cases. I totally understand your problem in applying solution called "Replace conditional with polymorphism" in your case. You successfully noticed that polymorphism works as long as object is already selected. It has been also said in this tread that this problem can be reduced to association [key] -> [class]. Here is for example AS3 implementation of the solution.

    private var _mapping:Dictionary;
    private function map():void
    {
       _mapping["view"] = new ViewAction();
       _mapping["edit"] = new EditAction();
       _mapping["sort"] = new SortAction();
    }
    
    private function getAction(key:String):BaseAction
    {
        return _mapping[key] as BaseAction;
    } 
    

    Running that would you like:

    public function run(action:String):void
    {
       var selectedAction:BaseAction = _mapping[action];
       selectedAction.apply();
    }
    

    In ActionScript3 there is a global function called getDefinitionByName(key:String):Class. The idea is to use your key values to match the names of the classes that represent the solution to your condition. In your case you would need to change "view" to "ViewAction", "edit" to "EditAction" and "sort" to "SortAtion". The is no need to memorize anything using lookup tables. The function run will look like this:

    public function run(action:Script):void
    {
       var class:Class = getDefintionByName(action);
       var selectedAction:BaseAction = new class();
       selectedAction.apply();
    }
    

    Unfortunately you loose compile checking with this solution, but you get flexibility for adding new actions. If you create a new key the only thing you need to do is create an appropriate class that will handle it.

    Please leave a comment even if you disagree with me.

提交回复
热议问题