Interesting patterns: Marker interface

Some time ago I got my friend’s code to review. Nothing special. After a few minutes of reading, I noticed that he added an empty interface to the definition of some classes. I was ready to write a comment about it but I heard a voice in my head to ask Google first.

I’ve discovered something interesting. A long time ago, when Java 1.5 was not yet released and annotations were not available in the language it was common to use something called “marker interface”. What is marker interface?

Marker interface is an empty interface. Its goal is just to let us know about something. That’s all. No methods or fields. Annotations are more complex because they may have parameters, marker interface doesn’t. I’ll explain it to you in an example.

Imagine that you have a REST API which always returns JSON documents in his response. Sometime in your application, you throw an exception. Some exceptions’ message should be displayed to end user and some of them shouldn’t. If the message should be hidden from the user, you show a generic text like ‘Internal server error’.

Implementation of it is very simple

interface UserFriendlyException {}
class Exception implements UserFriendlyException {}

somewhere in a listener which catches all uncaught exceptions, you may have code similar to the above.

<?php if ($exception implements UserFriendlyException) {
    $response.setMessage($exception->getMessage());
} else {
    $response.setMessage("Internal server error");
}

An advantage of the solution is that all exceptions are hidden by default. You have to mark precisely the exceptions you want to show to end user.

 

Do you know any other interesting or tricky patterns that you wanted to share with others? Let us know about them in the comments. Cheers.

Hi, I'm Bartek, founder of this blog. I am a developer since 2011. I love learning by teaching other people and this is my motivation for creating this website.
Posts created 16

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top