DEV Community

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

Collapse
 
nfrankel profile image
Nicolas Frankel

Can you please provide a concrete example of this advantage?

Thread Thread
 
kylec32 profile image
Kyle Carter

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.