Pages

Wednesday, April 4, 2012

The use of marker interfaces

When programming, we often use interfaces, to hide the realization. But in some occasions, we want just want to group classes. We call marker interfaces, to empty interfaces(No methods at all). 

A very simple example is the Serializabe interface: 
It has no methods at all, but all classes that whant to be writen into some kind of file, or network stream, need to implement Serializable. 

In the same way, you could make a Program with classes like Dog,Bird,Cow... and you dont need to add them any functionality extra, just to mark them, because somewhere in the code there will be a method that could look like this : String method(Flyer); So you need to create a marker interface called Flyer, to mark the animals that can fly(So you dont need to have unnecesary variables boolean like isFlyer, in classes Dog and Cow). 




maybe i should give a more pragmatical example, so it is easier to understand. Lets try:

See the folowing code:

1:  //Marking interface flyer  
2:  public interface Flyer {  
3:  //If this is a marker interface, there is no methods in it  
4:  }  
5:  public class Mammal {  
6:  private String someVariable;  
7:  }  
8:  public class Cow extends Mammal {  
9:  //Some code specific to cows  
10:  }  
11:  public class Bat extends Mammal implements Flyer {  
12:  //Some code specific to Mammal  
13:  //Note that the Bat is marked as a Flyer  
14:  }  



I think this example more or less explains my point. Bats are mammals and can fly,so why would you have a boolean variable that can be either true or false, when you can just mark the class. Another reason why i think this is a good approach, i because if the future we need to upgrade the program, we can just mark the classes that can fly with the interface.

Imagine somewhere in the program there is a method like this:

1:  public class AirportControl {  
2:  public void testFly(Animal a) {  
3:  if(a instanceof Flyer) {  
4:  //Perform a test fly  
5:  }  
6:  public void testFly(Vehicle v) {  
7:  if(a instanceof Flyer) {  
8:  //Perform a test fly  
9:  }  
10:  }  


I think this approach is pretty flexible,when creating your domain model.

No comments:

Post a Comment

Share with your friends