Why Interfaces


Interfaces are a very powerful and very important feature in Java. Part of the key to solid design in Java is knowing when (and when not) to use interfaces. Used properly, interfaces help you compartmentalize your software to help minimize impacts on other parts of the code.

Interfaces provide higher levels of abstraction. The sort code doesn't need to know any details about the objects it is sorting. It need not know whether it is sorting Student objects, Customer objects, or Strings. All the sort code needs to know is that the objects it is sorting support being compared to other objects. The sort code knows only about this more abstract quality, not any other specifics of the objects it is sorting.

You can view this concept of abstracting sortability as a way to eliminate duplication. Interfaces allow a sort algorithm to operate on objects of different base types. The sort algorithm needs no repetitive code to determine the types of objects it compares.

Use interfaces to provide abstraction layers in your system and to help remove duplication.


The abstraction layers in your system isolate your code from negative effects. Ideally, you write the sort class once, get it to work perfectly, and then close it off to any future changes. The only detail the sort class has to know about the objects it sorts is that they respond to the compareTo method by returning an int. The classes of those objects can change in other myriad ways, but none of these changes will ever impact your sort code.

You can use interfaces can break dependencies on code that doesn't work or doesn't even exist by writing stub code to meet the specifications of the interface. In Lesson 12, you will learn how to accomplish this using a technique known as mocking. Interfaces are an essential tool for effective testing.

By implementing the Comparable interface, the String class publicizes the fact that Strings can be compared for sort purposes. The String supplies code in the compareTo method to determine how String objects are compared.

In order to get the sort to work for the list of sessions, you must modify CourseSession to implement the Comparable interface.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net