How to write beautiful code (2)

Source: Internet
Author: User

(The idea of this article is basically from the classic book restructuring)

Http://www.cnblogs.com/ceys/archive/2012/03/05/2379842.html#commentform previous

 

 

PreviousArticleI mainly talked about how to make functional changes. Now we all use object-oriented languages. What kind of "object" is beautiful?

The functions and fields in the class should be the most closely related to the class. If there is more interaction with the other class, move it.When moving a field, if many functions reference this field, you can encapsulate this field using the get/set method. In this way, you only need to modify the get/set access function.

A class should be a clear abstraction to deal with some clear responsibilities. Otherwise, a new class is created to show the responsibilities separated from the old class.Refining class is to improve concurrencyProgramBecause the two classes can be locked separately after extraction. Note that to extract new classes, consider making them public to users. If any user is allowed to modify any part of the object, it becomes a reference object. If no one is allowed to modify any part of the object through object, you can set it to unmodifiable, or provide it with an interface that cannot be modified, delegate all functions related to a to completely hide this class.

Every object should know as little as possible about other parts of the system. When the customer calls another object through one delegate class, all functions required by the customer are created in the service class,Hide delegation relationships to reduce Coupling. However, if there are more and more functions of the delegate class, the service class will completely become an intermediary. It is hard to say to what extent it is suitable to hide it.

When you need to provide some additional functions for the service class but cannot modify the class, create a new class to include these additional functions and become a subclass or packaging class of the source class. If there are few functions, you can directly introduce the additional functions.

Subclass has less workload, but it has two problems: first, it must be implemented during the object creation period. If the object is created, it cannot be used. Second, subclass produces a subclass object. If other objects reference the old object, the original data is saved for the other two objects. If the original data can be modified, one modification action cannot change two copies at the same time. In this case, we need to use the packaging class. The packaging class must provide delegate functions for all functions of the original class. 

 

Ii. reorganizing data

 

Object-oriented languages have a useful feature: new types can be defined. In this way, we can use objects to organize data.

If there is a data item, it must be used together with other data and actions to make sense and change the data item to an object.

If a class derives many instances that are equal to each other, you want to replace them with the same object and change this value object to a reference object.. Each referenced object represents a thing in the real world. You can use = to check whether two objects are equal. The value object is defined by the value contained in it, regardless of the existence of the copy. Here is a simple example:

Value Object:

 
Class Customer {public customer (string name) {_ name = Name;} Public String getname () {return _ name;} private final string _ name ;} class order {public order (string customername) {_ customer = new customer (customername);} // set, get... private customer _ customer; // other function use customer ...}

Here, even if multiple orders belong to the same customer, each order object still has its own customer object. Change it to a reference object, that is, each customer name corresponds to only one customer object:

Class Customer {public static customer getnamed (string name) {return (customer) _ instances. get (name);} private customer (string name) {_ name = Name;} Private Static dictionary _ instances = new hashtable (); static void loadcustomers () {new customer ("gang li "). store ();} private void store () {_ instances. put (this. getname (), this );}//...} class order {public order (string customer) {_ customer = customer. getnamed (customer );}//...}

First, we create a factory function to control the creation process of the customer object. Then, you need to determine how to access the customer object and use another object for access. However, the Order class does not have an obvious field for access, so you can create an object to save all the customer objects. The static dictionary in customer is used for saving for simplicity. Use the customer class as the access point. Then, determine when to create a customer object. In order to simplify the process, the customer object to be used is created in advance in loadcustomer.

The referenced object may cause a complex association between memory areas. In distributed and concurrent systems, immutable value objects are especially useful because they do not need to be considered for synchronization. Here immutable means that the object itself cannot be changed, such as the money object. When determining equality, you must overwrite equals () and hashcode (). (The simple way to implement hashcode is to comfort all fields used by equals () with an exception or operation ).

If both classes use the opposite feature, but there is only one-way connection, add a reverse pointer and enable the modification function to update the two connections at the same time. AboveCodeFor example:

 
Class Customer {// customer has multiple orders private set _ orders = new hashset (); // Add auxiliary functions visible only in the package, enable order to directly access the _ orders set friendorders () {return _ orders;} // you can modify the connection in the customer, let it call the control function void addorder (Order Arg) {Arg. setcustomer (this);} class order... void setcustomer (customer Arg) {If (_ customer! = NULL) _ customer. friendorders (). Remove (this); _ customer = ARG; If (_ customer! = NULL) _ customer. friendorders (). Add (this );}

If an array has different elements, replace the array with objects..

Replace magic number with literal Constants.

If a function returns a set,Let this function return a read-only copy of the set and provide a function to add/remove the element of the set in this class.If the function returns the set itself, the user is allowed to modify the set without the owner's knowledge. Therefore, the set function should not be provided for the set. However, a function can be provided to increase or decrease elements of a set. For example:

 class person {// encapsulate Set Operations Public void addcourse (course Arg) {_ courses. add (ARG);} public void removecourse (course Arg) {_ courses. remove (ARG);} public void initializecourses (set Arg) {assert. istrue (_ courses. isempty (); iterator iter = Arg. iterator (); While (ITER. hasnext () {addcourse (course) ITER. next () ;}}// make sure that you have not modified the public set getcourses () {return collections by using the value function. unmodifiableset (_ courses);} private set _ courses = new hashset ();} 

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.