Large class----a signal to be reconstructed

Source: Internet
Author: User

If you want to do too much with a single class, there are often too many instance variables. Once that happens, duplicated code will follow. Workaround:1. Place the variables that are related to each other within the class and put them together.  Use the Extract class technique to refine the variables associated with each other to the new class. 2. If the new class in 1 is suitable as a subclass, then you can use the Extract subclass technique. 11. For too many code processing methods, decomposition function, the large function decomposition into a number of small functions, so that the duplicate code can be eliminated. Related functions can be distilled into a new class with variables, using extract class manipulation or extract subclass. 12. Implement 11 o'clock to determine how the client uses the refined class, and then, using the Extract interface technique, to extract an interface for each usage method. 111. If the currently oversized class is a GUI class, then the newly refined class and the current class will each keep some duplicate data on each side and remain in sync. This should use the duplicate observed data technique. Specific handling techniques introduced: 1. Extract SubclassSome of the attributes in a class are only used by some, but not all, instances. This feature allows you to create a subclass that uses only this part of the attribute. In this way, the proprietary characteristics of the class are extracted from the original class, thus making the original class less large. The point is to identify the existence of such a situation, such as: Job item has a use case, just use Getunitprice,getemployee, do not use the other features of job item. Then it is possible to refine the use of getunitprice,getemployee into a class, where the extract subclass technique is used. Another example:
1:public Class Registration

   2: {

   3: Public     nonregistrationaction Action {get; set;}

   4: Public     decimal Registrationtotal {get; set;}

   5: Public     string Notes {get; set;}

   6: Public     string Description {get; set;}

   7: Public     DateTime registrationdate {get; set;}

   8:}
This class, there are two usage scenarios, one is registered, and the other is non-registered. As a registered instance, it uses only the Registrationdate,description,registrationtotal method, no other method, and when used as a non-registered instance, Just use the Nonregistrationaction,notes method. conforming to characteristics, some of the attributes in a class are only used by some, but not all, instances. If the extract subclass technique is used here, then, after processing, the result is this:
   1:public Class Registration

   2: {

   3: Public     decimal Registrationtotal {get; set;}

   4: Public     string Description {get; set;}

   5: Public     DateTime registrationdate {get; set;}

   6:}

   7:  

   8:public class Nonregistration:registration

   9: {

  : Public     nonregistrationaction Action {get; set;}

  One: Public     string Notes {get; set;}

  12:}
2.Extract InterfaceThe meaning of "using a class" is interpreted as one of the following: 1). Use all areas of responsibility for this class. 2). A group of customers uses only a specific subset of the class responsibility area. 3). This class requires collaboration with all classes that assist in handling certain requests. for 2), 3), it makes sense to separate this part of the responsibility of a class. This makes it easier to see the division of responsibilities for classes. Therefore, Extract interface the way to do things, is the original class part of the subset, part of the responsibility to separate out. Example:The employee class, which provides a lot of functionality, however, has partial classes that only use its getrate () and Hasspecialskill () functions. So, in order to make the employee class smaller, it can be extracted from its two functions, getrate () and Hasspecialskill ().  Refinement for Interface interface billable{public int getrate (); public boolean Hasspecialskill ();} The employee class then implements the interface billable. In this way, those that only need to use the class Getrate (), Hasspecialskill () function of the employee class, only need to use the interface billable can, so that just exposes the billable function to the user. That is, only users are provided with the functionality they can use, and other functional subsets are not provided. Multiple users, focusing only on getrate (), Hasspecialskill () functions, different users, will require different implementations. At this point, different implementations can be implemented to meet the requirements of the user. 3.Duplicate observed data (copy "monitored")Scenario: A GUI class that contains business processing code and user interface code. As the business logic increases, the class gets bigger and the logic is complicated. This is because a GUI class takes on two responsibilities, the business processing function and the interface rendering function. At this point, you need to separate the business processing code from the GUI class. Business processing code and interface display code separation, easy to maintain and easy to develop. When doing business processing, you need to use the interface data, and when the interface is updated, it will also need to use the results of business processing. At this point, the data needs to be synchronized between the business layer and the interface layer.  And this method can achieve the same energy, business layer (domain layer) and interface layer of data synchronization. Example: The following is the Intervalwindow class:
  public class Intervalwindow extends Frame    ... Java.awt.TextField _startfield;    Java.awt.TextField _endfield;    Java.awt.TextField _lengthfield;     Class Symfocus extends Java.awt.event.FocusAdapter    {public        void Focuslost (Java.awt.event.FocusEvent event)        {            Object object = Event.getsource ();            if (object = = _startfield)                startfield_focuslost (event);            else if (object = = _endfield)                endfield_focuslost (event);            else if (object = = _lengthfield)                lengthfield_focuslost (event);}    }

