How do i keep myself DRY and prevent code explosion in this scenario
My application lets a user browse a world map. When the user clicks on a country, a mindmap appears. The user then traverses the nodes of this mindmap. So for example, when user clicks Singapore, a mind map appears. Next, the user clicks on a job function, e.g. Human Resources. This final node redirects the user to another page, in which there is a JSF datatable showing the job profiles in the respective location and function. A typical method which corresponds to each datatable looks like this.
public ResultSet getAll() throws SQLException {
Connection conn = ds.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM JOBPROFILE WHERE LOCATION='SINGAPORE' AND JOB开发者_开发百科FUNCTION='HUMAN RESOURCES'");
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
The problem is that I have 16 locations and 14 functions. This means that I have 224 pages,datatables & methods to write! Maintenance would be a nightmare. Is there some way I could do this programatically so I wouldn't have to repeat most of the code over and over again? The only variance between each method is the SQL query. I'm implementing the world map and mind map in flash, hence I'm not sure as to how can I retrieve the final value the user clicks, and pass it to the backing bean,so that I can call the relevant query, instead of writing 224 different pages, datatables and methods which varies in only one line of code.
You should store the data in the hyperlink. i.e.
foo.com/jobs?country=singapore&jobfunction=humanresources
The JSF can then take that and call a more resuable method:
public ResultSet getAll(String location, String profile) throws SQLException {
Connection conn = ds.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM JOBPROFILE WHERE LOCATION='"+location+"' AND JOBFUNCTION='"profile"'");
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
Just remember that you should be escaping these or, better yet, using a prepared statement
精彩评论