Java API 设计:方法中的窄返回类型 [英] Java API design: narrow return type in methods

查看:21
本文介绍了Java API 设计:方法中的窄返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类型族,我在基类型中定义了一组方法:

Suppose I have a type family, I have defined a set of methods in base type:

interface Foo<T> {
   Foo<T> a();
   Foo<T> b();
   ...
}

Bar 扩展 Foo

interface Bar<T> extends Foo<T> {
   Bar<T> a();
   Bar<T> b();
   ...
}

然后 Zee 扩展 Bar

interface Zee<T> extends Bar<T> {
   Zee<T> a();
   Zee<T> b();
   ...
}

当我用不同的装饰器实现这个类型家族时,我发现我经常写一些类似的东西

When I implement this type family with different decorators, I found I constantly write something like

class XBar<T> extends XFoo<T> implements Bar<T> {
   Bar<T> a() {
      return (Bar<T>)super.a();
   }
   Bar<T> b() {
      return (Bar<T>)super.b();
   }
   ...
}

真的很累.我想知道这是 Java API 设计中的正常情况还是我做错了什么,或者有一种聪明的方法可以用一行代码来解决常量类型转换?

It is really tedious. I am wondering is this normal case in Java API design or I did something wrong, or there is sort of smart way to workaround the constant typecast with one line of code?

更新,为了回答您的评论和回复,是的,方法链是我想在这里实现的一件事.顺便说一句,Java8 中的 BaseStream 类型声明是解决这个问题的一个很好的例子.我正在尝试使用这种方法.将在此处更新我的进度.

Updates, To answer your comments and response, yes, method chain is one thing I want to achieve here. BTW looks like the BaseStream type declaration in Java8 is a good example of addressing this problem. I am trying to use that approach. Will update my progress here.

更新 2,当我有多个继承级别时,BaseStream 方法不起作用.参见 Java 继承 Fluent 方法在多级层次结构中的返回类型

Updates 2, The BaseStream approach doesn't work when I have multiple inheritance levels. See Java inherited Fluent method return type in multiple level hierarchies

推荐答案

为什么你的子类需要返回子类类型?

Why do your subclasses need to return the subclass type?

Liskov 替换原则 指出对象可以被子类型替换而不改变任何属性,因此如果如果您正确地编写了类代码,那么您就不需要演员表,特别是如果您只是从 super 返回结果.

The Liskov Substitution Principle states that objects can be replaced by subtypes without altering any properties so if you code your classes correctly, then you don't need the cast especially if you are just returning the result from super.

当您需要在链接期间访问额外的子类方法时,我能想到的唯一一次是方法链接(如 builder 模式)......但这应该很少见.

The only time I can think of that has this problem is method chaining (like builder pattern) when you need to access extra subclass methods during the chaining... But that should be rare.

这篇关于Java API 设计:方法中的窄返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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