You will have learned by the end of this article

  • Write more elegant and efficient Java code

1. Introduction

On Saturday, I happened to brush a question like “How about Java development manual (Huangshan version)? , I carefully look at this is not gu Do teacher’s work? Actually has been updated to huangshan version.

The last time I looked at this brochure was the last time I looked at the Huashan edition in nineteen. Go ahead again that is 17 years of the first edition, at that time was downloaded in ali’s public number, and later also bought the entity of “Java development manual” and “code efficient” two books.

It wasn’t a very deep book, but it taught me a lot — you can’t write complex code, but you can write code that is clean, clean, and not “oh my God” but “oh my god”.

In this article I will give a brief introduction to a few programming conventions from the manual.

There is a way to download the manual at the end of the article.

For software, proper specifications and standards do not eliminate the creativity and elegance of code content, but limit excessive personalization, work together in a universally recognized and unified way, improve collaboration efficiency and reduce communication costs. Between the lines of the code is the blood of the software system, the improvement of the quality of the code is to step on the pit as little as possible, put an end to the repeated pit, effectively improve the stability of the system, the quality of the code.

2. Programming protocol introduction

2.1 Disable mana

No mana values (i.e., undefined constants) are allowed to appear directly in code.

// Counter example: Developer A defines the cache key. String key = "Id#taobao_" + tradeId; cache.put(key, value); // developer B uses the cache directly to copy the missing underline, // i.e. the key is "Id#taobao" + tradeId, resulting in a failure. String key = "Id#taobao" + tradeId; cache.get(key);Copy the code

A magic value is a value that appears magically without any definition in the code. It can be a number, a string, etc.

This is one of the more compelling regulations I remember.

When I first got into this business and started writing code, magic was flying around. Such a question would never have been considered, but then the pernicious consequences of doing so emerged.

  • Repetitive magic value, not concise enough, forced to death like reuse obsessive compulsive disorder!
  • It’s easy to make mistakes like the one above, such as missing underscores or misspelling a word.
  • Mana is difficult to concisely state what it means. For example, “0” and “1” that appear directly in code, who knows what that means?

So, you can define your constants by static constants or enumerations, which will wipe out the mana.

2.2 Strict Access Permission control

Class member and method access control is strict.

  • The constructor must be private if the object is not allowed to be created directly from the outside via new.
  • Utility classes are not allowed to have public or default constructors.
  • Class member variables that are non-static and shared with subclasses must be protected.
  • Class member variables that are non-static and used only in this class must be private.
  • Class static member variables must be private if they are used only in this class.
  • For static member variables, consider whether they are final.
  • Class member methods are called only from within the class and must be private.
  • Class member methods are only exposed to inherited classes, so limit them to protected.

This is recommended programming protocol, in fact, such a protocol is one of the characteristics of Java – encapsulation.

Access to any class, method, parameter, or variable should be strictly controlled. Too wide access range is not conducive to module decoupling.

When I write my own code, I use private as much as I can.

Gu Ju raised a very interesting question in the handbook:

If it is a private method, delete it if you want. If it is a public service member method, delete it if you want.

He made this analogy:

Variables like their own children, as far as possible in their line of sight, variable scope is too large, unlimited running around, then you will worry.

I think that really hits the nail on the head.

2.3 List disables remove/add in the for loop

Do not remove/add elements in foreach loops. The remove element must be iterator. If the operation is performed concurrently, the Iterator must be locked.

List List = new ArrayList<>(); list.add("1"); list.add("2"); Iterator iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); Iterator.remove (); if (delete element condition) {iterator.remove(); }} // For (String item: list) {if ("1". Equals (item)) {list.remove(item); }}Copy the code

I have also stepped on the trap of this mandatory protocol. In the counter example, when it performs the remove operation, it returns the following error.

java.util.ConcurrentModificationException

Specific reasons are not described in this article, interested readers can look up online friends.

2.4 Naming complex Boolean expressions

Do not execute complex statements in a conditional judgment other than the usual methods such as getXxx/isXxx. Assign the result of a complex logical judgment to a meaningful Boolean variable name to improve readability.

This recommended rule is one I highly recommend. Because of business needs, we can write very complex logical expressions in if statements. And, or, and unmixing operations, or even various method calls, are very difficult to understand.

It would be nice to give such a logical expression a name that is easy to understand (which I find more concise than comments).

Let’s look at a comparison example:

Final Boolean existed = (file.open(fileName, "w")! = null) && (...) | | (...). ; if (existed) { ... } public final void acquire(long arg) {if (! tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)){ selfInterrupt(); }}Copy the code

2.5 Exception Handling

For catch, distinguish between stable code and unstable code. Stable code is code that will not fail no matter what. For the catch of unstable code, distinguish the exception type as far as possible, and then do the corresponding exception processing.

I blushed when I saw this mandatory rule.

Because I’ve made the mistake of try-catching large chunks of code, which prevents the program from responding correctly to different exceptions and locating problems, is irresponsible.

In the scene of user registration, if the user enters illegal characters, or the user name already exists, or the password entered by the user is too simple, we should make classification judgment in the program and prompt the user.

2.6 Log Protocol

The production environment forbade the use of system.out or System.err output or the use of E.printStackTrace () to print the exception stack.

Printing logs using e.printStackTrace() takes up too much memory and locks up.

To print a string to the console, you need to have enough space in the block of memory where the string constant pool resides. However, because the e.printStackTrace() statement was trying to produce a stack of strings that were too long, memory filled up! A large number of threads output strings halfway through, waiting for memory to be freed, locking up and causing the entire application to hang.

In addition, logs are interlaced and difficult to read.

PrintStackTrace () uses the System.err output stream by default, which is two different streams from System.out, so it naturally intersects when printing. Moreover, the output stream is buffered, so there is also a randomness about when the output is specific.

Error (“”,e) is generally enough to print error logs.

2.7 database

Decimal type is decimal, and float and double are prohibited.

This is mandatory, and both floats and doubles suffer from a loss of precision when stored, and it is possible to get incorrect results when comparing values.

If you store data beyond the range of Decimal, it is recommended to split the data into integers and decimals and store them separately.

3. The conclusion

These are some of the guidelines I’ve taken from the handbook, along with some simple guides. I don’t know if you have some deja vu feeling.

The manual has seven chapters that cover virtually every aspect of Java programmer code.

How to get the manual, write more elegant and efficient code, please follow my public account “garden savage”, reply “PDF1”, you can get the Java development manual of Gujiu teacher.

Phase to select

  1. How many new Java8-15 features do you know?

  2. From the star of open source entrepreneurship to bomb building, finally delete library run away, what has he experienced?

  3. 11 Java Code Performance Optimization tips to Learn

Thanks for watching yijun@Monday Radio. If you feel good, quickly give me three support, let’s next period see each other.