Re: Best way to do this?
harryajh <harryreg_uk@yahoo.co.uk> wrote:
if (propName.equalsIgnoreCase("licence_number"))
else if (propName.equalsIgnoreCase("return_requirement_id"))
One thing to avoid unnecessary waste might be to "toLowerCase()" once,
and then use plain .equals() for comparisons.
Next step would be to look up the toLowerCase()'d property name in
a HashMap, that has all 10 strings associated with a small integer,
which you then use in a switch(...){...} to get the appropriate
method called on the MyBean for each number.
The "OO" way, would be to have some interface like
interface Storer { void store(MyBean b,String s); }
and in the HashMap you associate anonymous Storer-implementations:
Map<String,Storer> m = new HashMap<String,Storer>();
m.put("licence_number",new Storer() {
public void store(MyBean b,String s) { b.setLicenceNo(s); } } );
m.put("return_requirement_id",new Storer() {
public void store(MyBean b,String s) { b.ret.setReturnReqId(s); } } );
// ... ditto for the further 8 mappings
MyBean b = new MyBean();
Then, inside the loop:
m.get(rs.getString(2).toLowerCase()).store(b,rs.getString(3));
Well, actually you may want to break this up into separate statements
storing intermediate results in local variables and do null-checks
where appropriate.
For best encapsulation, you could add a method to MyBean, that takes
the Property's name and new value, and does the HashMap-lookup and
invocation of the obtained Storer. The HashMap itself would also be
maintained by MyBean and created and populated in the static initializer,
or lazily on first use.
I do not claim, that any of these would actually make your whole program
faster, but I dislike those if-chains, anyway, so even if your program
doesn't end up faster, I think those alternatives would still be worth
considering.
PS: "myBean" was a bad class-name and "GetString" is not a method of
ResultSet, so I changed them.