How to refactor code to avoid multiple if-s [from interview]?

限于喜欢 提交于 2019-12-08 12:20:45

问题


On interview I was asked the following question:

I have following method:

public void foo(SomeObject o){
    if(o.matches(constant1)){
          doSomething1(); 
    }else if(o.matches(constant2)){
          doSomething2(); 
    }else if(o.matches(constant3)){
          doSomething3(); 
    }
    ....
}

question was: you should refactor method above. What will you do?

On interview I didn't grasp how to make it.

Now I think that state design pattern is suitable for this task ?

Am I right? What do you think?

P.S.

I negotiated with my colleague. he thinks that strategy design pattern is more suitable.

P.S.

Another expert thinks that chain of responsibility design pattern is more suitable.


回答1:


The usual answer is Replace Conditional With Command

See this other SO answer I gave for a similar answer:

Replacing if else statement with pattern




回答2:


The key refactoring effort required in this case is to separate the behavior variation and encapsulate them into objects. This is a good use case of applying the strategy pattern. In your case, you would have an interface called SomeObjectInterface, which has an API called doSomething(). Then you would have implementations of the interface, each of wich implementes on strategy of doing something.

public void foo(SomeObjectInterface o){ o.doSomething(); .... }

Which doSomething() implementation gets invoked will be determined by the real type of the object o.

You can refer to this post for rationals behind this: http://blog.softwarerevisited.com/2015/06/strategy-pattern.html



来源:https://stackoverflow.com/questions/29469195/how-to-refactor-code-to-avoid-multiple-if-s-from-interview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!