Less Code == [Less Bugs,Better Readability,Less programmers to hire, Less organizational communication costs, Less maitain cost]
Less Code != [Higher Productivity,Better Performance]
1, import static
remove duplicated namespace
what does it do?
package com.toolbox.lang;
public class ClassWithStaticMember {
public static final String name="value";
public static String say() {
return "111";
}
public static String say(String msg) {
return msg;
}
}
package com.toolbox.lang;
import static com.toolbox.lang.ClassWithStaticMember.say;
import static com.toolbox.lang.ClassWithStaticMember.name;
public class Test {
public static void main(String[] args) {
System.out.println(say());
System.out.println(say(name));
}
}
import同名的member
意味着不同方法签名的member都会import, e.g. say() and say(String msg)
const #45 = Method #46.#48; // com/toolbox/lang/ClassWithStaticMember.say:()Ljava/lang/String;
const #46 = class #47; // com/toolbox/lang/ClassWithStaticMember
const #47 = Asciz com/toolbox/lang/ClassWithStaticMember;
const #48 = NameAndType #49:#38;// say:()Ljava/lang/String;
const #49 = Asciz say;
const #62 = Method #46.#63; // com/toolbox/lang/ClassWithStaticMember.say:(Ljava/lang/String;)Ljava/lang/String;
const #63 = NameAndType #49:#64;// say:(Ljava/lang/String;)Ljava/lang/String;
copy primitive type value
意味着编译后,Test class中static import的String, int 等是值的写入class中,不会在去引用ClassWithStaticMember
43: ldc #55; //String value
45: invokestatic #57; //Method com/toolbox/lang/ClassWithStaticMember.say:(Ljava/lang/String;)Ljava/lang/String;
48: invokevirtual #50; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
when to use it?
Do it when frequent access to static members from one or two classes
Not Do it when has naming conflict or complicated class body, otherwise, make you confuse with so many polluting namespace
2, apply lanuage feature
2.1 String contact
String s = "a" + "b";
compile into:
const #15 = Asciz ([Ljava/lang/String;)V;
const #16 = String #17; // ab
if String constance + String constance
直接编译成结果写入class
else
使用StringBuilder.append
So always use "+" unless you need to use StringBuffer or other specific class
3, inner class {{}}
List<String> list = new ArrayList<String>() {{add("data1");add("data2");}};
4, use PMD to find and remove duplicated code
已有 0 人发表留言,猛击->>这里<<-参与讨论
JavaEye推荐
文章来源:
http://sevenduan.javaeye.com/blog/504911