Separate APIs for Clients and Providers
From APIDesign
(Removing all content from page) |
(Question about Writer) |
||
Line 1: | Line 1: | ||
+ | === The Writer === | ||
+ | This chapter analyses the Writer example. Do you know that in JDK 1.5 new methods has been added into the Writer class to work with CharSequences? Of course, they could not be left abstract, as that would not be compatible. They needed some implementation. Of course, there are multiple choices to use. So, which one would you choose? | ||
+ | |||
+ | <source lang="java" snippet="writer.throw"/> | ||
+ | |||
+ | Possible, but useless, for clients calling the Writer.append method. They would always have to code very defensively, as shown here: | ||
+ | |||
+ | <source lang="java" snippet="writer.throw.client"/> | ||
+ | |||
+ | Of course, this is a very horrible API. You want to guarantee to clients calling into Writer that reasonable implementation of the append method is provided: | ||
+ | |||
+ | <source lang="java" snippet="writer.super"/> | ||
+ | |||
+ | This looks good, as clients can always rely on the append method to be implemented. Even by writers written against JDK 1.4 version of the Writer. This is not bad, however it is also not very efficient, as it always converts the whole CharSequence to String. In case of big sequences, like onces representing whole CD, this is a way to ask for OutOfMemoryErrors: | ||
+ | |||
+ | <source lang="java" snippet="writer.countcd"/> | ||
+ | |||
+ | There must be more effective way to do this! Yes, it is. Please read the chapter 8 of [[TheAPIBook]] to learn what to do and how to prevent situations like this. |
Revision as of 11:03, 7 July 2008
The Writer
This chapter analyses the Writer example. Do you know that in JDK 1.5 new methods has been added into the Writer class to work with CharSequences? Of course, they could not be left abstract, as that would not be compatible. They needed some implementation. Of course, there are multiple choices to use. So, which one would you choose?
does not exists: writer.throw
Possible, but useless, for clients calling the Writer.append method. They would always have to code very defensively, as shown here:
does not exists: writer.throw.client
Of course, this is a very horrible API. You want to guarantee to clients calling into Writer that reasonable implementation of the append method is provided:
does not exists: writer.super
This looks good, as clients can always rely on the append method to be implemented. Even by writers written against JDK 1.4 version of the Writer. This is not bad, however it is also not very efficient, as it always converts the whole CharSequence to String. In case of big sequences, like onces representing whole CD, this is a way to ask for OutOfMemoryErrors:
does not exists: writer.countcd
There must be more effective way to do this! Yes, it is. Please read the chapter 8 of TheAPIBook to learn what to do and how to prevent situations like this.