13.5 Separating business logic from UI logic



In general you'll want to design your classes so that each one does "only one thing." This is particularly important when user-interface code is concerned, since it's easy to wrap up "what you're doing" with "how you're displaying it." This kind of coupling prevents code reuse. It's much more desirable to separate your "business logic" from the GUI. This way, you can not only reuse the business logic more easily, it's also easier to reuse the GUI.

Another issue is multi-tiered systems, where the "business objects" reside on a completely separate machine. This central location of the business rules allows changes to be instantly effective for all new transactions, and is thus a compelling way to set up a system. However, these business objects can be used in many different applications and so should not be tied to any particular mode of display. They should just perform the business operations and nothing more.

The following example shows how easy it is to separate the business logic from the GUI code:

Case Study: Separation.java

You can see that BusinessLogic is a straightforward class that performs its operations without even a hint that it might be used in a GUI environment. It just does its job. Separation keeps track of all the UI details, and it talks to BusinessLogic only through its public interface. All the operations are centered around getting information back and forth through the UI and the BusinessLogic object. So Separation, in turn, just does its job. Since Separation knows only that it's talking to a BusinessLogic object (that is, it isn't highly coupled), it could be massaged into talking to other types of objects without much trouble. Thinking in terms of separating UI from business logic also makes life easier when you're adapting legacy code to work with Java.


Next Page