简体   繁体   English

提供类型安全的方法有用吗?

[英]Is it useful to provide a type-safe method?

I'm designing the interface as follows: 我正在设计界面,如下所示:

public interface Parameters {

    public <T> T getValue(ParameterName pn, Class<T> valueType) throws ClassCastException;
}

An implementation is obligated to throw ClassCastException if the Class instance of the value to be returned is not an assignableForm of the Class passed as a parameter. 如果要返回的值的Class实例不是作为参数传递的ClassAssignableForm ,则实现必须抛出ClassCastException

Does it make sesnse? 它会引起感冒吗? It provides compile-time type-safety, but we can do the same with just explicit cast. 它提供了编译时的类型安全性,但是我们可以通过显式强制转换来做到这一点。

Or it's much better to declare just 或者最好只声明

public Object getValue(ParameterName pn)

leaving all class-cast issues to the client. 将所有类转换问题留给客户端。

I have used this form of API where I add the ability to convert the type to the one desired. 我使用了这种形式的API,在其中添加了将类型转换为所需类型的功能。 eg if it's a String but you need an Integer it will attempt to parse it. 例如,如果它是一个字符串,但是您需要一个整数,它将尝试解析它。

Otherwise, as you suggest you are not adding much that this method doesn't provide. 否则,如您建议的那样,您不会添加该方法没有提供的内容。

 public <T> T getValue(ParameterName pn);

This avoid needing an explicit cast. 这样可以避免显式强制转换。

It is a misunderstanding that you gain any compile-time type-safety by passing the Class object of the expected return type as a parameter. 误解是通过将预期返回类型的Class对象作为参数传递来获得编译时的类型安全。 If the client passes a Class of the wrong type the error will only get detected at runtime. 如果客户端传递了错误类型的Class ,则仅在运行时才会检测到错误。

But I think the design with a Class parameter has other advantages: 但是我认为带有Class参数的设计还有其他优点:

  • The parameters creates a natural place to document the behaviour of the method regarding the return type. 参数创建了一个自然的地方来记录有关返回类型的方法的行为。
  • You can write code in the method to check the Class parameter and provide a specific and meaningful error message if the user makes a mistake. 您可以在该方法中编写代码以检查Class参数,并在用户犯错时提供特定且有意义的错误消息。
  • It is very visible in the calling code and brings attention to the behaviour of the method. 它在调用代码中非常明显,并引起对方法行为的注意。

I can think of two disadvantages of that design: 我可以想到该设计的两个缺点:

  • The existence of the parameter might give users the impression that the parameter affects the return value of the method. 参数的存在可能给用户一种印象,即参数会影响方法的返回值。
  • It is more verbose than using an unrestricted generic return type as Peter suggests in his answer. 它比使用Peter在其回答中建议的无限制的通用返回类型更为冗长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM