How Many Classes and Packages Should You Have?
Join the DZone community and get the full member experience.Join For Free
real world experience.
once upon a time there lived a family of programming bears.
each morning mammy bear, daddy bear and baby bear would rise and eat breakfast together in their secluded cottage deep in the forest before whipping out their three laptops to spend hours cheerily writing java code.
one day, while the bears were out shopping, professor of automation theory and software engineering, maria g. locks, stumbled upon the cottage while lost in the woods. cupping her hands against the glass as she peered through a window she spied the glowing screens of three laptops and immediately smashed her way inside.
she sat at the first laptop, cracked its password and pored over the java source code. it was a frightful mess. with just a few, monstrous classes containing thousand-line-long functions, the structure gashed her soul. distraught, she moved to the second laptop and cracked its password. a rancid splurge of code vomited itself up onto the screen, this time with hundreds of fiddly packages hosting hundreds of tiny classes, each in turn baring masses of disjointed functions. cracking a final password she sank weeping before the third laptop.
this code was beautiful.
the packages were neither too big nor too small, neither too many nor too few. the well-proportioned classes housed coherent implementation detail. the functions, appropriately information-hidden, performed single tasks without fuss.
then the three bears burst in through the front door and daddy bear roared with murderous rage at the sight of the intruder. professor locks, screaming, leaped to her feet. mammy bear shrieked something about porridge and a bed but no one could really remember how the tale ended so the whole thing was just abandoned.
the point being?
when is our software neither over-encapsulated, with too many packages and classes, nor under-encapsulated, with too few? when is it just right?
let us try to answer these questions by modeling a java program.
novices often ask, "how many classes should you have?" though unaware of their omission, they are actually asking, "how many classes should i have to satisfy a particular constraint?" we, too, must choose our constraint. real-world constraints usually relate to the problem-domain but, wishing our model to be as widely-applicable as it is simple, we shall choose as our constraint that we want to minimize the number of potential dependencies that our system can support. that is, we wish to minimize the system's potential coupling .
though simple, our choice is not without merit, for we wish (deep breath) to minimize the cost of developing our software and that means minimizing ripple-effect updates by minimizing the number of dependencies involved and that means minimizing the conditions that encourage dependency-formation and that means minimizing the number of potential dependencies.
eyebrows no doubt rise at such rattling chains of logic but the prize - that of an objective measure of how many functions, classes and packages we should have - might be worth some leeway.
our model is based on two assumptions: one sensible, one completely bonkers.
the first assumption is that our system consists of n functions. our task is find the number classes and packages over which we should distribute these n functions so that we minimize the potential coupling.
the second assumption is that all functions will be evenly distributed over all classes and packages, that each class will have d functions visible to other classes in the package and that each package will have the same number, d , functions visible to other classes in other packages.
but not without a smidgen of rationale. we know that evenly-distributing functions minimizes potential coupling in almost all cases. because potential coupling rises with the square of number of elements that can see one another, if a class has twice as many functions then it will have four times as much potential coupling.
as for having a strict number of default-accessor functions per class and public functions per package, well, precisely no one designs a system that way. programmers try, though, to minimize the number of maximally-visible elements so we can look at d = 1 as an ideal if asymptotic goal. certainly once a system is up and running it must have an average number of default-accessor functions per class and public functions per package. given that we want both numbers to be small it is perhaps not so outlandish to find that they might be similar.
our assumptions, however, these are. judge their plausibility for yourself.
finally, let us label our quarry: we wish to know how many packages, p a , and classes, r , our system should have.
so, how do we find p a and r ?
what a function sees.
let us take any function - we shall call it
- in our hypothetical, evenly-distributed system and ask: how many other functions can
see? everything here follows from this question.
there are three groups of functions that
can see. it can see functions within its own class. it can see functions in other classes within its own package. and it can see functions in other classes in other packages.
these three groups, taken together, comprise all the functions visible to
, that is, they give the potential coupling of
. for reasons that will become clear, we wish to find an equation for this potential coupling. to do this we must find three terms, one corresponding to each of these three groups.
functions in own class.
figure 1: potential dependencies from test1() within the own class.
figure 1 shows three packages, each with two classes, each class housing three functions. the red functions are public (their classes are also public), the green private and default-accessor functions are blue. our
function is selected at random to be the one in the bottom-left, as indicated throughout.
how many functions can
see in its own class?
well, it can see all of them; in the example above it can see both other functions in its class. we know that the number of functions in any class is just the total number of functions,
, divided by the total number of classes,
, so we might think that the number is
n / r
. but this would also include a dependency from
on itself, which we would like to ignore, thus the number of dependencies that can form is one less than the number of functions in the class, that is:
functions in own package.
figure 2: potential dependencies from test1() within the own package.
how many functions can
see in other classes within its own package?
it can see those functions that are not private in all other classes in the package; in the example above it can see just one other public function. we know that the number of functions that are not private in each class is
by definition. and we know that the number of classes per package is just the total number of classes,
, divided by the number of packages,
, though, again, we wish to exclude to possibility of
's forming dependencies on its own class. so the number of functions it can see in its own package is:
functions in other packages.
figure 3: potential dependencies from test1() towards other packages.
how many functions can
see in other packages?
it can see all public functions in all public classes in all other packages; the example above shows it forming dependencies on two other public functions. we know that the number of packages is p a and the number of public functions per package is d by definition. again, we shall discount forming dependencies within its own package, so the number of functions it can see in other packages is:
these are the three terms that make up the potential coupling of our one function. to find the potential coupling of the entire system we just multiply them by the total number of functions, n , to give our final equation for the potential coupling, s :
now, it is well-known that the greatest complaint raised by students learning java is that there are too few partial differential equations.
it so happens that our quest to find the number of classes and packages to minimize potential coupling involves just such beasts: for we face an optimization problem. remember those from high-school? set the derivative to zero and solve? that's all we need to do now, thank you, mister newton ... erh, herr leibniz ... whatever.
to find the number of classes, r , that minimizes the potential coupling, s , we calculate the derivative of s with respect to r :
to find the number of packages, p a , that minimizes the potential coupling, s , we calculate the derivative of s with respect to p a :
solving both simultaneous equations gives solutions:
thus if you have a system of 400 functions, that is n = 400 , and aim to have 5 functions per class visible within a package, that is d = 5 , then the number of packages you should have is 4, each with 18 classes.
figure 4 plots our model's potential coupling of 400 functions over all possible of numbers of packages, on the x-axis, and numbers of classes, on the y-axis, with each coordinate coloured red in proportion to the amount of potential coupling generated by that combination of package and class number; thus light pink implies wonderfully-low potential coupling. (the graph is triangular as we cannot have fewer classes than non-empty packages.) the black square indicates the potential coupling minimum.
figure 4: potential coupling of 400 functions as a function of package and class number, with d=5.
of course, you would never create such a system. having only 4 packages for so many functions strikes as far too few; brutal reality would surely barge in and dictate 8 packages, or 10.
this is where the efficiency * of your system comes into play.
100%-efficient systems are as rare as 100%-efficient steam engines. you should gladly descend to 80% or 70% efficiency to win some elbow-room for your design, to enjoy more semantically-driven packages and less-regular distributions than the restrictive ideal case demands. but you may hesitate to fall to the crass encapsulation of only 40% or 30% efficiency, opening your system to the possibility of enormous numbers of dependencies and their subsequent ripple-effect costs.
figure 5 shows an efficiency heat-map of our 400 functions generated by the same potential coupling equation derived above. the dark-blue area shows efficiency of above 90%, a tropical island untrodden by human feet. the cyan, green and yellow bands offer configurations of a more reasonable trade-off between practicality and potential expense. the red area, well ...
figure 5: absolute ideal efficiency of 400 functions as a function of package and class number, with d=5.
how many classes and packages should you have?
altogether now, "it depends."
it depends in particular on the constraint you choose to satisfy. the constraint chosen here was that which tries to minimize development cost by minimizing potential ripple-effect updates.
a simple model was built on some dubious assumptions which lead to some perhaps interesting conclusions.the model can easily be extended, at the cost of complexity, to more-accurately capture reality though, in the end, the model itself has perhaps less to offer than the method by which it was conceived.
however many classes and packages you decide to have, at least be aware of the principles by which you make your decisions.
the only bad design is no design.
photo credit attribution.
* for the absolute ideal efficiency, and as d=1
Opinions expressed by DZone contributors are their own.