On the way to learning programming, I believe you must listen to many words, what face object, encapsulation inheritance polymorphism, internal work method 21 design modes and so on. But it’s rarely used, or it’s used passively. They think about interfaces, base classes, and so on long before they write the code. When you write your own code, you rarely think about object-oriented aspects, and it’s easy to run into code that isn’t good enough, and then you need to refactor.

But we rarely refactor for a number of reasons, not least because we don’t want to fix bugs; Not wanting to add to my workload (I’m the guy who leaves at 5:30 and my girlfriend is waiting for me to cook); Time is very tight, first to achieve the function first; Code is’ 82 don’t move!!

Refactoring can actually produce more robust code, reduce later work, and make it easier for developers to read. I read a lot of refactoring articles, and found that many of them were basic naming conventions or function splitting. This article will write down some of the ideas I refactor and compare the code before refactoring. All right, without further ado, let’s get to the project. Mighty, mighty, mighty……..

A brief introduction to a project, a project is a client widget used to verify that a written submission is a specification. For the record, object orientation is an idea, independent of language. Any object-oriented language, whether you’re C#, Java, TypeScript, Python, can refactor with this idea.

The figure above is a partial screenshot of the small tool. There are several columns, and each column is to fill in some corresponding modification content. When reviewing and verifying, it will check whether the content written meets the standard.

My task is to complete the rest of the column: write the regular expression, and then indicate if it is not standard. Do you think there is no need to refactor at all?

RaisePropertyChanged is used to notify the front end to re-render if the variable changes# code, just know that these variables are bound to the foregroundprivate string _editDescription; /// </summary> Public String EditDescription {get {return _editDescription; }
        set{ _editDescription = value; RaisePropertyChanged(() => EditDescription); } } private string _editDescriptionRules; /// </summary> public String EditDescriptionRules {get {return _editDescriptionRules; }
        set{ _editDescriptionRules = value; RaisePropertyChanged(() => EditDescriptionRules); } } private bool _editDescriptionHasValidationError; / / / < summary > / / / modify that check mark / / / < summary > public bool EditDescriptionHasValidationError {get {return _editDescriptionHasValidationError; }
        set{ _editDescriptionHasValidationError = value; RaisePropertyChanged(() => EditDescriptionHasValidationError); } } private string _integratedNote; /// </summary> public string IntegratedNote {get {return _integratedNote; }
        set{ _integratedNote = value; RaisePropertyChanged(() => IntegratedNote); } } private string _integratedNoteRules; // </summary> public string integratedterules {get {return _integratedNoteRules; }
        set{ _integratedNoteRules = value; RaisePropertyChanged(() => IntegratedNoteRules); } } private bool _integratedNoteHasValidationError; / / / < summary > / / / integration note check mark / / / < summary > public bool IntegratedNoteHasValidationError {get {return _integratedNoteHasValidationError; }
        set{ _integratedNoteHasValidationError = value; RaisePropertyChanged(() => IntegratedNoteHasValidationError); }} // Here are two random columns of variables, followed by several columns.Copy the code

And when I did that, I found out it was true. Each column is directly bound with three separate variables: the content written, the standard flag, and the non-standard prompt. I am a lazy person, after I draw two gourd ladles, I get bored (keep copying variables there, change changes there), these variables are almost the same meaning. Why do I have to copy and modify?

Obviously each column has the same item, right, one is content, one is status, one is error message, roar!!

At this time, I think of a sentence in the book: “early reconstruction, often reconstruction”

I have been unable to calm down my lazy heart, because there are “much much much” column below, each line has three similar variables, I this according to gourd gourd gourd gourd, this week overtime, on the copy and paste. I am to progress, to progress every day, not so!

Why can’t I abstract out the same commonality? Is not, this time, I remembered “sunflower treasure Book” of the first page of the first sentence: “all things are objects”, so instinctively told me that each column as an object, but each column of value is not the same. I then wrote a “chicken rib” (base class) as follows:

