Deep understanding of the JavaScript series (6): single responsibility SRP under the five principles S.O.L. I. D

Source: Internet
Author: User
Preface Uncle Bob proposed and carried forward S.O.L. i. d. Five Principles for better Object-Oriented Programming: 1. theSingleResponsibilityPrinciple (single responsibility SRP) 2. theOpen/ClosedPrinciple (open and closed principle OCP) 3. theLisk... sy

Preface
Uncle Bob proposed and carried forward the Five Principles S.O.L. I. D to better implement object-oriented programming. The five principles are:
1. The Single Responsibility Principle (Single Responsibility SRP)
2. The Open/Closed Principle (Open and Closed Principle OCP)
3. The Liskov Substitution Principle (LSP)
4. The Interface Segregation Principle (Interface separation Principle ISP)
5. The Dependency Inversion Principle (Dependency reversal Principle DIP)
I believe that the five principles have been discussed in the blog Park, especially the implementation of C #, but there are still a few dynamic types of languages like JavaScript Based on prototype, this series will be divided into five articles to demonstrate the application of the five principles based on the JavaScript programming language. Okay. Let's start with our first article: single responsibility.
Http://freshbrewedcode.com/derekgreer/2011/12/08/solid-javascript-single-responsibility-principle/.
Single responsibility
A single responsibility is described as follows:
A class shoshould have only one reason to change
There should be only one reason for the class to change
Copy code
What does a class (JavaScript should be an object) mean by a group of closely related behaviors? The benefit of following a single role is that we can easily maintain this object. When an object encapsulates many responsibilities, once a role needs to be modified, it will inevitably affect other responsibility codes of this object. Through decoupling, each employee can change more elastically.
However, how do we know whether multiple actions of an object construct multiple responsibilities or a single responsibility? We can determine by referring to the Object Design: Roles, Responsibilies, and Collaborationshttp: // define Stereotypes concepts. This book proposes the following Role Stereotypes to differentiate Roles and responsibilities:
1. Information holder-this object is designed to store objects and provide object Information to other objects.
2. Structurer-this object is designed to maintain the relationship between objects and information.
3. Service provider-this object is designed to process work and provide services to other objects.
4. Controller-this object is designed to control decisions and handle a series of tasks
5. Coordinator-this object does not make any decision processing work, but delegate only works on other objects.
6. Interfacer-this object is designed to convert information (or requests) in each part of the system)
Once you understand these concepts, it is easy to know whether your code is multi-responsibility or single-responsibility.
Instance code
The example code demonstrates how to add a product to the shopping cart. The code is very bad. The Code is as follows:
Function Product (id, description ){
This. getId = function (){
Return id;
};
This. getDescription = function (){
Return description;
};
}

Function Cart (eventAggregator ){
Var items = [];

This. addItem = function (item ){
Items. push (item );
};
}

