Refactoring To Reuse #1

#1 Decouple connectivity from business logic

Often times you have a class that has a mixture of logic that is core or central to it and extraneous ones. A classic case is when you have a class that does calculations and also connects to a file or database. This isn’t bad per se because it probably works. But it inhibits reuse of both the calculation logic and the connectivity logic. One way to refactor the original class is to split it into 3 classes: a controller class, a connectivity class, and a calculation class. The controller is lightweight and co-ordinates the work across the other two classes. The connectivity class encapsulates file or database connectivity, and the calculation class executes a specific algorithm.

Here is an example – say you have a class named DiscountCalculator that accesses customer data from a database, and finds the ones that qualify for a particular promotional discount. You introduce a class named DBUtility that gets/closes a database connection, executes queries etc. I would advise against building such a class since good ones already exist. For example, if you use java, a better idea would be use Spring’s JDBCSupport and JDBCTemplate classes to achieve this. Now you can create a simple object (e.g. a plain old java object – POJO) that is returned from the database queries. The DiscountCalculator class can encapsulate the business logic within it or if you need to support multiple types of discountss you can consider introducing the Strategy design pattern. Whatever you decide, you can remove the database related logic from DiscountCalculator and keep it flexible for new types of discount calculations. In the same vein, the POJO is reusable as well for additional classes.

Like this post? Subscribe to RSS feed or get blog updates via email.

add to del.icio.us: Digg it : post to facebook: Stumble It! : :

Advertisements

One Response to Refactoring To Reuse #1

  1. […] Also common are formatting logic that is specific to a business channel or view. I talked about decoupling connectivity earlier so in this post I will expand on formatting logic. Just like any other aspect of your design you […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: