Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write efficient code by Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you Java how to write efficient code, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Most programmers are aware of the importance of consistency itself. But generally speaking, the consistency of everyone's understanding is shown in a larger aspect, for example, is database access called DAO or Mapper,Repository? Within a team, there is a uniform standard, but at the coding level, the requirements are often less detailed. That's why we see all kinds of inconsistencies in the code details. Let's analyze the problem from a specific piece of code.

Inconsistencies in naming

Once, I saw a piece of code like this in a code review:

Enum DistributionChannel {WEBSITE KINDLE_ONLY AL}

Using the distribution channels of tagged works, from the content of this code, we can see that the current distribution channels include:

Website (WEBSITE)

Only on Kindle (KINDLE_ONLY)

Omni-channel (ALL)

Faced with this code, I was a little confused, so I asked a question:

What do WEBSITE and KINDLE_ONLY mean, respectively?

WEBSITE said the work would only be published on our own website, while KINDLE_ONLY said the work would only be available in Kindle's e-book store.

Does both mean that they are only released in a single channel?

Yeah!

Since both have the meaning of being released on only one platform, why not call them XXX or XXX_ONLY?

Well, you have a point.

The reason for the problem is that the names WEBSITE and KINDLE_ONLY are not the same here.

Code that expresses a similar meaning should have a consistent name. For example, many teams write business to the service layer, and services are usually named XXXService.

Once inconsistent names appear, they usually have different meanings. For example, for business components that are not business entrances, their names will be different and will be more in line with their specific business behavior, such as BookSender, which means sending works to the translation engine.

In general, the meaning of enumerated values should have the same business meaning, and once there is a difference, I need to determine where the difference is, which is the reason for my question.

Obviously, when the author of this code names the two enumerated values, he only considers what they should be named, but ignores the role that the enumerated value plays in the whole.

To understand this, it is easy to change, and later, the code is unified into one form:

Inconsistent / / generation timestamps in enum DistributionChannel {WEBSITE KINDLE AL} scenario public String nowTimestamp () {DateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); Date now = new Date (); return format.format (now);}

When a system sends a request to another system, it needs to take a timestamp. Here, the timestamp is converted into a string type according to a certain format, mainly for transmission, which is convenient for other systems to identify and debug in the development process.

There is no problem with the implementation of this code itself. It even takes into account the multithreading problem of the SimpleDateFormat class itself, so it creates a new SimpleDateFormat object each time.

Then why did I say there was a problem with it? Because this is the way it was written before Java 8, and the version of Java we use is after Java 8.

For a long time, Java's date-time solution has been a controversial design. There are many problems, some concepts are easily confused (for example, which should be used by Date or Calendar), some interfaces are not intuitive (for example, the setMonth parameters of Date are from 0 to 11), and some implementations are easy to cause problems (for example, the previously mentioned SimpleDateFormat needs to consider the problem of multi-thread concurrency). You need to build a new object one at a time.

This mess has been around for a long time, and many people are trying to solve the problem (such as Joda Time). Starting with Java 8, Java's official SDK draws on a variety of libraries and introduces a new date-time solution. This solution is completely independent of the original solution, that is to say, we can handle all our work with this new solution.

Our current project is a completely new project, and the version we are using is Java 11, which means that we can use the date-time solution introduced from Java 8. So, our agreement in the project is that all date and time types are to use this new solution.

By now you probably know what the problem is. In this project, our requirement is to use the new date-time solution, and the SimpleDateFormat and Date here are part of the old solution. So, while there is no problem with the implementation of the code itself, it is a bad smell in the project as a whole, because it is not consistent with the rest of the project.

Later, a new solution was used:

