Thursday, October 15, 2009

Understanding OOP pitfalls in Java EE:

Object Orientated Programming (OOP) is the foundation on which the Java language is built upon. When you build a Java program you are building a set of objects that will work together towards a goal. This brings me to the first point: in Java EE it is important to remember to think of the object and not the task.

A common pitfall is to start adding logic into a class that broadens its scope. Remember, objects should be single shot, single idea things. Let's say you have an object call BankAccount. You would put into this class the account number, the account name, address, details, balance and so forth. However, you may be tempted to place logic that converts the object into, say a SQL string or properly formats an address for display in a GUI. NO! Do not add logic to the class if it does not need to be added to keep the concept that the class represents, sane. A bank account does not need to know about SQL, a bank account does not need to know about GUIs.

The reasoning behind this is that the Java EE platform takes a lot of the bridge work out for you, you adding it back in prevents you from fully accessing all of the features (besides if you're adding them in who is Java to tell you wrong?)

Complex logic goes into classes that will handle other classes. In the example above you might include the BankController class. It will be this class' job to gather the needed objects to handle the object you pass in. The BankController
class may need to gather the objects that handle permissions, validation, database connectivity, and so forth. The Java EE platform has this covered for you. So you just worry about modeling classes after the real world thing they represent.

No comments: