避免if语句 [英] avoiding if statements

查看:167
本文介绍了避免if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天正在思考面向对象的设计,我想知道你是否应该避免if语句。我的想法是,在任何需要if语句的情况下,您只需创建两个实现相同方法的对象。这两个方法实现只是原始if语句的两个可能分支。

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you can simply create two objects that implement the same method. The two method implementations would simply be the two possible branches of the original if statement.

我意识到这看起来很极端,但似乎你可以试着争论它在某种程度上。对此有何想法?

I realize that this seems extreme, but it seems as though you could try and argue it to some extent. Any thoughts on this?

编辑

哇哇哇哇哇哇哇哇。我想这太极端了。是否有可能说,在OOP下你应该期望更少的陈述?

Wow that didn't take long. I suppose this is way too extreme. Is it possible to say though, that under OOP you should expect way less if statements?

第二次编辑

这是怎样的:一个确定其方法实现的对象基于其属性。也就是说,您可以通过两种方式实现 someMethod()并指定一些限制。在任何时候,对象都将根据其属性路由到正确的方法实现。所以在的情况下if(x> 5)只有两个方法依赖于 x 属性

What about this: An object that determines its method implementation based on its attributes. That is to say you can implement someMethod() in two ways and specify some restrictions. At any point an object will route to the correct method implementation based on its properties. So in the case of if(x > 5) just have two methods that rely on the x attribute

推荐答案

我可以告诉你一件事。无论人们怎么说,考虑简化和消除不必要的分支都是您成为软件开发人员的标志。分支错误,测试,维护,错误率较高等原因有很多。这是我在面试人员时所寻求的事情之一,并且是他们作为开发人员成熟程度的一个很好的指标。我鼓励您继续尝试,通过使用更少的条件来简化代码和设计。当我执行此切换时,我发现调试代码的时间要少得多,它只是起作用,然后当我不得不改变某些内容时,由于大多数代码都是顺序的,所以更改非常容易。无论别人说什么,我都会鼓励你100%继续做你正在做的事情。请记住,大多数开发人员的工作和思考程度要低得多,只需遵循规则即可。这样做很好。

I can tell you one thing. No matter what people say, thinking about simplifying and eliminating unnecessary branching is a sign of you maturing as a software developer. There are many reasons why branching is bad, testing, maintenance, higher rate of bugs and so on. This is one of the things I look for when interviewing people and is an excellent indicator how mature they are as a developer. I would encourage you to keep experimenting, simplifying your code and design by using less conditions. When I did this switch I found much less time debugging my code, it simply worked, then when I had to change something, changes were super easy to make since most of the code was sequential. Again I would encourage you 100% to keep doing what you are doing no matter what other people say. Keep in mind most developers are working and thinking at much lower level and just follow the rules. So good job bringing this up.

这篇关于避免if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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