Write correct code

Source: Internet
Author: User

I was thinking about the correct code when I wrote this title? Can the code run correctly as required? Isn't it the correct code? If the code still has high performance, it can even be called very correct. In fact, this is not accurate. If the code is instant noodles, it can be thrown into the waste bin after eating. I think this is a good understanding. But in fact, after writing a piece of code, you may need to constantly modify and upgrade and release a new version. In this process, many people will join in, so after many changes, code can be quickly understood by others, so a clear logical structure and good readability are the correct criteria.

But we are not unfamiliar with the solution to this problem-architecture. However, this term makes many coder feel that they are faced with a difficult problem: Ah, how can I draw a mirage before seeing the Mirage? You can't help sweating. At least I think so. I believe that, even architects with such capabilities are not from the planet Krypton, and they are born with super capabilities. If you like to raise the bar, you have to say that when knuth is very small, you can use the computer as a printer, but you just need to repeat the macro picture in your mind. Then I have to convince myself that the hacker does not count. In order not to tell ghost stories and scare away children, the architecture can be changed to a friendly word and a design model. We are familiar with this thing. They are actually little tools in the craftsman's hand, which can help us build a decent hut. When I first came into contact with the design pattern, I found that although there are more than a dozen patterns, it is not easy to understand. However, when I started writing code, I found that these modes didn't help me at all, and the code is self-contained. It seems that there is no need or some modes are not available. I cannot use the design mode to use the design mode. Well, the last point is correct. I think this time is actually too close to the program. I will come back two months later and check again. The idea may change.

Graham believes that programmers and painters are essentially the same. painters or painters only have a subject and a general layout when drawing works, it also fills in the mind of the painter when you add it to the canvas. The process of programming is the process of talking to the program. The process of writing is the process of thinking. During the process of writing, the code is gradually full. Do not look at writing the first Int, the outline of the entire program is clearly visible, the program structure is modified step by step, and the architect is also developed a little bit. It seems a little far away, so we can go back to the topic and the design pattern can help us write the correct code. But how to use it? This is what we want to express in the above sections. We are always aware of the difficulties we encounter during the compilation process, and think about how to use elegant methods to solve them. Naturally, we will integrate them into the design model, try to understand the core concepts of the architecture.

Let me give you a small example. After writing a program, you may not conduct overall debugging. Unfortunately, this is a fact. This program requires a lot of service interaction with real devices, but these services cannot be provided in a simulated environment. Unfortunately, I have to wait a month to have the devices that meet the requirements, so the only thing you can do is test the UI process in a simulated environment. The method of testing the UI is quite primitive. I believe anyone who is mentally healthy will be surprised to see King Kong on the top of the Empire State Building. Yes, I will temporarily comment out all the code that needs to call the service. I admit that this is a shameless method that I did not find in the Java environment such as Conditional compilation, but fortunately I soon stopped this shameful behavior. Because, I not only need to add some test statements just for debugging in the code, but what's more terrible is that after going out for a cup of coffee, I also forgot where it was commented out and should be restored.

After realizing that this violence is not conducive to a harmonious society, I began to think about how to perform a comprehensive test before getting on the device. Fortunately, I had enough time to wait for the device. The first thing I think of is that we can build a simulated service and use this simulated testing service (testservice) during testing ), switch to a real device service during a real machine test ). Now, all I need to do is modify the code for using the device Service to use the test service, that is

Realservice. doservice () ----> testservice. doservice ()

No other code needs to be modified. I only need to perform a Ctrl + h operation. But with this dangerous replacement, I think I will be worried at night. So why not abstract the implementation? As mentioned in countless textbooks: interface-oriented programming rather than implementation-oriented.


