我正在阅读开发人员的最佳实践,发现一个建议是
使界面易于正确使用而难以错误使用
任何人都可以用最少的示例代码来描述以了解其原理。我试图在互联网上搜索,但未找到任何示例。
class Account{
void process(){}
}
interface IBankAccountService {
boolean check(Account acc);
void process(Account acc);
}
class ScbAccountService implements IBankAccountService {
@Override
public boolean check(Account acc) {
return true; // check account consistency
}
@Override
public void process(Account acc) {
acc.process(); // proceed operation
}
}
上面的例子是否违反了原则?我想如何在本示例中应用这一原理。
答案 0 :(得分:2)
简单的答案:您不容易做到。您必须使系统中的不同类型以一种或另一种方式依赖。在我的第一个示例中,我在perform
方法中使用了一个异常,以表示如果调用perform
可能发生可怕的事情。这需要实现。
interface Account {
double getBalance();
/**
* Indicates if an order can be performed by the account.
*
* @retrun {@code true} if the balance is bigger than the order's amount, {@code false} else.
*/
boolean canPerform(Order order);
/**
* @param order The order to apply.
* @throws Exception when the amount of the order is higher than the value returned by #getBalance.
*/
boolean perform(Order order) throws Exception;
}
interface Order { double getAmount(); }
interface Transaction { boolean transact(Account account, Order order) }
为依赖项建模的另一种方法,可以避免发生异常,并在调用Transaction
时(希望)产生新的perform
实例:
interface Account {
double getBalance();
/**
* @param order The order to apply.
* @throws Exception when the amount of the order is higher than the value returned by #getBalance.
*/
Transaction perform(Order order);
}
interface Order { double getAmount(); }
interface Transaction { TransactionState getState(); }
enum TransactionState { SUCCESS, ERROR }