Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class level annotations vs interfaces

I am looking at some code where class level annotations are used to 'add' properties to certain classes, later using reflection these properties are accessed and used.

My question: When is it appropriate to use an annotation to add new fields to a class, instead of using an interface. What are some benefits and drawbacks to this?

like image 703
mkoryak Avatar asked Feb 10 '10 04:02

mkoryak


1 Answers

I don't know that annotations would ever replace an interface, but I can kind of see the allure. It all depends on the implementations though.

Annotations provide meta data to further describe code, which a consumer (most of the time) interprets at runtime using reflections. Using an interface, this contract of implementation is clearly defined.

You could have:

interface CrudDao<T> {
   Serializable create(T t);
   T read(Serializable id);
   void update(T t);
   void delete(T t);
}

This would be a cumbersome contract to implement, and would likely incur some sort of method chaining.

Instead you could do something like:

class SomeDao {

   @Create
   long create(SomeEntity e) { // code }

   @Read
   SomeEntity read(long id) { // code }

   @Update
   void update(SomeEntity e) { // code }

   @Delete
   void delete(SomeEntity e) { // code }
}

The drawback is that it would be cumbersome to use:

class CrudFactory {
    long create(Class clazz, Object obj) {
       // loop through methods
       // find method with @Create
       // call method
    }    
}

Annotations in this example would be overkill a majority of the time, IMO. There is something to be said about a clearly defined, well documented contract.

like image 100
Droo Avatar answered Oct 19 '22 03:10

Droo