Writing high-quality code: 151 suggestions for improving Java programs (Chapter 1: common methods and guidelines for JAVA Development ___ suggestions 16 ~ 20), java151

Source: Internet
Author: User

Writing high-quality code: 151 suggestions for improving Java programs (Chapter 1: common methods and guidelines for JAVA Development ___ suggestions 16 ~ 20), java151
Recommendation 16: easy-to-change businesses written in scripting

The Java World has been suffering from intrusions from different languages, such as PHP, Ruby, Groovy, and Javascript. These intruders all share a common feature: the same language-scripting language, they are all interpreted and executed at runtime. Why does a strong compiled language like Java need these scripting languages? This is because of the three major features of the script language, as shown below:

These features of the scripting language are missing from Java. The introduction of the scripting language can make Java more powerful, so Java 6 began to formally support the scripting language. However, because there are many scripting languages, it is difficult for Java developers to determine which language to support. Therefore, JSCP (Java Community ProCess) cleverly proposed the JSR233 specification, any language that complies with this specification can run on the Java platform (it is supported by default for JavaScript ).

Let's take a look at the following small example:

function formual(var1, var2){     return var1 + var2 * factor; }

This is a simple scripting function, and you may wonder: where does the variable factor come from? It comes from context, similar to an environment variable for running. This js is stored in C:/model. js. The JavaScript formula needs to be called next. The Code is as follows:

