Improve code design-organize your data (composing data)

Source: Internet
Author: User
ArticleDirectory
    • Explanation:
    • Before impulse:
    • After Impulse:
    • Explanation:
    • Before impulse:
    • After Impulse:
    • Explanation:
    • Before impulse:
    • After Impulse:
    • Explanation:
    • Explanation:
    • Before impulse:
    • After Impulse:
    • Explanation:
    • Explanation:
    • Explanation:
    • Explanation:
    • Explanation:
    • Before impulse:
    • After Impulse:
    • Explanation:
    • Explanation:
    • Explanation:
    • Before impulse:
    • After Impulse:
1. Self encapsulate field (self-encapsulated value range) Explanation:

Most classes (Class(Field), There will be some methods to use these Value domains. "If you call these Value Domains", there are two points of view:1. They should be called directly. 2. They should be called through the access function..

In most cases, direct calling is convenient. Too many function accesses may lead to too many functions in the class. Of course, if I think direct calling will bring some problems in the future, writing an access function one by one is not very difficult.

The following example describes how to write an access function for the value range and call the value of the value range through the access function.

Before impulse:
Private string _ username, _ password; Public bool isvalid () {bool isvalid =! (String. isnullorempty (_ username) & string. isnullorempty (_ password); Return isvalid ;}
After Impulse:
 
Private string _ username, _ password; Public bool isvalid () {bool isvalid =! (String. isnullorempty (GetUserName () & string. isnullorempty (GetPassword (); Return isvalid;} private string GetUserName () {return _ username;} private string GetPassword () {return _ password ;}
2. replace data value with object (replace data value with object) Explanation:

If you findCodeThere are many fields or value fields that seem to be describing something. You can consider encapsulating these fields or value fields into a class and replacing the complicated fields and value fields in the original code with this object.

Before impulse:
 
Class order {Public String customername {Get; set;} Public String customeraddress {Get; set;} public int creditlevel {Get; set;} public int customertel {Get; set ;} //...}
After Impulse:
Class order {public customer {Get; Set ;}} Class Customer {Public String customername {Get; Set ;}public string customeraddress {Get; Set ;}public int creditlevel {Get; set;} public int customertel {Get; set ;}//...}
3. Change Value to reference (change value object to reference object) Explanation:

A class sometimes contains a value object as its field or attribute, such as an order.OrderClass contains a customerCustomername. If the same customer has several orders, the customer's name will be saved once for each order. if the customer's name changes, you need to changeCustomername.

IfCustomernameExtract and extractCustomerClass, the order isCustomerInstance reference, you only need to change the attributes of the customer name in the instance, because all orders are referenced by this customer instance, so they do not need to be changed.

Before impulse:
Class order {private string _ customername; public order (string customername) {This. _ customername = customername ;}}
After Impulse:
 
Class order {private customer _ customer; public order (customer) {This. _ customer = Customer ;}} Class Customer {Public String customername {Get; Set ;}}
4. Change reference to value (change the referenced object to a value object) Explanation:

If you want to pass a reference type to a class, for example, I have done something similarMSNSoftware, in which the person's profile picture, nickname, personalized signature is displayed in a custom control, and then in useListBox. Add (mycontrol)And I was surprised to find that the last friend list was actually the same (last) person.ListBox. Add ()All passed in are the same referencedMycontrolInstance, although the Code seems to be dynamically generating everyone, it actually only modifies oneMycontrol, AndListBoxThis problem was solved only by referencing this object. Later, I dynamically generated instances of different objects in the code.

In addition, you can define a value object in your class. Each time you generate a class instance, the control of the class value object always belongs to you.

5. Replace array with object (replace array with object) Explanation:

A class may contain many fields.StringType, put them inString []In the method body of the class, you can use the array index to obtain the value you need. This makes it difficult for others to remember you.String [0]Indicates the name,String [1]It indicates his address...

The following section shows the differences in code readability.

Before impulse:
String [] _ person = new string [5]; Public String getname () {return _ person [0];} Public String getadd () {return _ person [1];}
After Impulse:
 
Private person _ person; Public String getname () {return _ person. Name;} Public String getadd () {return _ person. Address ;}
6. Duplicate observed data (copying monitored data) Explanation:

A good system should have prior business logic (Business Logic) And user interface (User Interface) Separation. If this is not doneProgram. CSA large amount of code is stacked, and the business logic is closely coupled with the user interface to separate the business logic from the user interface. The most important implementation is the data synchronization mechanism,Duplicate observed dataThe reconstruction method is used to complete this task. Due to the long examples, you can write an article independently. In the future, we will introduce the observer mode (Observer Pattern.

7. Change unidirectional Association to bidirectional (change one-way Association to two-way Association) Explanation:

If twoClassBoth use the features of the other party, but there is only one-way association between the two (for example, only the called feature can be called ), if you want the called party to know which objects have called itself, you need to useChange unidirectional Association to bidirectional.

The common practice is to define a set of called types in the called party's Code (Collection), SuchArraylist <t>,List <t>(Recommended)List <t>) When the [Caller] calls [called Party], add your reference to the set in [called Party.

8. Change bidirectional Association to unidirectional (Change bidirectional Association to unidirectional) Explanation:

UsedChange unidirectional Association to bidirectionalThen, if the demand changes, it is unnecessary to find two-way association. In this case, you need to change the two-way Association to one-way, that isChange bidirectional Association to unidirectional, Steps andChange unidirectional Association to bidirectional opposite.

9. Replace magic number with symbolic constant (replace the magic number with a symbolic constant) Explanation:

New users are writingProgramUsually do not pay attention to naming (Name), Their requirements for the program is that they can run correctly. Drag a fewButtonAnd do not rename it, so a similarButton1,Button2,Button3... And so on, you can't imagine it simply by looking at the code.Button1CorrespondingUIWhich of the following buttons appears in the code field? The name of the temporary variable is everywhere.A,AA,Aaa...

UseReplace magic number with symbolic constantRight! If yourButtonIs used to "send", then you can give it a name --BtnsendIf yourInt32 typeThe variable is used to indicate a person's age. Please give it a name --Age.

10. Description of encapsulate field (encapsulation value range:

If yourClassThere isPublicField. Set it as a property.

The first principle of object-oriented is encapsulation (Encapsulation), Or data hiding (Data Hiding), If a field is to be accessed by the outside world, you should set it as a property, inC #Set the property ratio inJavaIs much more convenient, becauseC #The compiler does some extra work for you.

Before impulse:
 
Public String _ name;
After Impulse:
 
Public string name {Get; set ;}
11. Description of encapsulate collection (encapsulation set:

If yourClassThere is a method that needs to return multiple values, and there is a set in the class (Collection) Temporarily retain these returned values. In some cases, you should avoid directly accessing this set from the [Caller. if the [Caller] modifies an item in your set, and the [called end] does not know that its set has been modified, some other methods are still calling the modified set, which may cause unexpected consequences.

Encapsulate collectionWe recommend that you encapsulate the set on the [called end] (at least you set its access permission to private) and provide functions to modify the set if necessary.

12. Replace record with data class (replace record with data) Explanation:

And article 2Replace data value with objectAnd article 5Replace array with objectSimilar practice: extracts data from a class to a record class, so that you can extend the class later.

13. Replace subclass with fields (replace subclass with value range) Explanation:

The subclass is built on the parent class and then adds new functions or loads the possible behavior changes of the parent class. There is a change behavior (Variant Behavior) Become a constant function (Constant Method), They will return a hard-coded (Hard-coded) Value. This value is generally used to return different values for the same access function in different parent classes. You can declare the access function as an abstract function in the parent class, and let it return different values in different subclasses. however, if only a function that returns a constant does not play any other role in the subclass, The subclass does not have much value.

In the parent class, you can design some values corresponding to the return value of the subclass, and then make some other modifications to the parent class to eliminate these subclasses, the advantage is to avoid the complexity of unnecessary subclass, which isReplace subclass with Fields.

Before impulse:
Class person {protected abstract bool ismale (); protected abstract char code ();//...} class male: person {protected override bool ismale () {return true;} protected override char code () {return 'M' ;}} Class Female: person {protected override bool ismale () {return false;} protected override char code () {return 'F ';}}
After Impulse:
Class person {public bool ismale {Get; set;} public char code {Get; set;} public person (bool ismale, char code) {This. ismale = ismale; this. code = Code;} public person male () {return new person (true, 'M');} public person female () {return new person (false, 'F ');}//...}

This is the case when calling:PersonCreate_chen =Person. Male ();

Link: http://www.cnblogs.com/technology/archive/2011/05/13/2045394.html

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.