将控制流/条件基于对象的类进行设计是否不好? [英] Is it bad design to base control flow/conditionals around an object's class?

查看:59
本文介绍了将控制流/条件基于对象的类进行设计是否不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究Rails项目,并且发现最容易做到的时间

I'm currently working on a Rails project, and have found times where it's easiest to do

if object.class == Foo
  ...
else if object.class == Bar
  ...
else
  ...

我开始在需要以不同方式显示不同对象的视图中执行此操作,但是现在发现自己在其他地方使用了它,例如在将对象作为参数的函数中.我不确定为什么,但是我觉得这不是一个好习惯.

I started doing this in views where I needed to display different objects in different ways, but have found myself using it in other places now, such as in functions that take objects as arguments. I'm not precisely sure why, but I feel like this is not good practice.

如果不是很好的做法,为什么呢?

If it's not good practice, why so?

如果完全可以的话,什么时候可能要专门使用它呢?

If it's totally fine, when are times that one might want to use this specifically?

谢谢!

推荐答案

完全不确定为什么对您有用.当需要测试object是否为类Foo的实例时,应使用

Not sure why that works for you at all. When you need to test whether object is instance of class Foo you should use

object.is_a? Foo

但是在Ruby中,这并不是一个好习惯.尽可能使用多态性要好得多.例如,如果在代码中的某个地方可以具有两个不同类的对象,并且需要以不同的方式显示它们,则可以在两个类中定义display方法.之后,您可以调用object.display,然后将使用相应类中定义的方法来显示对象.

But it's not a good practice in Ruby anyway. It'd much better to use polymorphism whenever it's possible. For example, if somewhere in the code you can have object of two different classes and you need to display them differently you can define display method in both classes. After that you can call object.display and object will be displayed using method defined in the corresponding class.

该方法的优点是,当您需要增加对第三类或一堆新类的支持时,您需要做的就是在每个类中定义display方法.但是,在您实际使用此方法的地方,什么都不会改变.

Advantage of that approach is that when you need to add support for the third class or a whole bunch of new classes all you'll need to do is define display method in every one of them. But nothing will change in places where you actually using this method.

这篇关于将控制流/条件基于对象的类进行设计是否不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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