(Function (){
Var products = [new Product (1, "Star Wars Lego Ship "),
New Product (2, "Barbie Doll "),
New Product (3, "Remote Control Airplane")],
Cart = new Cart ();

Function addToCart (){
Var productId = $ (this). attr ('id ');
Var product = $. grep (products, function (x ){
Return x. getId () = productId;
}) [0];
Cart. addItem (product );

Var newItem = $ ('

  • 'Your .html (product. getDescription (). attr ('Id-cart', product. getId (). appendTo ("# cart ");
    }

    Products. forEach (function (product ){
    Var newItem = $ ('

  • 'Privacy .html (product. getDescription ())
    . Attr ('id', product. getId ())
    . Dblclick (addToCart)
    . AppendTo ("# products ");
    });
    })();
    Copy code
    The Code declares two functions to describe the product and cart respectively, while the role of an anonymous function is to update the screen and interact with the user. This is not a very complex example, however, anonymous functions contain a lot of irrelevant responsibilities. Let's see how many responsibilities are there:
    1. First, there is a declaration of the product set.
    2. Second, there is a code that binds the product set to the # product element, and adds an event to the shopping cart.
    3. Third, the Cart shopping Cart display function is available.
    4. Add the product item to the shopping cart and display it.
    Code Reconstruction
    Let's break down the code so that the code can be stored in their own objects. For this reason, we refer to the Event Aggregator theory of martinfowler to process the code so that the objects can communicate with each other.
    First, let's implement the Event aggregation function. This function is divided into two parts: one is Event, the code used for Handler callback, and the other is EventAggregator used to subscribe to and publish events. The Code is as follows:
    Function Event (name ){
    Var handlers = [];

    This. getName = function (){
    Return name;
    };

    This. addHandler = function (handler ){
    Handlers. push (handler );
    };

    This. removeHandler = function (handler ){
    For (var I = 0; I If (handlers [I] = handler ){
    Handlers. splice (I, 1 );
    Break;
    }
    }
    };

    This. fire = function (eventArgs ){
    Handlers. forEach (function (h ){
    H (eventArgs );
    });
    };
    }

    Function EventAggregator (){
    Var events = [];

    Function getEvent (eventName ){
    Return $. grep (events, function (event ){
    Return event. getName () === eventName;
    }) [0];
    }

    This. publish = function (eventName, eventArgs ){
    Var event = getEvent (eventName );

    If (! Event ){
    Event = new Event (eventName );
    Events. push (event );
    }
    Event. fire (eventArgs );
    };

    This. subscribe = function (eventName, handler ){
    Var event = getEvent (eventName );

    If (! Event ){
    Event = new Event (eventName );
    Events. push (event );
    }

    Event. addHandler (handler );
    };
    }
    Copy code
    Then, declare the Product object. The Code is as follows:
    Function Product (id, description ){
    This. getId = function (){
    Return id;
    };
    This. getDescription = function (){
    Return description;
    };
    }
    Copy code
    Then declare the Cart object. In the addItem function of this object, we will trigger the release of an event itemAdded and then pass the item as a parameter.
    Function Cart (eventAggregator ){
    Var items = [];

    This. addItem = function (item ){
    Items. push (item );
    EventAggregator. publish ("itemAdded", item );
    };
    }
    Copy code
    CartController mainly accepts cart objects and event aggregators. It adds a li element node by subscribing to itemAdded and adds product by subscribing to productSelected events.
    Function CartController (cart, eventAggregator ){
    EventAggregator. subscribe ("itemAdded", function (eventArgs ){
    Var newItem = $ ('

  • '{.Html (eventArgs. getDescription (). attr ('Id-cart', eventArgs. getId (). appendTo ("# cart ");
    });

    EventAggregator. subscribe ("productSelected", function (eventArgs ){
    Cart. addItem (eventArgs. product );
    });
    }
    Copy code
    The purpose of Repository is to obtain data (which can be obtained from ajax) and then expose the get data method.
    Function ProductRepository (){
    Var products = [new Product (1, "Star Wars Lego Ship "),
    New Product (2, "Barbie Doll "),
    New Product (3, "Remote Control Airplane")];

    This. getProducts = function (){
    Return products;
    }
    }
    Copy code
    ProductController defines an onProductSelect method, which is mainly used to publish and trigger the productSelected event. forEach is mainly used to bind data to the product list. The Code is as follows:
    Function ProductController (eventAggregator, productRepository ){
    Var products = productRepository. getProducts ();

    Function onProductSelected (){
    Var productId = $ (this). attr ('id ');
    Var product = $. grep (products, function (x ){
    Return x. getId () = productId;
    }) [0];
    EventAggregator. publish ("productSelected ",{
    Product: product
    });
    }

    Products. forEach (function (product ){
    Var newItem = $ ('

  • 'Privacy .html (product. getDescription ())
    . Attr ('id', product. getId ())
    . Dblclick (onProductSelected)
    . AppendTo ("# products ");
    });
    }
    Copy code
    Finally, declare the anonymous function:
    (Function (){
    Var eventAggregator = new EventAggregator (),
    Cart = new Cart (eventAggregator ),
    CartController = new CartController (cart, eventAggregator ),
    ProductRepository = new ProductRepository (),
    ProductController = new ProductController (eventAggregator, productRepository );
    })();
    Copy code
    We can see that the code of the anonymous function is much reduced, mainly because of the instantiation code of an object. In the code, we introduce the concept of Controller, which accepts information and passes it to action, we also introduced the concept of Repository, which is mainly used to process the display of product. The result of refactoring is to write a lot of object declarations, but the advantage is that each object has its own clear responsibilities, this shows the data presentation, and changes the processing set of the processing set, so that the coupling degree is very low.
    Final code
    Summary
    Looking at the reconstruction result, some bloggers may ask, is it really necessary to make it so complicated? I can only say: whether or not to do so depends on your project.

    If your project is a very small project with less code, there is no need to refactor it so complicated, however, if your project is a very complex and large project, or your small project may grow rapidly in the future, you have to consider the SRP principle for separation of duties in the early stage, this will facilitate future maintenance.

    From Uncle Tom's blog

    Related Article

    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.