If you're paying attention, you've probably noticed a little repetition. In fact, some of those inner classes may be better served by separate classes that can populate your domain model. In this example, you'll refactor a little of that common code.
Your small objects may keep this book short, but they're not particularly realistic. Business objects typically have many more fields. If you try to do everything in line, you can accumulate a little too much replication. I like repetition about as much as I like paddling on flat water. In fact, my worst injuries have both come on easier rapids, or easy trails, because I wasn't not paying attention as closely as I should have been. You're likely to find the same phenomenon with tedious, repetitive code: the monotony can keep you from paying attention, and cause an uncomfortable number of minor injuries.
You're simply going to break some of the code in those inner classes free, so they're easier to read and easier to reuse. You'll focus on the code that populates each object (Example 4-8).
Example 4-8. JDBCRentABike.java
public List getBikes( ) { final ArrayList results = new ArrayList( ); JdbcTemplate template = new JdbcTemplate( ); class BikesHandler implements RowCallbackHandler { public void processRow(ResultSet rs) throws SQLException { Bike bike = new Bike(rs.getString(MANUFACTURER), rs.getString(MODEL), rs.getInt(FRAME), rs.getString(SERIALNO), rs.getDouble(WEIGHT), rs.getString(STATUS)); results.add(bike); } } template.query("SELECT * FROM bikes", new BikesHandler( )); return results; } public Bike getBike(String serialNo) { final Bike bike = new Bike( ); JdbcTemplate template = new JdbcTemplate( ); class BikeHandler implements RowCallbackHandler { public void processRow(ResultSet rs) throws SQLException { bike.setManufacturer(rs.getString(MANUFACTURER)); bike.setModel(rs.getString(MODEL)); bike.setFrame(rs.getInt(FRAME)); bike.setSerialNo(rs.getString(SERIALNO)); bike.setWeight(rs.getDouble(WEIGHT)); bike.setStatus(rs.getString(STATUS)); } } template.query("SELECT * FROM bikes WHERE bikes.serialNo = '" + serialNo + "'", new BikeHandler( )); return bike; }
When you run the application, you should get the same behavior, since once again, you're only changing database logic. Notice how Spring is protecting the user interface from churn.
Get Spring: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.