Question

I've got some java classes which I would like to put into a packages. Here is an example:

Foo.java 
Bar.java 
Qux.java 
MetaFoo.java 
MetaBar.java 
MetaQux.java

As you can see, classes exist in pairs "Class" <-> "MetaClass".

I consider three approaches for organizing those files:

One package for all classes

Simply keeping everything in one package.

enter image description here

Put each pair in separate package

This will result in following structure:

Each pair in separate package

Create separate packages for classes and meta-classes

enter image description here

Which approach has lower coupling and higher cohesion?

Additional info:

  • Each meta-class contains field with instance of "normal" class, i.e. MetaFoo contains field foo of type Foo,
  • Meta classes have common super class called MetaClass. They do not inherit anything more.
  • Regular classes are not associated witch each other by composition/aggreation nor inheritance.
Was it helpful?

Solution 2

I decided to use Code Metrics to measure cohesion and coupling.

Cohesion

For Cohesion, lets use metric called Lack of Cohesion of Packages (LCOP). It is modified version of LCOM4 metrics. It counts number of connected components (in this case classes) in each package:

LCOP

The bigger value, the more cohesive package is. Note, that only directly connected components will count. For each approach we will get averaged values for every package. Here are measured values:

  • Approach 1: 3/1 = 3
  • Approach 2: (1+1+1)/3 = 1
  • Approach 3: (3+3)/2 = 3

Approach 2nd has the lowest value, so it is the most cohesive.

Coupling

Now, lets measure coupling. For this we will use metric Coupling Between Objects (CBO). This metric is defined as:

CBO

The bigger value, the higher coupling between packages. We will count only efferent coupling. Again, values will be averaged in each approach. We have:

  • Approach 1: 3/6 = 0.5
  • Approach 2: (1/2+1/2+1/2)/3 = 0.5
  • Approach 3: (0/3+6/3)/2 = 1

Aprroaches 1st and 2nd have the lowest value of coupling.

Summary

Approach 2nd is the most coehsive and just as good as 1st approach in coupling. Moreover, in practical use, approach 2nd will be easier to manage when the project will grow up. Quite suprisingly, approach 3rd seems to be the worst.

OTHER TIPS

In my opinion you should place any classes with shared logic in the same package - second case. That's because if you have multiple child classes like xxxBar you have all of these classes close at hand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top