Loose coupling of classes

Loose coupling is the first step on the road that leads to true modular programming.
Any object-oriented system is made up of components interacting with each other.
They must be as independent as possible, or one change in the system can trigger cas-
cading changes.
Imagine one of your business services needs to notify other components that a new
user has been created. The following snippet illustrates a tightly coupled solution
(you should not do this!):
public class BusinessServiceImpl implements BusinessService {
private JmsNotifier jmsNotifier;
public void createUser(User user) {
...
jmsNotifier.notify("User created");
}
}
Why can the previous snippet be considered tightly coupled? The reason is that the
notification technology is concretely defined using the JmsNotifier property. This
tells us that the BusinessServiceImpl class can’t be used or even tested without a Java
Message Service (JMS) container. Reuse of the BusinessService with another type of
notification technology or even without notification at all wouldn’t be an easy task.
The BusinessServiceImpl class can easily be decoupled from the notification by
introducing a Notifier interface instead of using an implementation. The following
snippet shows this solution:
public class BusinessServiceImpl implements BusinessService {
private Notifier notifier;
public void createUser(User user) {
...
notifier.notify("User created");
}
}
In this snippet, the notification concept is embodied by the Notifier interface, without
any reference to the underlying technology. Thanks to this abstraction, the Busi-
nessServiceImpl can now easily be reused with any kind of notification (email, JMS,
and so on), the only requirement being to implement the Notifier interface. Fig-
ure 1.1 shows how we moved from a tightly coupled solution to a loosely coupled one.
Now in BusinessServiceImpl, the notification concept is a simple dependency.
The next problem is to assign the right Notifier implementation. This is where
dependency injection comes in and we let an external system assemble all the applica-
tion components.
Advertisements

About lorddisk

WebCenter Content, WebCenter Portal, WebCenter Sites,Weblogic, Identity and Access Management (IAM),SSO,OAM,OIM,OAAM,OUD, OPAM,OID, OVD ,Oracle API Gateway ,OBIEE,OEDQ, Oracle ADF, Oracle SOA,J2EE, CackePHP ,PHP,J2SE,J2EE,Spring,Hibernate,JQuery,CSS,Java Script ,Joomla,Drupal,Worpress
This entry was posted in java. Bookmark the permalink.

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