类型检查是否正常? [英] Is type checking ever OK?

查看:124
本文介绍了类型检查是否正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使您正在检查接口,类型检查也被认为是不好的做法吗?我知道你应该总是编程到一个接口而不是一个实现 - 这是什么意思?

Is type checking considered bad practice even if you are checking against an interface? I understand that you should always program to an interface and not an implementation - is this what it means?

例如,在PHP中,以下是否可以?

For example, in PHP, is the following OK?

if($class instanceof AnInterface) {
   // Do some code
}

或者是否有更好的方法来改变基于类类型的代码行为?

Or is there a better way of altering the behaviour of code based on a class type?

编辑:为了清楚我正在讨论检查类是否实现接口,而不仅仅是它是某个类的实例。

Edit: Just to be clear I am talking about checking whether a class implements an interface not just that it is an instance of a certain class.

推荐答案

只要你遵循 LSP ,我没有看到问题。您的代码必须与接口的任何实现一起使用。只要您可以正确使用接口的任何实现,某些实现会导致您遵循不同的代码路径,这不是问题。

As long as you follow the LSP, I don't see a problem. Your code must work with any implementation of the interface. It's not a problem that certain implementations cause you to follow different code paths, as long as you can correctly work with any implementation of the interface.

如果您的代码不能与界面的所有实现一起使用,那么您不应该首先使用该界面。

If your code doesn't work with all implementations of the interface, then you shouldn't use the interface in the first place.

这篇关于类型检查是否正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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