Maybe you thought of doing this in the first step. I want to admit that you are smarter than me. don't dream about it. It's not an extraordinary programmer. In other words, it seems to be much better now. In the code, top-level services are used, similar to iservice. doservice (), yes, you only need to switch between the real service and the Test Service where the service is obtained, and finally the thing becomes more reasonable. In addition, it seems that the dependencyinjection mode can be used to make the design more beautiful. Why not? I modified the code and obtained the service from the uniform entrance. At this time, the service is abstracted using the iservice interface. The whole program does not know whether to use a real service or a test service, I configure it myself to determine whether realservice or testservice is injected.

If I stop it, I believe many people will say, well, you are right, but wait, how can we do it? Yes, my own code can only be designed by myself. Do anyone blame me for throwing it to the test team's little sister. Well, I want to write the program running mode in the configuration file, such as run_mode = test, then the program will establish a Test Service and inject it into the request service. Now I need a creator. The Code requesting the service only knows the service creator. It tells the creator, hello, I want to serve! Then the creator said yes. He looked at run_mode = test in the configuration file and then picked up a test service to the requester and said, "serve you! Yes, it's just that simple. I thought so in my mind at the time. I hope that you will understand this. This is an abstract factory model (Abstract
Factory ).


The service requestor maintains an icreator (I use creator instead of factory for a reason) reference. When the requestor needs to use the service, based on the configuration file, icreator decides whether to use the testservicecreator or the realservicecreator, and then each of them produces their own services and delivers them to the requester, complete simple dependency injection.

Now pause and review the current design. From the initial direct access to and use of the Service, it is now the use of the Creator to get the service, and the objects involved in the process are added, it seems that the complexity of the program has been increased. But in fact, the program is more beautiful and correct now, and the service user and service get points are gone, I can finally start debugging the main program without worrying about being laughed at by you. If you need to modify the service or add a new service in the future, you only need to add the new service and its creator. The service call code does not need to be changed. Reducing system coupling and improving system scalability is the core purpose of countless current development frameworks. Understanding this central idea (which reminds me of the Primary School Chinese teachers ), then you can master these development frameworks so that they can be integrated into your own internal strength rather than the cold sword in your hands.

Things seem to be perfect here, but wait, there's something other than textbooks. There is a service that is very special. I want to say "special" is really a terrifle word. If you say a girl is very special, I know that you fall in love with her, she certainly attracts you in some aspects, but if you encounter something special during programming, it is worth a headache. It means you have to use special code for special processing. This headache is service A, which requires the requester to gradually fill in some configuration parameters, and finally use the services obtained based on these configuration parameters, such:

Servicea. config (PARAM );

Servicea. doservice ();

Gradually filling, this requirement ruined all of my previous designs, but I calmed down later, and I don't want to return to the previous bad design because of a special requirement. But this step-by-step filling reminds me of another design, the builder mode. The design problem to be solved is the gradually generated object creation mode. Well, Let's combine the factory mode with the generator mode, this is why I named the previous builder "creator" because it is neither a factory nor a builder. The basic idea is that the requester submits a service request to the Creator, configures the Creator step by step, and then creates a service based on these configuration parameters, the Creator serves as a configuration parameter forwarder here, and the final implementation is the service itself. Finally, the Creator transfers the configured service to the requester.


The final result is similar to the original factory model, but the difference is that the current factory can be viewed as a dynamic creation, while the orange part can be regarded as a generator model. The service of the program is created as follows:

Requester. creator. Configservice (ARGs). createservice (). doservice ();

The last step after completing step-by-step configuration is to return the service object. When designing the interface, the configuration method is defined:

Icreator Configservice (ARGs)

Therefore, you can configure it continuously in use:

Creator. Configservice (...). Configservice (...).........

This method is called method chain. Method chain is a useful method in programming, but some people do not agree, because it increases the difficulty of debugging and makes it difficult to track the source of exceptions, however, its readability is much higher than that of the box assignment code. In general, the advantage is greater than the disadvantage.

OK. Now the Special Service has been solved. You can test it with confidence.

After writing the correct code, I forgot which book I saw this sentence. I only tried to watch myself think twice when coding, write elegant code as much as possible, eventually merged into the sea.

I wish and I believe.

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.