View Full Version : shrinking code

01-05-2008, 04:12 PM
this is a bit of java script code:
functions like checkNick .. all return "" if it is all OK or otherwise some kind of message for user

result = checkNick(nick) || checkMail(email) || checkPwd(pwd1,pwd2);
if (result)

// go forvard ..

This is attempt to do the same in java, knowing that HashSet does not allow duplicates. It works as wanted, first occurance that does not satisfy , jumps out.

java.util.HashSet hs = new java.util.HashSet();
boolean f;
f = hs.add("");

result = hs.add(checkNick(nick)) ||
hs.add(checkPwd(pwd1, pwd2)) ||
hs.add(checkMail(email)) ||
hs.add(checkCaptcha(clientCaptcha, serverCaptcha));

if (!result)
String[] a = (String[])hs.toArray(new String[0]);
// output to user about error
return a[a.length-1].toString();

Comments welcome.

01-07-2008, 01:06 AM

java.util.List<String> list = java.util.Arrays.asList(
checkNick(nick), checkPwd(pwd1, pwd2), checkMail(email), checkCaptcha(clientCaptcha, serverCaptcha)
String s;
for(Iterator<String> iter = list.iterator(); iter.hasNext();) {
s = iter.next();
if(s.length() != 0)
return s; // return erroneus string
// all okay


String[] strs = new String[]{
checkNick(nick), checkPwd(pwd1, pwd2), checkMail(email), checkCaptcha(clientCaptcha, serverCaptcha)
for(int i = 0; i < strs.length; ++i)
if(strs[i].length() != 0)
return strs[i]; // return "bad" string
// all okai

01-11-2008, 06:37 PM
looks less code than mine, which is what I want, but has fundamental error:
it has to check all functions before, rolls thru all results and decide what to do.
Mine jumps out as soon as first result is bad.

01-11-2008, 07:34 PM
java.util.Set<String> set = new java.util.TreeSet<String>(2);
if(set.add(checkNick(nick)) ||
set.add(checkPwd(pwd1, pwd2)) ||
set.add(checkMail(email)) ||
set.add(checkCaptcha(clientCaptcha, serverCaptcha)))
return (String)set.toArray(new String[2])[1];
// okay

01-12-2008, 07:32 PM
Why don't you just return boolean values from your checking methods. This would make much more sense. Also, wouldn't returning "" in the functions and then using a HashSet's failure to add more than 1 "" just mean that one thing can fail but 2 can't. Do you really want 1 thing being able to fail? For example the nickname and email may be correct but an invalid password returning "" is only returned false by adding it to a hash set if something else has previously failed and thus added "".

Also, be wary of lazy execution. I expect that Java only executes statements in boolean expressions until the expression is certain. For example (false && foo()) will always return false even before foo is to be executed, so if you want all functions to be executed, do something like
boolean isFoo = foo();
boolean isBar = bar();
if(isFoo || isBar)
// exists
// doesn't exist.