This article was originally translated by Xiaofeng from MaNong.com. Please read the reprint requirements at the end of the article for reprinting. Welcome to participate in our paid contribution plan!
Anyone who writes Java code is an API designer! Regardless of whether the coder shares the code with others, the code is still used: either by others, by themselves, or both. Therefore, it is important for all Java developers to understand the basics of good API design.
A good API design requires careful thinking and a lot of experience. Fortunately, we can learn from other, smarter people like Ference Mihaly, whose blog inspired me to write this Java 8 API addendum. When designing the Speedment API, we relied heavily on his list of interfaces. (I recommend you read his guide.)
It’s important to do this from the beginning, because once the API is released, it will become a solid foundation for everyone who uses the API. As Joshua Bloch once said: "Public APIs, like diamonds, last forever. If you have a chance to do it right, you should try your best to do it."
A well-designed API combines the two The essence of this world is both a solid and precise foundation and a high degree of implementation flexibility, ultimately benefiting API designers and API users.
As for why we need to use the interface list? Getting the API right (that is, the visible part that defines a collection of Java classes) is much more difficult than writing the implementation classes that make up the actual work behind the API. It's an art that really few people master. Using an interface checklist allows readers to avoid the most obvious mistakes, become a better programmer, and save a lot of time.
It is strongly recommended that API designers put themselves in the perspective of client code and optimize this view for simplicity, ease of use, and consistency - rather than thinking about the actual API implementation. At the same time, they should try to hide as many implementation details as possible.
It can be proven that inconsistent null handling (leading to the ubiquitous NullPointerException) is the largest Java application error in history the only source. Some developers regard the introduction of the null concept as one of the worst mistakes made in computer science. Fortunately, the first step towards mitigating Java's null handling problems was the introduction of the Optional class in Java 8. Make sure that methods with a null return value return Optional instead of null.
This clearly indicates to API users that the method may or may not return a value. Don't be tempted to use null instead of Optional for performance reasons. Anyway, Java 8's escape analysis will optimize away most Optional objects. Avoid using Optional in parameters and fields.
You can write like this
public Optional<String> getComment() { return Optional.ofNullable(comment); }
instead of like this
public String getComment() { return comment; // comment is nullable }
When the Enum concept was introduced in Java 5, a major API error occurred. We all know that the Enum class has a method called values(), which returns an array of all different Enum values. Now, because the Java framework must ensure that client code cannot change the value of an Enum (for example, by writing directly to the array), a copy of the internal array must be made for each call to the value() method.
This results in poor performance and poor client code usability. If an Enum returns an unmodifiable List that can be reused on every call, then client code has access to a better and more useful model of Enum values. In general, if an API returns a set of elements, consider exposing a Stream. This clearly illustrates that the result is read-only (as opposed to a List which has a set() method).
It also allows client code to easily collect elements from another data structure or operate on them on the fly. Additionally, the API can lazily generate elements as they become available (e.g., pulled from a file, socket, or from a database). Likewise, Java 8's improved escape analysis will ensure that the fewest objects are actually created on the Java heap.
Also do not use arrays as input arguments to methods because - unless a protective copy of the array is created - it is possible for another thread to modify the contents of the array during method execution.
You can write like this
public Stream<String> comments() { return Stream.of(comments); }
instead of like this
public String[] comments() { return comments; // Exposes the backing array! }
避免允许客户端代码直接选择接口的实现类。允许客户端代码创建实现类直接创建了一个更直接的API和客户端代码的耦合。它还使得API的基本功能更强,因为现在我们必须保持所有的实现类,就像它们可以从外部观察到,而不仅仅只是提交到接口。
考虑添加静态接口方法,以允许客户端代码来创建(可能为专用的)实现接口的对象。例如,如果我们有一个接口Point有两个方法int x() 和int y() ,那么我们可以显示一个静态方法Point.of( int x,int y) ,产出接口的(隐藏)实现。
所以,如果x和y都为零,那么我们可以返回一个特殊的实现类PointOrigoImpl(没有x或y字段),否则我们返回另一个保存给定x和y值的类PointImpl。确保实现类位于另一个明显不是API一部分的另一个包中(例如,将Point接口放在com.company。product.shape中,将实现放在com.company.product.internal.shape中)。
你可以这样写
Point point = Point.of(1,2);
而不要这样写
Point point = new PointImpl(1,2);
出于好的原因,对于任何给定的Java类,只能有一个超类。此外,在API中展示抽象或基类应该由客户端代码继承,这是一个非常大和有问题的API 功能。避免API继承,而考虑提供静态接口方法,采用一个或多个lambda参数,并将那些给定的lambdas应用到默认的内部API实现类。
这也创造了一个更清晰的关注点分离。例如,并非继承公共API类AbstractReader和覆盖抽象的空的handleError(IOException ioe),我们最好是在Reader接口中公开静态方法或构造器,接口使用Consumer
你可以这样写
Reader reader = Reader.builder() .withErrorHandler(IOException::printStackTrace) .build();
而不要这样写
Reader reader = new AbstractReader() { @Override public void handleError(IOException ioe) { ioe. printStackTrace(); } };
使用@FunctionalInterface注解标记的接口,表示API用户可以使用lambda实现接口,并且还可以通过防止抽象方法随后被意外添加到API中来确保接口对于lambdas保持长期使用。
你可以这样写
@FunctionalInterface public interface CircleSegmentConstructor { CircleSegment apply(Point cntr, Point p, double ang); // abstract methods cannot be added }
而不要这样写
public interface CircleSegmentConstructor { CircleSegment apply(Point cntr, Point p, double ang); // abstract methods may be accidently added later }
如果有两个或更多的具有相同名称的函数将功能性接口作为参数,那么这可能会在客户端侧导致lambda模糊。例如,如果有两个Point方法add(Function
你可以这样写
public interface Point { addRenderer(Function<Point, String> renderer); addLogCondition(Predicate<Point> logCondition); }
而不要这样写
public interface Point { add(Function<Point, String> renderer); add(Predicate<Point> logCondition); }
默认方法可以很容易地添加到接口,有时这是有意义的。例如,想要一个对于任何实现类都期望是相同的并且在功能上要又短又“基本”的方法,那么一个可行的候选项就是默认实现。此外,当扩展API时,出于向后兼容性的原因,提供默认接口方法有时是有意义的。
众所周知,功能性接口只包含一个抽象方法,因此当必须添加其他方法时,默认方法提供了一个安全舱口。然而,通过用不必要的实现问题来污染API接口以避免API接口演变为实现类。如果有疑问,请考虑将方法逻辑移动到单独的实用程序类和/或将其放置在实现类中。
你可以这样写
public interface Line { Point start(); Point end(); int length(); }
而不要这样写
public interface Line { Point start(); Point end(); default int length() { int deltaX = start().x() - end().x(); int deltaY = start().y() - end().y(); return (int) Math.sqrt( deltaX * deltaX + deltaY * deltaY ); } }
在历史上,人们一直草率地在确保验证方法输入参数。因此,当稍后发生结果错误时,真正的原因变得模糊并隐藏在堆栈跟踪下。确保在实现类中使用参数之前检查参数的空值和任何有效的范围约束或前提条件。不要因性能原因而跳过参数检查的诱惑。
JVM能够优化掉冗余检查并产生高效的代码。好好利用Objects.requireNonNull()方法。参数检查也是实施API约定的一个重要方法。如果不想API接受null但是却做了,用户会感到困惑。
你可以这样写
public void addToSegment(Segment segment, Point point) { Objects.requireNonNull(segment); Objects.requireNonNull(point); segment.add(point); }
而不要这样写
public void addToSegment(Segment segment, Point point) { segment.add(point); }
Java 8的API设计师犯了一个错误,在他们选择名称Optional.get()的时候,其实应该被命名为Optional.getOrThrow()或类似的东西。调用get()而没有检查一个值是否与Optional.isPresent()方法同在是一个非常常见的错误,这个错误完全否定了Optional原本承诺的null消除功能。考虑在API的实现类中使用任一Optional的其他方法,如map(),flatMap()或ifPresent(),或者确保在调用get()之前调用isPresent()。
你可以这样写
Optional<String> comment = // some Optional value String guiText = comment .map(c -> "Comment: " + c) .orElse("");
而不要这样写
Optional<String> comment = // some Optional value String guiText = "Comment: " + comment.get();
最后,所有API都将包含错误。当接收来自于API用户的堆栈跟踪时,如果将不同的接口分割为不同的行,相比于在单行上表达更为简洁,而且确定错误的实际原因通常更容易。此外,代码可读性将提高。
你可以这样写
Stream.of("this", "is", "secret") .map(toGreek()) .map(encrypt()) .collect(joining(" "));
而不要这样写
Stream.of("this", "is", "secret").map(toGreek()).map(encrypt()).collect(joining(" "));
以上就是Java 8 API 设计经验浅析 的内容,更多相关内容请关注PHP中文网(www.php.cn)!