In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to write the least code". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Java: I want to return multiple return values
Show the multiple return values of Go:
Package main import "fmt" / / returns X + Y and X * Y func Computer (X, Y int) (int, int) {return X + Y, X * Y}
As we all know, Java only supports a single return value. In general, if we need to return multiple objects, we will select a container or create a new class according to the code semantics to package the data we need.
Is there a problem with this? Of course, there is no problem, but the flaw is that there may be intermediate classes that have no semantics but have to exist. I personally discuss this kind of code very much, so how to solve this problem?
First, you need to realize that the solution must meet several requirements:
Code reusable
Semantics should be clear
Safety
In this case, we can use generics to meet the requirements of reuse and semantic clarity, and intermediate classes to meet the requirements of code security. The code is as follows:
Public class MultipleTwoReturn {/ * * first return value * * / private final A first; / * * second return value * * / private final B second; public MultipleTwoReturn (A first, B second) {this.first = first; this.second = second;} / / omit Get method}
At the same time, we can rely on inheritance to allow the utility class to extend more parameters:
Public class MultipleThreeReturn extends MultipleTwoReturn {/ * * third return value * * / private final C third; public MultipleThreeReturn (A first, B second, C third) {super (first, second); this.third = third;}}
Test class:
Public class MultipleApp {public static void main (String [] args) {MultipleTwoReturn returnTest = MultipleApp.getReturnTest (); System.out.println (returnTest.getFirst ()); System.out.println (returnTest.getSecond ());} private static MultipleTwoReturn getReturnTest () {MultipleTwoReturn demo = new MultipleTwoReturn (0, "Kerwin Demo."); return demo;}}
In essence, it is still an ordinary object, but the power increases dramatically after adding generics! Because the generic constraints are enforced in the method definition, the semantics are very clear, and the above non-semantic intermediate classes can be completely eliminated. Of course, this approach is not recommended for some necessary, business-meaningful assembly classes.
Generics: I want to new an object
Did you have this idea when you were learning Java generics? I want to use it as a generic constraint, but I need a T for new, but Java doesn't new it?
A long time ago, I was writing a general Java crawler interface, in which a function is to input the target web page to obtain the Bean designed for different web pages, which is roughly as follows:
Public interface SpiderBeansHandle {/ * * get Url * * / String getUrl (); / * get Cookie * * / String getCookie (); / * get CSS selector * * / String getSelector (); / /.... }
The key point in the middle is how to get this Bean. At that time, I had only one idea: new a T.
It turns out that I was too naive?
But another way of thinking, since the new doesn't come out, I'll go back for a while, so the code comes out.
Public interface SpiderBeansHandle {/ * get Url * / String getUrl (); / * get Cookie * / String getCookie (); / * get CSS selector * / String getSelector (); / * parse Element * @ param element element * / T parseElement (Element element) / * Get Beans * @ param handle Bean object | handle object * @ param Bean type * @ return List * / static List getBeans (SpiderBeansHandle handle) {List list = new ArrayList (); List elements = SpiderUtils.getElementWithCookie (handle.getUrl (), handle.getSelector (), handle.getCookie ()) For (Element element: elements) {T bean = handle.parseElement (element); if (bean! = null) {list.add (bean);}} return list;}}
The key step is:
/ * parse Element * @ param element element * / T parseElement (Element element)
So what's the use of this little trick? If you look closely, will it look like a variant of a design pattern? That's right! There is only one truth: template method pattern
I just mentioned that I need a general interface to deal with crawlers, because simple crawlers just get the url and request, parse the details into their own Bean, and then get a list, then when developing business code, there must be some scenarios and requirements with a high degree of consistency, so using this design solution can greatly reduce repetitive code.
Method: what do you want?
Have we ever encountered this kind of problem when writing code? Wrote a tool method, but the function is too single, although the single principle is good, but a small logic to write a bunch of methods, always feel powerless, how to solve it?
The functional programming provided by Java8 can help us solve this problem to some extent, such as:
/ / write a tool method that gets the list of files and determines whether it ends with txt. The novice will write public static File getFileWithTxt (String path) throws IOException {File file = new File (path); if (! file.exists ()) {throw new IOException ("File is not exist.");} if (file.getName (). EndsWith (".txt")) {return file;} return null;}
Veterans usually pass .txt as a parameter, but what should I do one day when I need to determine file size, file length, or even file content? Write N more?
The best solution is to pass in the Predicate predicate, let the caller customize the processing logic, and then copy the most commonly used logic based on this method, extensible Max! The code is as follows:
/ * folder predicate matching * @ param file file * @ param predicate predicate matching * @ return List * @ throws IOException IOException * / public static List listFilesInDirWithFilter (File file, Predicate predicate) throws IOException {if (! file.exists ()) {throw new IOException ("File is not exist.");} List fileList = new ArrayList () If (file.isDirectory ()) {File [] files = file.listFiles (); for (File f: Objects.requireNonNull (files)) {fileList.addAll (listFilesInDirWithFilter (f, predicate));} else {if (predicate.test (file.getName () {fileList.add (file);}} return fileList;}
Similarly, for example, dealing with IO, directly to the code:
Public static void readLine (BufferedReader br, Consumer handle, boolean close) {String s; try {while (s = br.readLine ())! = null)) {handle.accept (s);}} catch (IOException e) {e.printStackTrace () } finally {if (close & br! = null) {try {br.close ();} catch (IOException e) {e.printStackTrace ();}
What do you want to do?! Forget it. You can do whatever you want. Make yourself at home.
Overload: write more and write less
Writing more is also for writing less. this sentence sounds very contradictory at first, but experienced programming partners should be able to realize the power of method overloading, especially when writing tool classes or underlying interfaces. It is recommended that we first write a large and comprehensive internal method, and then reload it little by little as needed, there will be unexpected benefits.
The simplest example is as follows:
/ / Root method private static void readLine (BufferedReader br, Consumer handle, boolean close) {String s; try {while (s = br.readLine ())! = null)) {handle.accept (s);}} catch (IOException e) {e.printStackTrace () } finally {if (close & & br! = null) {try {br.close ();} catch (IOException e) {e.printStackTrace () } / / overloading method-public static void readLine (String path, Consumer handle, boolean close) {try {BufferedReader br = new BufferedReader (new FileReader (path)); readLine (br, handle, close);} catch (FileNotFoundException e) {e.printStackTrace () }} / / overloading method 2: public static void readLine (String path, Consumer handle) {readLine (path, handle, true);}
Overloading can make our method invocation rich and colorful. In the case of clear semantics, writing code is like divine help, and with functional programming, the ability of tool classes or underlying interfaces can be greatly enhanced.
At the same time, when we need to adjust a method logic, we can also use the way to continue overloading to minimize the impact and try not to move the code of other modules.
Ultimate: from Design pattern to Abstract
It's not so much how to write the least code as how to write only the really valuable code.
When faced with this problem, our first reaction must be the design pattern. For example, the template method pattern mentioned in the generics section above, I would like to recommend my previous article:
Template method of "Learning together Series": I only need 5 minutes to write SSO.
General part of design patterns: from why principles are needed to actual landing
Through a good design pattern or its deformable body, we can get code with high cohesion and low coupling, which is a very good idea.
Another idea, everyone agrees on one point: program = algorithm + data structure, choosing the right data structure can get half the result with twice the effort. For example, when we do similar folder requirements, we will think of using linked list or tree structure. When doing things such as: how to efficiently send birthday messages to users, you will think of using heap structure (compare the maximum value in the heap with the current time, continue to iterate if satisfied, reduce traversal), and so on.
This is actually abstract, deep or shallow. When I first learned Java, the teacher would say: everything is an object. Let's take a look at what the above techniques correspond to.
Multiple return values: encapsulated objects + generic constraints
Generics: public interfaces that encapsulate objects, highly abstract
Functional method: treat a method as an object
Overloading: the continuous evolution of object methods (behaviors)
This is the end of "how to write the least Code". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.