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.

 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 38
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%.

Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity
Microsoft's Novell Investment Tops $340M
Fedora 10 Takes Shape
IBM Gives a Mobile Voice to Developers
Inadequate Tools Send Software Down the Drain
USB 3.0 One Step Closer to Reality
Would-Be Linux Contributors May Get a Leg Up

Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element
Setting Up and Running Subversion and Tortoise SVN with Visual Studio and .NET
Java/JRuby Developers, Say Open 'Sesame' to the Semantic Web
Interpreting Images with MRDS Services
DevXtra Editors' Blog: Executives Avoiding Cloud Computing in Droves
Q&A with James Reinders on the Intel Parallel Studio Beta Program
The Pros and Cons of Outsourcing Enterprise Emails

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