// </summary> public Class Base: ObservableObject {private String _Content; /// </summary> public Virtual String Content {get {return _content; }
            set{ _content = value; RaisePropertyChanged(() => Content); } } private string _errorTip; /// </summary> public Virtual String ErrorTip {get {return _errorTip; }
            set{ _errorTip = value; RaisePropertyChanged(() => ErrorTip); } } private bool _isError; /// </summary> public virtual bool IsError {get {return _isError; }
            set{ _isError = value; RaisePropertyChanged(() => ErrorTip); }}}Copy the code

Virtual was designed to allow subclasses to override get and set (for later extensions if needed), and the fields were changed from 3 to 1.

// </summary> public Class EditDescription: Base { } private EditDescription _editDescriptions; // </summary> public EditDescription EditDescriptions {get {return _editDescriptions; } set { _editDescriptions = value; RaisePropertyChanged(() => EditDescriptions); }} // The others are the same, I won't write moreCopy the code

So, let’s calculate, the original variables, each column had 3 variables, each variable had 6 lines of code, if I had 100 columns, it would be:

Before refactoring: 100 (columns) x3x6 = 1800 lines of code. .

After refactoring: 100 (columns) x1x6 = 600 lines of code.

Primary math: 1800-600 = 1200 (1200 lines)

Do you have to be brave to spend so much time copying and pasting your predecessors’ code?

And then doesn’t it feel like an inheritance is a lot easier, it’s just a simple application of object orientation, so we don’t have to write so much code.

Seniors told me that writing code is like practicing martial arts, just like you can learn “Jiuyang Shengong” or “star absorption method”, you can learn other martial arts at a glance. In other words, when you understand object orientation, you will naturally write much simpler code. Ash? That’s another digression.

Variable good, look up a function, my face will have a little twitch, ah!! This function is toxic! The function looks like this:

// This function is used to set the border to red for each column errorSetValidateFlag() {// The bound entity class determines the stateif(tsEntity EditDescriptionHasValidationError) {/ / change control border color EditDescriptionHsExpander BorderThickness = new Thickness (1); EditDescriptionHsExpander.BorderBrush = _readBrush; }if (tsEntity.TestSuggestionHasValidationError)
        {
            TestSuggestionHsExpander.BorderThickness = new Thickness(1);
            TestSuggestionHsExpander.BorderBrush = _readBrush;
        }

        if(tsEntity.IntegratedNoteHasValidationError) { IntegratedNoteHsExpander.BorderThickness = new Thickness(1); IntegratedNoteHsExpander.BorderBrush = _readBrush; } // omit ten thousand hereif, one for each columnif
    }
Copy the code

And then, you know, after I changed two columns, I got impatient again. Look again, feeling deja vu yan return feeling ah! Are there any? There are three things like that in every if. My heart ah, and can not help throbbing up, like the feeling of first love, want her to come, come and do not know to do ha. Then I found that if is the state of each column, parentheses are the Settings for the control bar. And then I thought, well, what if I could make something like a loop, and just write a for.

After thinking about it, I made the control a property of the column, so that the if judgment is all about a class. The code looks like this:

Public Class Base: ObservableObject {/// <summary> // </summary> Public Object Control {get;set; } // The rest is the same as above Base}Copy the code

The SetValidateFlag() function then looks like this:

/// </summary> // set the verification interface effect /// </summary> private voidSetValidateFlag() {// listBase all column entities foreach (var item)in listBase)
        {
            if (item.IsError)
            {
                var control = item.Control as HsExpander;
                if (control == null)
                    continue; Control. BorderThickness = new Thickness(1); control.BorderBrush = _readBrush; }}}Copy the code

Ok, a good if gourd gourd gourd gourd gourd for us to complete. Now let’s figure out how much work we’ve saved by refactoring. Old:

The original if was 5 lines of code. This one has 100 columns, which is:

Before refactoring: 100 (columns) x 5 = 500 lines of code.

After refactoring: I counted correctly: 14 lines of code.

After refactoring, the variables are reduced and unified externally. I feel a little satisfaction in my heart and a sublimation in my soul. I don’t know whether I am too easily satisfied or the sense of achievement in the code world. Feel “heaven and earth move” instant on two layers.

So that’s a little bit of refactoring I did when I was writing code, and I hope it helps you a little bit. Then this is my Github, if there is any project that will help you, you can give me a star, xiao Xiao is here, thank you!!