如何重构代码以避免多个if-s [面试]? [英] How to refactor code to avoid multiple if-s [from interview]?

查看:213
本文介绍了如何重构代码以避免多个if-s [面试]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面试中我被问到以下问题:



我有以下方法:

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

问题是: 你应该以上面的重构方法。你会做什么?



在面试中我没有把握如何做到。



现在我认为状态设计模式适合这项任务?



我是对的吗?你怎么看?



P.S。



我和我的同事谈判了。他认为策略设计模式更合适。



PS


$ b $另一位专家认为,连锁责任设计模式更合适。

解决方案

在这种情况下需要的关键重构工作是分离行为变化并将其封装成对象。这是应用策略模式的好用例。在你的情况下,你将有一个名为SomeObjectInterface的接口,它有一个叫做doSomething()的API。那么你会有接口的实现,每个都实现了做某事的策略。



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



哪些 doSomething()实现被调用将由对象 o 的实际类型确定。



您可以参考这篇文章的理由: http://blog.softwarerevisited.com/2015/06/strategy-pattern.html


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.

解决方案

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

这篇关于如何重构代码以避免多个if-s [面试]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