You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 20 Next »

Several well-known adages in Object-oriented design suggest that the dependency structure of a package or module must never contain cycles, or in other words, must orchestrate a Directed Acyclic Graph (DAG).

There are several advantages of eliminating cycles between packages:

  • Testing and maintainability: It is preferable to make a change somewhere (or patch) and limit the repercussions to as few packages as possible (ideally just one) as opposed to having to monitor or refine numerous packages.
  • Reusability: When a new version of a package is released, clients who reuse it do not have to test their existing code bases for compatibility with other packages that this particular package depends on. Sometimes, the reusable package evolves only to accommodate the changes to packages that it depends on.
  • Releases and builds: Avoiding cycles also helps to steer the development towards an environment that fosters modularization. Owners of different packages are also redeemed from relying on other bleeding-edge packages.
  • Deployment: By resolving the cycles, deployment is simplified, as runtime errors like the infamous ClassNotFoundError, are reduced to a minimum by virtue of the toned down coupling between packages.

Noncompliant Code Example

This noncompliant code example features two different packages named Account and User that consist of the classes AccountHolderClass and UserClass, respectively. The class UserClass extends from AccountHolderClass because a user is a kind of account holder. The class AccountHolderClass depends on a few non-static utility methods defined in UserClass and must declare and use its instance. Likewise, the UserClass depends on AccountHolderClass but instead chooses to extend from it. This vicious circle is one recipe for a cyclic dependency.

package Account;
import User.*;
  class AccountHolderClass {
    private UserClass uc;  // Uses a class defined in package User
    protected synchronized void depositFunds(String username, double amount) {
      // Use a utility method of UserClass to check if username exists
      if(uc.exists(username)) { 
        // Deposit the amount
      } 
    }
    protected double getBalance(String accountNumber) { 
      // return the account balance 
    }
  }

package User;
import Account.*;
  class UserClass extends AccountHolderClass {
    protected synchronized double getUserBalance(String accountNumber) {
      // use a method of AccountHolderClass to get the account balance 
      return getBalance(accountNumber); 
    }
    public boolean exists(String username) { /* check whether user exists*/ }
  }

Compliant Solution

The tight coupling between the classes in the two packages can be weakened by introducing an interface called BankApplication in a third package, Bank. The cyclic dependency is eliminated by ensuring that the AccountHolderClass does not use an instance of UserClass, but instead relies on the interface by importing the Bank package. In this compliant solution, such functionality is achieved by adding a parameter of the interface type BankApplication to the depositFunds() method. This gives the AccountHolderClass a solid contract to bank upon. Additionally, UserClass implements the interface and provides concrete implementations of the methods while at the same time, inheriting the other methods from AccountHolderClass.

It might appear that the interface BankApplication contains superfluous methods such as depositFunds() and getBalance(). These methods are present so that if the subclass overrides them, the superclass retains the capability of internally invoking the subclass' methods polymorphically (such as calling ba.getBalance(), with an overridden implementation of the method in UserClass).

package Bank;
public interface BankApplication {   
  void depositFunds(BankApplication ba, String username, double amount);
  double getBalance(String accountNumber);
  double getUserBalance(String accountNumber);
  boolean exists(String username); 
}

package Account;
import Bank.*;  // Import from a third package
class AccountHolderClass  {	  
  public synchronized void depositFunds(BankApplication ba, String username, double amount) {	
    // Use a utility method of UserClass to check if username exists
    if(ba.exists(username)) { 
      // Deposit the amount
    } 
  } 
  public double getBalance(String accountNumber) { 
    // Return the account balance 
    return 1.0; 
  }   
}

package User;
import Account.*; // One way dependency
import Bank.*; // Import from a third package
class UserClass extends AccountHolderClass implements BankApplication {
  public synchronized double getUserBalance(String accountNumber) {
    // Use a method of AccountHolderClass to get the account balance 
    return getBalance(accountNumber); 
  }
  public boolean exists(String username) { 
    // check if user exists
    return true; 
  }
} 

package Implementer;
import Bank.*;
import Account.*;
import User.*;
class BankOperations {
  private BankApplication ba;
  public BankOperations(BankApplication ba) {
    this.ba = ba;
  }

  public void doUserActions() {
    System.out.println(ba.exists("user"));
    System.out.println(ba.getUserBalance("1111"));
  }

  public static void main(String[] args) {
    AccountHolderClass ac = new AccountHolderClass(); 
    ac.depositFunds(new UserClass(), "user", 1.0); // Pass an interface argument
    BankOperations bo = new BankOperations(new UserClass()); 
    bo.doUserActions(); 
  }
} 

Risk Assessment

Cyclic dependencies between packages can lead to fragile builds. A security vulnerability in a package can easily percolate to several other packages.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC02- J

low

probable

medium

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[Martin 96]]
[[Knoernschild 01]] Chapter 1: "OO Principles and Patterns, 1.2.5 Acyclic Dependencies Principle"


MSC01-J. Avoid memory leaks      49. Miscellaneous (MSC)      SDV01-J. Prefer using URIs to URLs

  • No labels