Archive for December, 2013

inArray instead of multiple conditionals or switch case lines: () && () && () && ()

Thursday, December 12th, 2013

Tired of writing


$var != null && $var != undefined &&

forever…?


if( $var != 'NULL' && $var != ' ' && $var != undefined &&....... )

?

or:


switch($var){
case null: break;
case " ": break;
case undefined: break;
...
default:
}

?

Do this instead!


if (!in_array($var, array("", null, "undefined", 'etc.'))){
//
}

Example 2:


$var1 = 50, $var2 = 43, $var4 = 48;
$inProductArray = array($var1, $var2, $var3, $var4);

Instead of:


foreach($inProductArray as $temp){
switch($temp){
case 40:
case 44:
case 48:
case 52: echo "Flight + Hotel"; break;
case 41:
case 45:
case 49:
case 53: echo "Flight"; break;
case 42:
case 46:
case 50:
case 54: echo "Hotel"; break;
case 43:
case 47:
case 51:
case 55: echo = "Car"; break;
}
}// Result HotelCarFlight + Hotel

Do this!


foreach($inProductArray as $temp){
switch($temp){
case in_array($temp, array(40,44,48,52)): echo "Flight + Hotel"; break;
case in_array($temp, array(41,45,49,53)): echo "Flight"; break;
case in_array($temp, array(42,46,50,54)): echo "Hotel"; break;
case in_array($temp, array(43,47,51,55)): echo "Car"; break;
}
}// Result HotelCarFlight + Hotel

JAVA Reflection handy MethodInspector Class

Sunday, December 8th, 2013

import java.lang.reflect.*;

public class MethodInspector {

public static void main(String[] arguments) {

Class inspect;
try {

if (arguments.length > 0)

inspect = Class.forName(arguments[0]);

else

inspect = Class.forName(“MethodInspector”);

Method[] methods = inspect.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {

Method methVal = methods[i];
Class returnVal = methVal.getReturnType();
int mods = methVal.getModifiers();
String modVal = Modifier.toString(mods);
Class[] paramVal = methVal.getParameterTypes();
StringBuffer params = new StringBuffer();
for (int j = 0; j < paramVal.length; j++) {

if (j > 0)

params.append(“, “);

params.append(paramVal[j].getName());

}
System.out.println(“Method: “ + methVal.getName() + “()”);
System.out.println(“Modifiers: “ + modVal);
System.out.println(“Return Type: “ + returnVal.getName());
System.out.println(“Parameters: “ + params + “\n”);

}

} catch (ClassNotFoundException c) {

System.out.println(c.toString());

}

}

}

credit: Sams Teach Yourself JAVA in 21 Days, Day 16, http://workbench.cadenhead.org/book/java21days/