Public String nowTimestamp () {LocalDateTime now = LocalDateTime.now () return now.format (DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss");}

The reason for this is that there are multiple solutions to the same problem in a project, and if there is no unified agreement, project members will randomly choose the solution according to how they feel when they write the code, resulting in inconsistency.

Why are there multiple solutions in a project?

time

With the passage of time and the development of technology, people will take the initiative to realize the problems of the original solution, and they will put forward new solutions, such as the Java date-time solution here, which is caused by the evolution of JDK itself over time. Some projects take a long time and there will be similar problems.

Introduced for one's own reasons

For example, introduce a library that does the same thing in your code. For example, to determine whether the string is empty or empty, there are Guava and Apache Commons Lang, both of which can do the same thing, so programmers will choose one of them to use according to their familiarity, resulting in code inconsistency.

These two libraries are the basis of many libraries, and the corresponding dependencies often appear in our code because of the introduction of other libraries. Therefore, we must agree on which approach is our standard practice in the project, in case we go our own way. For example, in my team, we chose Guava as the base library, because its style is relatively modern, so the team agreed that similar operations will prevail on Guava.

Inconsistent public void createBook (final List bookIds) throws IOException {List books = bookService.getApprovedBook (bookIds) CreateBookParameter parameter = toCreateBookParameter (books) HttpPost post = createBookHttpRequest (parameter) httpClient.execute (post)} in the code

The code to create the work in the translation engine:

First of all, get the approved works according to the ID of the works to be processed

Then, send a HTTP request to create the work in the translation engine

What's the problem?

The inconsistency of this code, these codes are not a level of code!

The first is to get the approved work, which is a business action, and the next three lines are actually doing one thing, that is, sending a request to create the work, these three lines of code:

Create the requested parameters

Create a request based on the parameters

Finally, send the request.

Together, three lines of code complete the task of sending a request to create a work, which is a complete business action.

Therefore, the code in this function is not at the same level, some are business actions, some are business action details. With this in mind, extract the code for these business details into a function:

Public void createBook (final List bookIds) throws IOException {List books = bookService.getApprovedBook (bookIds) createRemoteBook (books)} private void createRemoteBook (List books) throws IOException {CreateBookParameter parameter = toCreateBookParameter (books) HttpPost post = createBookHttpRequest (parameter) httpClient.execute (post)}

As a result, the original functions (createBook) are all business actions, while the extracted functions (createRemoteBook) are all details of business actions, and their statements are all at the same level.

Distinguish between different levels of code, basic skills or separate concerns!

Once you break down the different concerns, you can further adjust the structure of the code.

Like the previous split method, we already know that its role is to make a request to create a work, which is not essentially part of this business class.

So, you can also adjust this part by introducing a new model:

Public void createBook (final List bookIds) throws IOException {List books = this.bookService.getApprovedBook (bookIds); this.translationEngine.createBook (books);} class TranslationEngine {public void createBook (List books) throws IOException {CreateBookParameter parameter = toCreateBookParameter (books) HttpPost post = createBookHttpRequest (parameter) httpClient.execute (post).}

When it comes to layering, most people only think of the layering of the model, and few people think of layering in the statements of the function. Various levels of code are mixed together, and many problems follow, most typical of which are long functions.

What we are still doing is model layering, but this time the starting point is the statement of the function. The meaning of "separate concerns, the smaller the better." Observe that the granularity of the code is small enough, and many problems will naturally be exposed.

When programmers start to write tests, there is a typical problem: how to test a private method. Some people suggest using some special abilities (such as reflection) to test. My answer to this question is, don't test private methods.

The reason why I want to test private methods is that the separation of concerns is not done well, mixing different levels of code together. In the previous code, it is still difficult to test the previous createRemoteBook method, but after the adjustment, the TranslationEngine class is introduced, and the method becomes a public method, which can be tested according to a public method, and all the problems are solved.

The technical problem that many programmers struggle with is actually a software design problem. Don't solve a problem that should not have been solved by skillful tricks.

For a team, consistency is very important and an important way to reduce the cost of collective cognition. We have seen separately:

Inconsistencies in naming

Inconsistencies in the scheme

Inconsistencies in the code.

Code with similar meaning should have similar naming, inconsistent naming means different meaning, need to give an effective explanation.

Inconsistencies in the scenario:

Due to the long-term evolution of the code

There are libraries in the project that perform the same function.

Whatever the reason, the team needs to agree first to ensure that everyone writes the code in the same way.

Inconsistencies in code often involve writing different levels of code together, most typically mixing business-level code with implementation details. The way to solve this problem is to extract different levels of code into different functions, and the premise of all this is to separate concerns, and the design problem is still behind this code problem.

Keep the code consistent at all levels.

These are all the contents of the article "how to write efficient code in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report