In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to understand Java repetitive code". In daily operation, I believe many people have doubts about how to understand Java repetitive code. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to understand Java repetitive code"! Next, please follow the editor to study!
Catalogue
Why does a method have parameters?
The problem of long parameter list
Solution
many littles make a mickle
Dynamic and static separation
Farewell mark
Summary
Experienced programmers should have seen that a method has dozens or hundreds of parameters.
Why does a method have parameters?
Because information needs to be shared between different methods.
However, there is more than one way to share information between methods, in addition to parameter lists, there are global variables. But global variables can always bring surprises, so it is also a trend for major languages to cancel global variables.
However, there is still information to be passed between methods, and global variables cannot be used, so parameters are the only choice, so as long as you think of any information to pass to a method, it will be directly added to the parameter list, and the parameter list is getting longer and longer.
The problem of long parameter list
If the parameter list is too long, it will be difficult for you, a crud programmer, to fully control the logic.
Therefore, the crux of the problem is the large number, and the key to the solution is to reduce the number of parameters.
The solution gathers sand into a tower
A simple way to create a blog:
Public void createActicle (final String title, final String introduction, final URL coverUrl, final ActicleType type, final ActicleColumn column, final String protagonists, final String tags, final boolean completed) {. Acticle acticle = Acticle.builder .title (title) .examples (introduction) .coverUrl (coverUrl) .type (type) .column (column) .proagontists (protagonists) .tags (tags) .build (completed) .build (); this.repository.save (acticle);}
The parameter list contains all kinds of information that a blog needs to have, such as: blog title, blog profile, cover URL, blog type, blog belonging column, protagonist name, blog tag, whether the blog is finished.
If you just want to understand the logic, you may also find the parameter list reasonable. After all, it sends all the information needed to create a blog to the method, which is the initial point of view for most people to understand the problem when faced with a piece of code.
Although writing code in this way is easy to understand, it is not enough for you to find the problem.
Now the product requires that a message be added to the blog to identify whether the blog is a contracted blog, that is, whether this blog can be charged, what to do?
It's very simple! I will add a parameter directly. Many shit mountains come from this way, add up a little, and quantitative change causes qualitative change!
All the parameters here are necessary to create a blog. So, what you can do is encapsulate these parameters into a class, a parameter class for creating a blog:
Public class NewActicleParamters {private String title; private String introduction; private URL coverUrl; private ActicleType type; private ActicleColumn column; private String protagonists; private String tags; private boolean completed;...}
This leaves only one parameter left in the parameter list:
Public void createActicle (final NewActicleParamters parameters) {...}
So encapsulate the parameter list into an object!
Would it be superfluous to just encapsulate a list of parameters into a class, and then, when using these parameters, you need to take them out one by one? It's like this:
Public void createActicle (final NewActicleParamters parameters) {... Acticle acticle = Acticle.builder .title (parameters.getTitle ()) .coverUrl (parameters.getCoverUrl ()) .type (parameters.getType ()) .channel (parameters.getChannel ()) .protagonists (parameters.getProtagonists ()) .tags (parameters.getTags ()) .building (parameters.isCompleted ()) .build (); this.repository.save (acticle);}
If you feel the same way, you haven't formed an understanding of software design yet. We do not simply encapsulate the parameters into classes, from a design point of view, we introduce a new model.
The encapsulation of a model should be based on behavior.
There was no such model before, so I can't imagine what behavior it should have. Now that the model is produced, it should have its own supporting behavior.
So what is the behavior of this model? Build a blog object, which is clear, and the code can be refactored further:
Public class NewActicleParamters {private String title; private String introduction; private URL coverUrl; private ActicleType type; private ActicleColumn column; private String protagonists; private String tags; private boolean completed; public Acticle newActicle () {return Acticle.builder .title (title) .examples (introduction) .coverUrl (coverUrl) .type (type) .column (column) .protagonists (protagonists) .tags (tags) .build (completed) .build () }}
The method of creating a blog has been greatly simplified:
Public void createActicle (final NewActicleParamters parameters) {... Acticle acticle = parameters.newActicle (); this.repository.save (acticle);}
"how to expand demand"? If the demand expands and you need to increase the content needed to create a blog, then the parameter list is constant and relatively stable.
Then this class will continue to expand and become a large category, so what should we do? How to solve the big category?
Dynamic and static separation
Not in all cases, parameters belong to the same class:
Public void getChapters (final long acticleId, final HttpClient httpClient, final ChapterProcessor processor) {HttpUriRequest request = createChapterRequest (acticleId); HttpResponse response = httpClient.execute (request); List chapters = toChapters (response); processor.process (chapters);}
Get the corresponding chapter information according to the blog ID.
It is purely based on the number of parameters, and the number of parameters is small.
If you just look at this method, it may be difficult to find a direct problem. The absolute quantity is not the key point, and the parameter list should be as few as possible.
Among these parameters, the acticleId passed in each time is different and varies with the request. But the two parameters httpClient and processor are the same, because they both have the same logic, there is no change.
That is, the change frequency of acticleId is different from that of httpClient and processor.
Different directions of data change are also different concerns. What is shown here is the typical dynamic data (acticleId) and static data (httpClient and processor), which are different concerns and should be separated.
In this scenario, the static data can be a field of the class in which the method is located, and only pass what changes each time as a parameter. According to this idea, the code can be changed to look like this:
Public void getChapters (final long acticleId) {HttpUriRequest request = createChapterRequest (acticleId); HttpResponse response = this.httpClient.execute (request); List chapters = toChapters (response); this.processor.process (chapters);}
This bad smell is actually a software design problem, and the code lacks the proper structure, so the parts that should belong to the static structure are passed back and forth in the form of dynamic parameters, virtually lengthening the parameter list.
The long parameter list can be encapsulated by a class, but the prerequisite for encapsulating this class is that these parameters belong to the same class and have the same reason for change.
If the parameters of the method change at different frequencies, it depends on the situation. For the static part, as we have seen earlier, it can be a part of the software structure, and if there are multiple frequency changes, we can also encapsulate multiple parameter classes.
The farewell mark public void editChapter (final long chapterId, final String title, final String content, final boolean apporved) {...}
The ID, title and content of the chapter to be modified. The last parameter indicates whether the change is approved directly.
The first few parameters are necessary to modify a chapter, focusing on the last parameter.
From a business point of view, if it is edited by the author, it will be reviewed later, and if the editor edits it, the review will be passed directly, because the editor itself plays the role of auditor. So, you found that this parameter is actually a tag that indicates that the next processing flow will be different.
The use of tag parameters is a common technique for programmers when they are beginners to program. It is this technique that is so easy to use that it leads to wanton drift in the code. There are tags not only in variables, but also in parameters. Many long parameter lists contain various tag parameters.
In the actual code, the current value of each tag must be judged carefully in order to handle it.
A simple way to solve the tag parameters is to split the different paths represented by the tag parameters.
One method here can be split into two methods, one responsible for "normal editors" and the other for "editors that can be directly reviewed."
/ / ordinary editors need to audit public void editChapter (final long chapterId, final String title, final String content) {...} / / directly approved editors public void editChapterWithApproval (final long chapterId, final String title, final String content) {.}
Tag parameters take many forms in code, including Boolean values, enumerated values, strings, or integers. They can be taken apart by means of split methods. In refactoring, this technique is called removing tag parameters (Remove Flag Argument).
Only short code, we can have a better grasp, and to write short code, we need to be able to "separate concerns."
Summary
The main way to deal with a long parameter list is to reduce the number of parameters, and the most direct way is to encapsulate the parameter list into a class. But not all cases can be encapsulated into classes to solve, we also need to analyze whether all parameters have the same frequency of change.
If the change frequency is the same, it is encapsulated into a class.
If the frequency of change is different:
Static invariant can be a part of software structure.
Multiple changing frequencies can be encapsulated into several classes
In addition, tag parameters often appear in the parameter list, which is another important reason why the parameter list is longer. For such tag parameters, one solution is to split the method into multiple methods based on these tag parameters.
Reduce the list of parameters, as few as possible.
At this point, the study on "how to understand Java repetitive code" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.