A GUI interface with three text boxes that trigger a calculation when a text box is entered, leaving, or losing focus. When the Start text box loses focus, executes the Startfield_focustlost method, executes the Endfield_focuslost method when the end text box loses focus, executes the lengthfield_ when the length text box loses focus Focuslost method. When the Start text box and end text box lose focus, the thing to do is to check whether the input to the text box is an integer, or if not, to set the contents of the text box to 0, and then to calculate the contents of the Length text box. When the length text box loses focus, the thing to do is to check whether the input to the text box is an integer, or if not, to set the contents of the text box to 0, and then to calculate the value of the current text box. This is the interface operation code.
    void Startfield_focuslost (Java.awt.event.FocusEvent event) {        if (Isnotinteger (_startfield.gettext ()))            _ Startfield.settext ("0");        Calculatelength ();    }     void Endfield_focuslost (Java.awt.event.FocusEvent event) {        if (Isnotinteger (_endfield.gettext ()))            _ Endfield.settext ("0");        Calculatelength ();    }     void Lengthfield_focuslost (Java.awt.event.FocusEvent event) {        if (Isnotinteger (_lengthfield.gettext ()            )) _lengthfield.settext ("0");        Calculateend ();    }
 void Calculatelength () {try {int start = Integer.parseint (_startfield.gettext ());        int end = Integer.parseint (_endfield.gettext ());        int length = End-start;      _lengthfield.settext (string.valueof (length));      } catch (NumberFormatException e) {throw new RuntimeException ("Unexpected number Format Error");      }}void calculateend () {try {int start = Integer.parseint (_startfield.gettext ());      int length = Integer.parseint (_lengthfield.gettext ());      int end = start + length;    _endfield.settext (string.valueof (end));    } catch (NumberFormatException e) {throw new RuntimeException ("Unexpected number Format Error"); }}
The Calculatelength () method and the Calculateend () method, which contain the logic of the calculation, also contain references to interface components. The thing we want to do now is to decouple the two methods from the interface component (_startfield,_endfield,_lengthfield). Here you can use the duplicate observed data technique. Create a domain class, a domain class, and an interface class for data synchronization; When the data for the domain class is updated, the results are passed to the interface class. -------------------------------------------------------------------------------------------------------Application Duplicate After observed data manipulation, the following code is obtained: The whole process becomes this: 1. The GUI class, when Intervalwindow initialized, uses the value of the interval class. 2. When the GUI class event changes, the value of the component is passed to the _subject instance and calculated. 3._subject the GUI class interface to update after the calculation is complete. Here, the computational logic is partitioned into _subject instances (domain classes). data transfer process:Domain class, interface initial value data------>{ Interface Generation (GUI Class)------> Domain class------> interface}------>{ Interface Generation (GUI Class)---> Domain class---> interface}public class Intervalwindow extends Frame implements observer{private Interval _subject;    Public Intervalwindow () {_subject = new Interval (); _subject.addobserver (this);Update (_subject, null);} String Getend () {return _subject.getend ();    } void SetEnd (String arg) {_subject.setend (ARG);            } void Startfield_focuslost (Java.awt.event.FocusEvent event) {if (Isnotinteger (_startfield.gettext ())) _startfield.settext ("0");_subject.Setstart (_startfield.gettext ());_subject.calculatelength ();} void Endfield_focuslost (Java.awt.event.FocusEvent event) {if (Isnotinteger (_endfield.gettext ())) _endfield.settext ("0");_subject.SetEnd (_endfield.gettext ());_subject.calculatelength ();} void Lengthfield_focuslost (Java.awt.event.FocusEvent event) {if (Isnotinteger (_lengthfield.gettext ())) _lengthfield.settext ("0");   _subject.setlength (_lengthfield.gettext ());_subject.calculateend ();} @Override public void Update (Observable observed, Object Arg) {_endfield.settext (_subject.getend ());_startfield.settext (_subject.getstart ());_lengthfield.settext (_subject.getlength ());}}-------------------------------Class Interval extends Observable {private String _end = "0";    Private String _start = "0";      Private String _length = "0";    String Getend () {return _end; } void SetEnd (String arg) {_end = arg;setchanged ();notifyobservers ();} String Getstart () {return _start; } void Setstart (String arg) {_start = arg;setchanged ();notifyobservers ();} String GetLength () {return _length; } void SetLength (String arg) {_length = arg;setchanged ();notifyobservers ();} void Calculatelength () {try {int start = Integer.parseint (Getstart ());        int end = Integer.parseint (Getend ()); int length = End-start;setLength (string.valueof (length));} catch (NumberFormatException e) {throw new RuntimeException ("Unexpected number Format Error");        }} void Calculateend () {try {int start = Integer.parseint (Getstart ());        int length = Integer.parseint (GetLength ()); int end = start + length;SetEnd (string.valueof (end));} catch (NumberFormatException e) {throw new RuntimeException ("Unexpected number Format Error"); }  }
} Reference: https://sourcemaking.com/refactoring/duplicate-observed-datahttps://lostechies.com/seanchambers/2009/08/ 20/refactoring-day-20-extract-subclass/http://www.refactoring.com/catalog/duplicateobserveddata.htmlhttp:// Www.refactoring.com/catalog/extractSubclass.html

Large class----a signal to be reconstructed

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.