SPECIAL CASE PATTERN (Fowler)

Most of the time, we would throw an exception to handle an unexpected behavior. In some cases, if the caller code does not want to handle that error and follow a default approach, then we can use “Special Case Pattern”. Refer the below example to know how to do that.

Assume that we have class “BillingDao” contains methods to fetch the billing details of an employee. “getBillingDetails” is a method returns the billing details of an employee by his/her company name. Assume that if it does not find the billing details, then it will throw “BillingDetailsNotFoundException “. So the client code has to handle that scenario. We can refactor this code with “Special Case Pattern”


float rate = 0.0f
try {
  BillingDetails billingDetails= billingRateDao.getBillingDetails(employee.getCompany());
  rate+= billingDetails.getRate();
} catch(BillingDetailsNotFoundException e) {
  rate += getDefaultBillingRate()
}

We will create a new class “DefaultBillingDetails” which implements “BillingDetails” and we can specify the default billing details in it.
Then we can update the “BillingRateDAO” to return the instance of DefaultBillingDetails instead of throwing an exception. I have not given the BillingRateDAO code here but assume that it return an instance of DefaultBillingDetails.

The modified code will look like below.


BillingDetails billingDetails= billingRateDao.getBillingDetails(employee.getCompany());
  rate+= billingDetails.getRate();
....
.....
public class DefaultBillingDetails implements BillingDetails {
 public int getRate() {
 // return the per default rate
 }
}