Sunday 20 March 2016

Default Values in Java similar to python

I am working on making one of my projects more streamlined. I have a way that checks if a parameter of a function is empty by doing a bunch of if statements. I was wondering if there is a more elegant solution similar to default values in python? I have posted my current code below. Thanks!



I looked into ways about setting default values similar to python but java sadly doesn't support that.



/**

* Updates a user defined address on the mySQL server
* @param conn The mySQL connection
* @param id The id of the address
* @param number The new house number
* @param name The new street name
* @param city The new city
* @param state The new state
* @param zip The new zip code
*/
public static void update(Connection conn, int id, String number, String name, String city, String state, String zip) {

Address address = Address.getBy(conn, "id", Integer.toString(id));
if(number.equals("")) {
number=address.getNumber();
}
if(name.equals("")) {
name=address.getName();
}
if(city.equals("")) {
city=address.getCity();
}

if(state.equals("")) {
state=address.getState();
}
if(zip.equals("")) {
zip=address.getZip();
}
try {
PreparedStatement ps = conn.prepareStatement("UPDATE address SET number=?, name=?, city=?, state=?, zip=? WHERE id =?");
ps.setString(1, number);
ps.setString(2, name);

ps.setString(3, city);
ps.setString(4, state);
ps.setString(5,zip);
ps.setInt(6, id);
ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...