Design using layers

Designing your code in layers helps to ensure clean separation between database code, business logic and presentation. This helps with maintainability and makes testing easier. Aim for at least:

Data access layer

The data access layer consists of Data Access Objects (DAO) which read from database views and write to tables or call stored procedures.
Each DAO should cover a single database view/table or a small group of related views/tables. For example an OrderDAO would cover the two tables which contain data for Orders and OrderLines. You will have methods for creating, reading and updating orders.

You will need a class for Order which contains a list of OrderLine objects. At this domain object level, all the fields are strongly typed, so use BigDecimal for currency, int or float for quantity, java.util.Date for dates etc.

Service layer

Where database updates are handled by calling stored procedures, the service is layer often very thin, just calling the DAOs and returning the results.
It's a good place to put code that deals with more than one DAO for example if you are reconciling orders and payments the service-level method will use two DAOs: PaymentsDAO and OrdersdAO. It's also a good place to put your transactions: most methods in the service layer should be in a transaction.

If you are not using stored procedures to update your data, the service layer is a good place to put business logic.

Presentation layer

The presentation layer consists of the code to render your data to the screen, whether that is via a web page or desktop application.

In a web application JSP or ASP is used to render the data to a web page. Depending on what framework you are using, Actions or Controllers are used to handle interaction from the users. They control validating the input data and passing it to the service layer.
In the presentation layer the data is likely to be untyped, so dates and numbers are handled as text strings; the classes at this level are sometimes called Form Beans. The Action or Controller converts them to the strongly-typed domain objects before calling the service layer.

If you try to use strongly typed objects in the presentation layer, it may not be possible to display an incorrect value back to the user when validation fails. For example if the field should contain a number but the user enters a letter, you will only be able to display the error back to the user if you hold the value as a string. Trying to convert to its correct numeric type too early means you will not be able to do this.