Domanda

Pretty simple question. Should package structure closely resemble class hierarchy? If so, how closely? Why or why not?

For instance, let's say you've got class A and class B, plus class AFactory and class BFactory. You put class A and class B in the package com.something.elements, and you put AFactory and BFactory in com.something.elements.factories. AFactory and BFactory would be further down the hierarchy package-wise, but they'd be further up class-wise. Is this sort of thing a good idea or a bad idea?

È stato utile?

Soluzione

According to Uncle Bob, classes should be grouped together into packages if they change together. Presumably, if class A changes, then class AFactory would need to change as well, but class BFactory would not. So, if A and B are unrelated, then each should be in a separate package together with the corresponding factory. On the other hand, if there is a dependency between A and B that forces you to change one when you change the other, then the two classes and the two factories should all be in the same package.

If you follow this pattern, then you should be able to build each package into a separate library, independently of the other one.

Altri suggerimenti

You are asking the wrong question. It is not whether something is a good or bad idea but whether it is useful.

Consider another developer who has to deal with your code. What will they understand from the package structure? Will it improve their understanding and ability to maintain and expand you code, or will it make them want to change it?

The technical aspects of OO are clear, inheritance and polymorphism (implements/extends) amongst others, and these are apparent from the code, along with design patterns. Package structure and naming should be about describing the aims and functionality of the code base (e.g. what is an xxxImpl and how does it work?)

The previous answer talks about coupling and may help in general development, but having the business goals and requirements clearly defined in the overall structure is much more useful.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top