Re: why program to interface is better design?
- From: "H. S. Lahman" <h.lahman@xxxxxxxxxxx>
- Date: Thu, 29 Sep 2005 21:05:12 GMT
Responding to Jrefactors...
Is this an example of program to interface? 1) Transaction t = new BankTransaction();
The following only uses the concrete class without the interface 2) BankTransaction t = new BankTransaction();
Note that this is an interface as well; it is just a different one than Transaction that <presumably> allows access to additional properties of BankTransaction in addition to the deposit property. Think of BankTransaction as the default interface for the BankTranasction class where one has access to all of its public properties.
Is (1) a better choice than (2)? Why is that? (2) and (1) yield the same output.
It depends upon what you need to do. If you need to limit access to BankTranasction properties, then the Transaction interface is the way to go. That is pretty much what programming to interface is about. When programming one limits access to the object on a need-to-know basis using interfaces. For example,...
public interface Transaction { public void deposit(double amt); } public class BankTransaction implements Transaction { private double balance = 100; public void deposit(double amt) { balance += amt; } }
This example would be better with:
public class BankTransaction implements Transaction
{
public void deposit (double amt) {...}
public void witdrawal (double amt) {...}
}Now a client with either of your instantiation lines can access the t.deposit property. But your first line's client cannot access t.withdrawal while the second line's client can. Effectively you are controlling what the client can do by providing different, context-dependent interface access for the BankTransaction object.
************* There is nothing wrong with me that could not be cured by a capful of Drano.
H. S. Lahman hsl@xxxxxxxxxxxxxxxxx Pathfinder Solutions -- Put MDA to Work http://www.pathfindermda.com blog: http://pathfinderpeople.blogs.com/hslahman (888)OOA-PATH
.
- Prev by Date: Re: Abstract factory pattern
- Next by Date: Re: Factory pattern and building object
- Previous by thread: Abstract factory pattern
- Index(es):