advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Coupling and Cohesion: The Two Cornerstones of OO Programming :

A Concrete Example

Listing 1 defines an Order class to which you can apply the LCOM metrics. Figure 1 displays a high-level UML model of an imaginary Order Processing system.


Figure 1:
This shows a UML class diagram for an Order Processing Sytem.

Note: The example UML diagram and the source code below is just an example and present a very much rough code sample. Please do not try to reuse this class for any real project.

To apply the LCOM3 metric to the Order class, define the metric variables as follows:


m(number of methods in the class) = 4
a(number of attributes in the class)=5

m[prod] = number of methods accessing the attribute prod = 3

m[orderNumber] = number of methods accessing the attribute orderNumber= 2

m[totalAmount] = number of methods accessing the attribute totalAmount = 4

m[deliveryType] = number of methods accessing the attribute deliveryType = 2

m[underPromotion] =number of methods accessing the attribute underPromotion=3
Therefore:

LCOM3 = ( m - sum(mA)/a ) / (m - 1)
             
             = ( 4 - 14/5 ) / (4-1)
         
             = 0.73
Remember to also count the constructor as a method of the class in this calculation.

The LCOM analysis on the Order class revealed that it had a reasonably high level of non-cohesiveness. Although, it is not "alarming" (as values >1 would be alarming according to LCOM3), you would be wise to improve its design.

A little inspection of all the methods in the class will immediately reveal that the method checkIfProductExists() is not a good fit for this class. The Order class must encapsulate the behaviours that an Order will need to exhibit. Basically, assume that when an instance of Order is created, the product within it is a valid and existing product. The responsibility of assigning a valid product to the Order object is better placed as part of the OrderManager class.

After removing the checkIfProductExists() method from the Order class, recalculate the value of LCOM3:


m(number of methods in the class) = 3
a(number of attributes in the class)=5
Therefore:

LCOM3 = ( m - sum(mA)/a ) / (m - 1)
             
             = ( 3 - 13/5 ) / (3-1) ***Note: sum(mA) is now reduced by one.
         
             = .20
This class is now more cohesive, with an LCOM value of 0.20—compared to the previous value of 0.73. That simple change made a world of difference in peace of mind.

Measuring Coupling

Coupling is a word that's usually used in a derogatory manner in design review meetings. Even so, it's not possible to design a functional OO application without coupling. Whenever one object interacts with another object, that is a coupling. In reality, what you need to try to minimise is coupling factors. Strong coupling means that one object is strongly coupled with the implementation details of another object. Strong coupling is discouraged because it results in less flexible, less scalable application software. However, coupling can be used so that it enables objects to talk to each other while also preserving the scalability and flexibility.

Though this seems like a difficult task, OO metrics can help you to measure the right level of coupling.

  • Coupling Between Objects (CBO): CBO is defined as the number of non-inherited classes associated with the target class. It is counted as the number of types that are used in attributes, parameters, return types, throws clauses, etc. Primitive types and system types (e.g. java.lang.*) are not counted.
  • Data Abstraction Coupling (DAC): DAC is defined as the total number of referred types in attribute declarations. Primitive types, system types, and types inherited from the super classes are not counted.
  • Method Invocation Coupling (MIC): MIC is defined as the relative number of classes that receive messages from a particular class.
    
    MIC = nMIC / (N -1 )
    
    Where N = total number of classes defined within the project.
    nMIC = total number of classes that receive a message from the target class.
    

Demeter's Law

Ian Hollaand first proposed the Law of Demeter. The class form of Demeter's Law has two versions: a strict version and a minimization version. The strict form of the law states that every supplier class of a method must be a preferred supplier. The minimization form is more permissive than the first version and requires only minimizing the number of acquaintance classes of each method.
  • Definition 1 (Client): Method M is a client of method f attached to class C, if inside M message f is sent to an object of class C, or to C. If f is specialized in one or more subclasses, then M is only a client of f attached to the highest class in the hierarchy. Method M is a client of some method attached to C.In Listing 1, the constructor of the Order class is a client to the Product class because it calls the getPrice() method of the Product class.
  • Definition 2 (Supplier): If M is a client of class C then C is a supplier to M. In other words, a supplier class to a method is a class whose methods are called in the method. In Listing 1, the Product class is a supplier class to the client class Order.
  • Definition 3 (Acquaintance Class): A class C1 is an acquaintance class of method M attached to class C2, if C1 is a supplier to M and C1 is not one of the following:
    • The same as C2;
    • A class used in the declaration of an argument of M
    • A class used in the declaration of an instance variable of C2
    In Listing 1, Product is an acquaintance class of the Order class, because Product is declared as an instance variable of the Order class and also passed as an argument to the constructor.
  • Definition 4 (Preferred-supplier class): Class B is called a preferred-supplier to method M (attached to class C) if B is a supplier to M and one of the following conditions holds:
    • B is used in the declaration of an instance variable of C
    • B is used in the declaration of an argument of M, including C and its superclasses
    • B is a preferred acquaintance class of M.
In Figure 1, the OrderLine, Order class is a preferred supplier class to the OrderManager class as they are used as instance variables inside the OrderManager class.

A Concrete Example

In the imaginary Order Processing example, imagine you've got the following form of code in the OrderManager class.

Class OrderManager {

 Private Order order;

public void getOrderByCustomer() {

     int productPrice = order.prod.price

}
You can see that the Product class becomes a supplier to the OrderManager class. This is not allowed according to the strict form of Demeter law because Product is not a preferred supplier to the OrderManager class.

Try the following:


Class OrderManager {

  Private Order order;

public void getOrderByCustomer() {

     int productPrice = order.getProductPrice();
}
Note that the above code makes the assumption that OrderManager will deal with only one Order at one time and also that one Order can have only one Product.

In the modified code, the client OrderManager class does not need to know how the object model is between Order and Product. Also, you never used or initialised the Product class within the OrderManager class. Having to reference to the Product class indirectly to get the price is a violation of Demeter Law.

Figure 2 presents a corrected UML diagram with all the changes that have been made so far.
Figure 2:
The corrected UML diagram.

What It All Adds Up To

All these coupling metrics really serve the same function: to reduce dependencies between several classes. The less dependency, the better the chance of a more flexible solution. But in OO programming, coupling is unavoidable. Therefore, the goal is to reduce unnecessary dependencies and make necessary dependencies coherent. In this article's example, the OrderManager class is still coupled to the OrderLine and Order classes, but its unnecessary coupling with the Product class has been eliminated.

Make no mistake, these metrics are vital to measuring the quality of an application.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 DevX Skillbuilding from IBM developerWorks
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 48
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Apple Details iPhone/Mac Developer Event
RIM Ups Ante With Mobile Software Push
Novell Readies Silverlight Clone for Linux
Yahoo Pitches The 'Next Generation of Search'
Alfresco's Latest ECM: Prying Open a Sector?
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads for the JON 2.0
Out with the Old, in with the New at JavaOne

Create Secure Java Applications Productively, Part 1: Use Rational Application Developer and Data Studio
.NET Building Blocks: Custom User Control Fundamentals
Secure Internet File-Sharing with PHP, MySQL, and JavaScript
Getting Started with TBB on Windows
Moving to VoIP: Should You Go It Alone?
Introduction to the WPF Command Framework
7.0, Microsoft's Lucky Version?
Will Hyper-V Make VMware This Decade's Netscape?
Eliminate Fragmentation Frustration with Netbiscuits
Taming Trees: Building Branching Structures

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES