Saturday, March 1, 2008

To promote reusability

To reuse our source code or classes is a hard task specially when we don't think about this in the beginning of analysis or design. Even though we have already done our projects or programs that is not well-designed, we can use some refactoring function inside the IDE tool for us to adjust or arrange our source code, for instance, to extract the interface from classes. But, it is still much better if we know how to promote reusability and do it in the analysis/design phase. In the book, Pro Java Programming 2nd Edition, it provides 2 good principles (Loose Coupling and Strong Cohesion) for reference.

1. Loose Coupling
Coupling means that it refers to the degree to which classes depend upon one another, and two classes that are highly dependent upon each other are considered tightly (or highly) coupled. In other words, they cannot be used alone and also not be used for other classes. There are some examples from this book and I draw the class diagrams to explain the idea.

a.) This diagram shows that these two classes have strong coupling. They refer each other and are Bad-designed.

b.) This diagram shows that it uses an interface "FontListener" to reduce the coupling. "FontProperitesPanel" doesn't need to know who implements the interface "FontListener". It just calls the method "fontChanged()" in the interface, and "SampleTextFrame" that implements the interface will response.

c.) This diagram shows we create a "FontPropertiesFrame" class that extends "SampleTextFrame" that can eliminate "SampleTextFrame"’s references to the "FontPropertiesPanel" class and move them into a subclass of SampleTextFrame.
2. Strong Cohesion
If a class is highly cohesive, it means its responsibilities are closely related and that it’s complete. In other words, the class isn’t cohesive if it contains methods that perform unrelated functions or if some set of closely related functions is split across that class and one or more others.
So, I think that these 2 principles are quite useful when we design our classes structure.

No comments: