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 reconstruct 3000 lines of code into 15 lines

2025-01-29 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 reconstruct 3000 lines of code into 15 lines". In the operation of practical cases, many people will encounter such a dilemma, so 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!

ReFactor 3,000 lines of code into 15 lines

I just graduated that year and joined the present company. The company is engaged in data center environment monitoring, which is full of embedded, precision air conditioning, bus, RFID concepts, I do not understand one. Fortunately, the old client that the company used to write in Delphi was too slow, and then I made a replacement for Webform. I happen to know Asp.Net quite well, and my lack of knowledge of the business does not prevent me from calling myself a programmer in this company.

Small companies also have the advantages of small companies, with few people, so they will soon be responsible for code development. Of course, I will work on this intelligent management system of the data center.

This system is very large, especially powerful is to support client configuration, and then dynamically generate web pages, and the data can be monitored in real time through Socket (I really didn't know anything about network programming at that time). For me at that time, it was really tall, big and high! At that time, it took more than half a month to understand the whole system to be able to debug and write some simple pages.

In the process of maintaining the system, you have to extend some functions from time to time, so you come into contact with the following class:

See, it is the product of the most popular three-tier architecture at that time, for the fledgling boy, what a professional header comment, and even if there is reflection, this constructor can still be static and private? At that time, I was on my knees when I first came into contact with such a high-end code.

However, when I write too many classes, I feel more and more awkward, which is the following code:

Every time I add a table, in addition to changing the interface, DAL and BLL, I also have to add a method to this factory class. I am really tired to cramp. Even if I have the artifact recommended to me by the G worker of the company at that time-- the soft code generator, this paste and copy several times, it also makes me feel extremely tedious. Sometimes I get a little tired from typing, and I correct the copied code, your sister. Is that what programmers are supposed to do? no, absolutely not! I think of a wise saying: when you think the code is repeated in the program, it should be refactored. Yes, under the guidance of this sentence, I began to struggle and decided to challenge this high-end code. Facts have proved that the power of thought is infinite.

So, how to modify it? after careful observation, it is found that the generation of className is very similar to the returned type, except that one is the class name and the other is a string, which should be associated with each other. So google for a while (at that time GFW is not rampant ha), vaguely found the word "reflection", after in-depth understanding, I am sure it can be completed.

Next, there is the type of return, the type of return is not fixed, but seems to be very regular. This seems to have been seen somewhere, by the way, templates, C++ courses, so google again, learned that generics are used in C # instead of C++ templates. After learning generics and reflection, and referring to some online articles, I came up with the following code:

Yes, this is it, the most popular factory class in the era of three-tier architecture.

Look at the original roll more than a dozen screen code, into more than a dozen lines of code, really cool to the bone, too clean! The only thing that worries me is that when I enter the company, it takes the amount of code to help the company apply for software copyright. Evaluate the size of the software according to the number of lines of code. If the boss knows that I not only did not increase the amount of code for the company, but also reduced it, will you fire me immediately? I didn't dare to show my excellent results to our boss.

Fortunately, this code not only did not have any problems, but also avoided the problem that former colleagues always copied the code after adding a class, but did not modify it correctly, which greatly improved the efficiency. Although I didn't dare to announce the fruits of my labor, this successful modification completely put me on the road to code refactoring.

Seeing here, we should know whether this case is real or not. I believe that the code farmers who have seen this kind of code since 2008 are definitely no less than me. So, what do I want to tell you?

Think more about it in the process of programming

The idea of programming is very important. Please read more classic books.

Focus on the small and slowly restructure, especially in dealing with a large system

When it repeats itself, you should consider refactoring

The less code you paste and copy, the more stable your system will be.

Use less code generators

Let's analyze why my predecessors wrote the above code. I can sum up the following points:

Because of the use of dynamic soft code generator, it is convenient to generate code, so I don't think much about it.

I understand the concept of three-tier architecture, but apply it without thinking about it.

When it comes to repetitive code, there is no concept of refactoring, which is a matter of thought-- thought is more important than your ability.

So far, many people still use code generators, so how should we deal with this problem? I think the code generator can really save you a lot of work, but use less. Most of the repetitive work can be solved through the framework, for example, like the three-tier architecture, the code generator is really needed, that is, the Model class, and the rest can be done in the framework.

So you should try your best to think about how to reduce your repetitive work in the framework, rather than relying on the code generator. In addition, if you are still using the relevant code generation tools, please redefine the code template of the "dynamic soft code generator" and write your own template, or use CodeSmith to completely develop your own code generation, because the code template is really messy, such as the following code:

For (int n = 0; n < rowsCount; nails +) {model = new DBAccess.Model.eventweek (); if (dt.Rows [n] ["GroupNo"] .ToString ()! = "") {model.GroupNo=int.Parse (dt.Rows [n] ["GroupNo"] .ToString ()) } if (dt.Rows [n] ["Week0"]. ToString ()! = "") {model.Week0=int.Parse (dt.Rows [n] ["Week0"] .ToString ());} if (dt.Rows [n] ["Week1"]. ToString ()! = ") {model.Week1=int.Parse (dt.Rows [n] [" Week1 "]. ToString ());}

First of all, can't you use var row=dt.Rows [n] instead? Second, how low is the performance if you throw an exception using int.Parse directly? Again, if there is any change in this code, don't I want every dt.Rows [n] to change it?

Don't reinvent the wheel.

Let's take a look at some other code:

Public List GetDevices (string dev) {List devs=new List (); int start=0; for (int iTunes I 0) {var asmCache = new Dictionary (); foreach (var bundle in bundles) {try {if (! asmCache.ContainsKey (bundle.Category)) asmCache.Add (bundle.Category, Assembly.Load (bundle.AssemblyName)) Var handler = (ITaskHandler) asmCache [bundle.Category] .CreateInstance (bundle.ClassName, false, BindingFlags.Default, null, new object [] {this, bundle}, null, null); _ taskHandlerBundles.Add (bundle, handler) } catch (Exception e) {NLogHelper.Instance.Error ("load bundle [Name: {0}, Assembly: {1}: Class: {2}] exception: {3}", bundle.Name, bundle.AssemblyName, bundle.ClassName, e.Message);}}

Modify MainEngine code

Class MainEngine:IEngine {private NewFuncClass newCls=new NewFuncClass (); public MainEngine (ConfigSettings config) {RegisterTaskHandlerBundles ();} public void Start () {_ taskHandlerBundles.Start ();} public void Stop () {_ taskHandlerBundles.Stop ();}}

OK, now let's take a look at how to implement the original new functionality: you just need to create a new class according to the specification, inherit the ITaskHandler interface, and implement the interface's methods. Finally, add a new record to the XTGL_ Service Bundle table. Let's see what the benefits of this are:

The new class just needs to be written according to the specification and has no effect on the MainEngine code at all. You can even write this MainEngine code in a new Dll.

This business class of the new function is decoupled from the original code, so it is very convenient to test the business of the new function without considering the impact of the original framework.

The business class of the new function is completely separated from the architecture. In rewriting the code, as long as we ensure the stability of the interface, no matter how we rewrite the system architecture, we can immediately reuse the original business function code.

One of the goals of refactoring is to completely separate the framework from the business. Students who are interested in in-depth understanding can learn about reflection, Ioc and plug-in programming.

Learn unit testing to cultivate your sense of refactoring

Perhaps after all that has been said above, there are still many people who do not understand refactoring. It doesn't matter. I'll teach you a quick start here, that is, unit testing. What is a unit test? please google yourself. What are the requirements for unit testing? It is required that you make every method as testable as possible. Try to make your method testable, which is to cultivate your sense of refactoring. When you ask for a method to be testable, you will find that you have to constantly modify your method to make its responsibilities as simple as possible and make it as context-free as possible. let it complete the relevant functions as far as possible through the input and output of method parameters, so that dependent classes are changed to interfaces rather than instances as far as possible. Eventually, you will find that this is refactoring! And unconsciously, your ability of refactoring will be greatly improved, and your programming level will be greatly improved!

When you see this, experienced programmers will ask, are you encouraging me to use TDD? No, it's not. TDD (Test-Driven Development) encourages test-driven development, writing unit test case code before development, and testing code to determine what product code needs to be written.

This is a relatively advanced development method, but in the practice of programming, I think it is too cumbersome for many small and medium-sized enterprises to implement, not to mention our personal developers. I encourage you to use unit testing to cultivate your awareness of refactoring, which can be said to be a post-drive to improve your refactoring ability and refactoring desire. You can call my method "TDR (Test-Driven Refactoring)-test-driven refactoring".

Of course, if you consciously make the method testable before development, the functions you write will be of higher quality. When your functions are reusable functions, you will find that writing code is like building blocks, which can decompose a large requirement into countless small functions and quickly implement the requirements. Here is a piece of code from an oversized method. If you know how to program a testable method for this code, congratulations, you are getting started.

The so-called reconstruction

If you have the patience to see here, you should know that I am not a title party, and this article may be called "how to apply the idea of refactoring in programming" is more appropriate, but I do not want to use such a serious title. Many programming beginners, or people with years of programming experience, find it very difficult to read other people's code, let alone refactoring. They either marvel at the code or overturn it. However, if we have a sense of refactoring and are familiar with some tips for code tuning and optimization in the programming process, you will naturally develop the ability to refactoring. Refactoring is actually very simple:

Lay a solid foundation

Look at more good code.

Avoid copying and pasting. If you see duplicate code, you should consciously destroy it.

Reduce dependence on code generators

When dealing with existing code, try to use refactoring instead of rewriting. Be sure to ReFactor before rewriting.

Try to make all methods testable.

If you insist on doing this, it will feel natural after a period of time. The purpose of refactoring is to make your code more concise, stable, reusable, and to maximize the separation of function and business. In the process of refactoring, your ability to read code, write good code, and system architecture will steadily improve. It is just around the corner for you to become a good programmer.

This is the end of "how to reconstruct 3000 lines of code into 15 lines". Thank you for your 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.

Share To

Development

Wechat

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

12
Report