1 import java. io. fileNotFoundException; 2 import java. io. fileReader; 3 import java. util. export; 4 5 import javax. script. bindings; 6 import javax. script. invocable; 7 import javax. script. scriptContext; 8 import javax. script. scriptEngine; 9 import javax. script. scriptEngineManager; 10 import javax. script. scriptException; 11 12 public class Client16 {13 public static void main (String [] args) throws FileNotFoundException, 14 ScriptException, noSuchMethodException {15 // get a JavaScript execution engine 16 ScriptEngine engine = new ScriptEngineManager (). getEngineByName ("javascript"); 17 // create the context variable 18 Bindings bind = engine. createBindings (); 19 bind. put ("factor", 1); 20 // bind context, so the current engine range is 21 engine. setBindings (bind, ScriptContext. ENGINE_SCOPE); 22 bytes input = new bytes (System. in); 23 24 while (input. hasNextInt () {25 int first = input. nextInt (); 26 int second = input. nextInt (); 27 System. out. println ("input parameter:" + first + "," + second); 28 // run the Js Code 29 engine. eval (new FileReader ("C:/model. js "); 30 // call Method 31 if (engine instanceof Invocable) {32 Invocable in = (Invocable) engine; 33 // execute the function 34 Double result = (Double) in. Js. invokeFunction ("formula", first, second); 35 System. out. println ("Operation result:" + result. intValue (); 36} 37} 38 39} 40}

The previous Code uses the accept class to accept two numbers entered by the keyboard, and then calls the formula function of the JavaScript script to calculate the result. Note that the current JVM will continue to run unless a non-int number is entered, this also simulates online changes to the generation system. The running result is as follows:

Input parameter: 3

At this point, keep the JVM running state. Let's modify the formula function. The Code is as follows:

function formual(var1, var2){     return var1 + var2 - factor; }

Here, the multiplication number is changed to a minus sign, and the calculation formula is greatly changed. Return to JVM and continue the input. The running result is as follows:

Input parameter: 1 and 2 running results: 2

Modify the Js Code. The JVM does not restart and the input parameters are not changed. You can change the script function to produce different results. This is where the scripting language is most advantageous for system design: It can be released at any time without deployment. This is also a favorite of Java er-even if it is changed, it can also provide uninterrupted business services.

Java 6 not only provides built-in code-level scripts, but also provides jrunscript command tools that can achieve maximum performance in batch processing without the need to explain the scripting language through JVM, you can run the script directly using this tool. Think about it. How tempting this is! In addition, this tool can be used across operating systems, making it easier to port scripts.

Suggestion 17: use dynamic compilation with caution

Dynamic compilation has always been a dream of java. It has supported dynamic compilation since java 6 and can be directly compiled at runtime. java file, run. class, get the relevant input and output, and even listen to related events. However, what we expect most is to set a piece of code, compile it directly, and then run it, that is, on-the-fly. See the following code:

1 import java. io. IOException; 2 import java. lang. reflect. method; 3 import java.net. URI; 4 import java. util. arrayList; 5 import java. util. arrays; 6 import java. util. list; 7 8 import javax. tools. javaCompiler; 9 import javax. tools. javaFileObject; 10 import javax. tools. simpleJavaFileObject; 11 import javax. tools. standardJavaFileManager; 12 import javax. tools. toolProvider; 13 14 public class Client17 {15 pu Blic static void main (String [] args) throws Exception {16 // Java source code 17 String sourceStr = "public class Hello {public String sayHello (String name) {return \" Hello, \ "+ name + \"! \ ";}}"; 18 // class name and file name 19 String clsName =" Hello "; 20 // method name 21 String methodName =" sayHello "; 22 // current compiler 23 JavaCompiler cmp = ToolProvider. getSystemJavaCompiler (); 24 // Java standard file manager 25 StandardJavaFileManager fm = cmp. getStandardFileManager (null, null, 26 null); 27 // Java file object 28 JavaFileObject jfo = new StringJavaObject (clsName, sourceStr); 29 // compile the parameter, similar to options30 List <String> optionsList in javac <options> = New ArrayList <String> (); 31 // place where the compiled files are stored. Note: This is the 32 optionsList special for the Eclipse tool. addAll (Arrays. asList ("-d ",". /bin "); 33 // The 34 List of units to be compiled <JavaFileObject> jfos = Arrays. asList (jfo); 35 // set the compiling environment 36 JavaCompiler. compilationTask task = cmp. getTask (null, fm, null, 37 optionsList, null, jfos); 38 // compilation successful 39 if (task. call () {40 // generate Object 41 Object obj = Class. forName (clsName ). newInstance (); 42 Class <? Extends Object> cls = obj. getClass (); 43 // call sayHello Method 44 Method m = cls. getMethod (methodName, String. class); 45 String str = (String) m. invoke (obj, "Dynamic Compilation"); 46 System. out. println (str); 47} 48 49} 50} 51 52 class StringJavaObject extends SimpleJavaFileObject {53 // Source Code 54 private String content = ""; 55 56 // class name and file 57 public StringJavaObject (String _ javaFileName, String _ content) compliant with Java specifications {58 super (_ createStringJavaObjectUri (_ javaFileName), Kind. SOURCE); 59 content = _ content; 60} 61 62 // generate a URL resource path 63 private static URI _ createStringJavaObjectUri (String name) {64 // note, package name 65 return URI is not set here. create ("String: //" + name + Kind. SOURCE. extension); 66} 67 68 // text file code 69 @ Override70 public CharSequence getCharContent (boolean ignoreEncodingErrors) 71 throws IOException {72 return content; 73} 74}

The code above is large and can be used as a dynamically compiled template program. All tasks that can be implemented through local static compilation, such as compilation parameters, input and output, and error monitoring can be implemented through dynamic compilation.

The dynamic compilation of Java provides multiple sources. For example, it can be a string, text file, bytecode file, or plaintext code or bytecode stored in the database. To summarize a sentence, as long as it complies with Java specifications, it can be dynamically loaded at runtime. The implementation method is to implement the JavaFileObject interface and rewrite getCharContent, openInputStream, and openOutputStream, you can also implement two SimpleJavaFileObject and ForwardingJavaFileObject provided by JDK. For specific code, refer to the previous example.

Dynamic compilation is a good tool that allows us to control the compilation process more freely, but it is rarely used in projects we currently have access. The reason is very simple. Static compilation can help us deal with most of the work, even all of the work. Even if we really need dynamic compilation, there are good alternatives, for example, Jruby, Groovy, and other seamless scripting languages. In addition, when using dynamic compilation, pay attention to the following points:

Suggestion 18: avoid unexpected instanceof results

Instanceof is a simple binary operator used to determine whether an object is implemented as a class. Its operations are similar to> =, =, and so on. The Code is as follows:

1 import java. util. date; 2 3 public class Client18 {4 public static void main (String [] args) {5 // whether the String Object is an Object instance true 6 boolean b1 = "String" instanceof Object; 7 // whether the String Object is a String instance true 8 boolean b2 = new String () instanceof String; 9 // whether the Object is a String instance false10 boolean b3 = new Object () instanceof String; 11 // whether the binning type is A boxed instance is compiled without 12 boolean b4 = 'A' instanceof Character; 13 // whether the empty object is a String instance false14 boolean b5 = null instanceof String; 15 // whether the converted empty object is a String instance false16 boolean b6 = (String) null instanceof String; 17 // whether the Date is String-based instance compilation does not pass 18 boolean b7 = new Date () instanceof String; 19 // In the generic type, judge whether the String object is a Date instance false20 boolean b8 = new GenericClass <String> (). isDateInstance (""); 21 22} 23} 24 25 class GenericClass <T> {26 // determine whether it is a Date type 27 public boolean isDateInstance (T t) {28 return t instanceof Date; 29} 30 31}

For such a program, the application scenarios of instanceof have basically appeared, and the problem also arises: which statements in this program fail to be compiled? One by one, we explain:

Suggestion 19: assertions are definitely not chicken ribs

In Defensive Programming, Assertion is often used to judge parameters and environments to avoid logical exceptions caused by improper judgment or input errors. Assertion exists in many languages, c, C ++, and Python all have different assertions. the assert keyword is used in Java assertions. Its basic usage is as follows:

Assert <Boolean expression>

Assert <Boolean expression >:< error message>

When the Boolean expression is false, the AssertionError error is run with an error message. The syntax of assert is relatively simple and has the following two features:

(1) assert is disabled by default.

We know that assertions serve debugging programs to quickly and conveniently check program exceptions, but Java is not enabled by default, to enable this function, you need to add related keywords during compilation and runtime. This is not much to mention. If necessary, you can refer to the Java specifications.

(2) AssertionError is inherited from Error

After an AssertionError is thrown, the JVM will throw an AssertionError that inherits from the Error. Note that this is an Error and cannot be recovered, which indicates that this is a serious problem, developers must pay attention to and solve this problem.

Although assert is an assertion, it cannot be equivalent to a condition like if... else... which is unavailable in the following two cases:

(1) In the public Method

We know that the core of Defensive Programming is that all external factors (input parameters, environment variables, and context) are "evil" and there are evil origins that attempt to destroy programs, to resist it, we need to test it everywhere. If the ground is filled with cards and the conditions are not met, subsequent programs will not be executed to ensure the correctness of subsequent programs. There is no problem with cards everywhere, but it is impossible to use assertions for input verification, especially the public method. Let's look at an example:

1 public class Client19 {2 public static void main (String [] args) {3 System. out. println (StringUtils. encode (null); 4} 5} 6 7 class StringUtils {8 public static String encode (String str) {9 assert str! = Null: "The encrypted string is null"; 10/* encryption processing */11 return str; 12 13} 14}

The encode method assumes that the input parameter is not null. If it is null, an AssertionError error is thrown. However, this program has a serious problem. encode is a public method, this indicates that when it is made public, any class can be called as long as it can pass a String type parameter (subject to the contract), but the Client19 class calls the encode method according to the regulations and contract, but an AssertionError message is obtained. who has broken the contract agreement? --- The encode method itself.

(2) When the logic code is executed

The support of assert is optional. It can be run during development, but the system does not need to run it in the production environment (to improve performance ), therefore, the logic Code cannot be executed in the Boolean expression of assert. Otherwise, different logics are generated due to different environments. For example:

Public void doSomething (List list, Object element) {assert list. remove (element): "delete element" + element + "failed";/* business processing */}

This code has no problem in the assert enabled environment, but once it is invested in the build environment, it will not enable assertions, and this method will be completely finished, the Delete action of the list will never be executed, so no error or exception will be reported, because it is not executed at all!

In the above two cases, assert cannot be used. Under what circumstances can assert be used? One sentence: assert can be prevented from reaching the code area according to the normal execution logic. There are three situations:

Public void doSomething () {int I = 7; while (I> 7) {/* business processing */} assert false: "An error is returned when it arrives ";}

3. create a program Probe: We may define two variables in a program to represent two different business meanings, but the two have a fixed relationship, such as: var1 = var2 * 2, then we can set up a "pile" everywhere in the program, asserted the relationship between the two, if not satisfied, it indicates that the program has encountered an exception, the business is not necessary to run.

Suggestion 20: do not replace only one class

We often define a constant interface (or constant class) in the system to include constants involved in the system, which simplifies code and facilitates development, similar methods have been adopted in many open-source projects, such as in struts2, org. apache. struts2.StrutsConstants is a constant class that defines configuration-related constants in the Struts framework, while org. apache. struts2.StrutsConstants is a constant interface, which defines the keyword for OGNL access.

For a constant interface (class), let's look at an example. First, define a constant class:

Public class Constant {// defines the limit of human life. public static final int MAX_AGE = 150 ;}

This is a very simple constant class that defines the largest age of human beings. We reference this constant. The Code is as follows:

Public class Client {public static void main (String [] args) {System. out. println ("human life limit:" + Constant. MAX_AGE );}}

The running result is easy, so it is omitted. The current Code is written in the "smart" IDE tool. The following code is now traced back to the original era, that is, back to the era when coding with notepad, then let's see what will happen (why? The answer is given below)

Modify the Constant class. The maximum lifetime of a human is increased to 180. The Code is as follows:

Public class Constant {// defines the limit of human life. public static final int MAX_AGE = 180 ;}

Then re-compile, javac Constant. After compilation, execute: java Client. You can guess the output age?

The output is: "The Life limit of human beings is 150", but it was not changed to 180. That's strange. Why?

The reason is: for the basic types and String types modified by final, the compiler will regard it as Immutable Status. Therefore, the value is directly compiled into the bytecode during compilation, this avoids running-time Reference during runtime to improve code execution efficiency. For our example, the Client class writes "150" in the bytecode during compilation, instead of an address reference. Therefore, no matter how you modify the constant class, as long as the Client class is not re-compiled, the output remains the same.

For final-modified classes (non-basic types), the compiler considers them not stable (Mutable Status ), the reference relationship (Soft Final) is created during compilation ). If the constant introduced by the Client class is a class or instance, the latest value will also be output if it is not re-compiled in time.

Never underestimate this knowledge, but it can also trip elephants. For example, in a web project, a developer modifies a final value (basic type) Considering the high risk of re-release, or the approval process is too cumbersome. It is to be lazy, So we directly release it by replacing the class file. After the replacement, the application server restarts automatically. Then, let's test it. Everything is OK, after several days of running, you can find that the business data is not correct. Some classes (referenced classes) use old values, and some classes (inherited classes) use new values, the root cause of the problem lies in the lack of clues.

There is another small problem that does not explain why our example does not run in IDE tools (such as Eclipse? This problem cannot be reproduced because automatic compilation is set in the IDE. If the Constant class is modified, the IDE tool will automatically compile all the reference classes. This problem is blocked by "intelligence, however, there are still potential risks. I remember that Eclipse should have an entry for setting automatic compilation. If you are interested, try it on your own.

 Note: the replacement of class files is not allowed when the application system is published. The release of the overall WAR package is a panacea. However, I think special treatment should be taken in special circumstances, but it cannot be partial. What do you think?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.