DEV Community

loading...

Discussion on: Effective Java! Use Marker Interfaces to Define Types

Collapse
kylec32 profile image
Kyle Carter Author

I definitely agree that interfaces most often are used to define a contract and it does muddie the waters to use them as marker interfaces. I think the author is simply pointing out that marker interfaces do have interesting attributes that annotations don't give you, namely compile time checking vs runtime checking. While I personally have never used an interfaces this way it is an interesting attribute of marker interfaces, and one that can be weighed against the shortcomings of the pattern as well.

Collapse
nfrankel profile image
Nicolas Frankel

Can you please provide a concrete example of this advantage?

Thread Thread
kylec32 profile image
Kyle Carter Author

Sure. For example if my method takes a Set. Set adds nothing new to the Collection interface other than some JavaDoc changes in my reading of the two interfaces. If I wanted to force the implementation of Set that would mean I don't require anything above a Collection interface but I could enforce that implementation detail at compile time.

As stated above the ObjectOutputstream.writeObject method is a missed opportunity for forcing at at compile time compliance in that only objects that implement Serializable can successfully be processed by this method. Of course these classes were added to Java before annotations so they can't use annotations. However, they act the same way that annotations would act today (checked at runtime). The author is pitching that if the original designer would have made the method take Serializable rather than Object it would be slightly easier to work with the method and more self documenting.

Thread Thread
nfrankel profile image
Nicolas Frankel

I'll focus on Serializable, because Set cannot be replaced by annotation. Worse, its "contract" is enforced by nothing.

Regarding Serializable, it should be the class that offers the writeObject() method. It should also be a default method, just as List.sort() is. For the whole rationale behind default methods, please check this post.