@[Toc]


What is the open close principle?


Definition of open close principle:

Software entities like classes,modules and functions should be open for extension but closed for Modifications. (A software entity such as classes, modules, or functions that should be open to extension and closed to modification.)

In the process of developing software, for change, upgrade and maintenance and so on reasons need to modify the original code software, may introduce errors already tested the old code, the destruction of the original system, therefore, when software requirements change, we should try to use the extension to implement changes, rather than to modify the original code.


Open and close principle detailed explanation

Take, for example, the sale of books in bookstores:



Book interface IBook:

public interface IBook {   
     // Books have names
     public String getName(a);
     // Books have a price
     public int getPrice(a);
     // Books have authors
     public String getAuthor(a);
}
Copy the code


NovelBook: is a concrete implementation class, is the general name for all fiction books.

public class NovelBook implements IBook {
     // Book name
     private String name;       
     // The price of books
     private int price; 
     // The author of the book
     private String author;             
     // Pass the book data through the constructor
     public NovelBook(String _name,int _price,String _author){
this.name = _name;
             this.price = _price;
             this.author = _author;
     }  
     // Find out who the author is
     public String getAuthor(a) {
             return this.author;
     }
     // What is the name of the book
     public String getName(a) {
             return this.name;
     }
     // Get the price of the book
     public int getPrice(a) {
             return this.price; }}Copy the code


Bookshops:

public class BookStore {
     private final static ArrayList bookList = new ArrayList();
     //static a static module initializes data. In real projects, this is usually done by the persistence layer
     static{
             bookList.add(new NovelBook("Heavenly Dragon eight Bu".3200."Jin yong"));
             bookList.add(new NovelBook(Notre Dame de Paris.5600."Hugo"));
             bookList.add(new NovelBook(Les Miserables.3500."Hugo"));
             bookList.add(new NovelBook("Golden Vase plum".4300."Lanling smiles."));
     }
     // Simulate the bookstore to buy books
     public static void main(String[] args) {
             NumberFormat formatter = NumberFormat.getCurrencyInstance();
             formatter.setMaximumFractionDigits(2);
             System.out.println("The records of books sold at ----------- bookstore are as follows: -----------");
             for(IBook book:bookList){
                     System.out.println("Book Title:" + book.getName()+"\ T Book Author:" +book.getAuthor()+"\t Book Price:"+ formatter.format (book.getPrice()/100.0) +"Yuan"); }}}Copy the code


Running results:

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- bookstore sell books record is as follows: -- -- -- -- -- -- -- -- -- -- -- -- -- -- books name: tian long ba bu & emsp;   Authors: Jin Yong & EMSP;       Book price: ¥25.60Titles of meta-books: Notre Dame de Paris & EMSP; Authors: Hugo & Emsp;       Book price: ¥50.40Title of metabook: Les Miserables & EMSP;   Authors: Hugo & Emsp;       Book price: ¥28.00Titles of yuan books: Jin Ping Mei & EMSP;     Author: LAN Ling Xiaosheng & EMsp; Book price: ¥38.70yuanCopy the code


Now the new demand comes, influenced by the development of mobile Internet, bookstores have to offer discounts to keep their stores alive. All books over 40 yuan are sold with a 10% discount, and other books are sold with 20% discount.

There are three ways to achieve this change:

● Modify the interface

A new method, getOffPrice(), was added to the IBook to be used for discounting, and all implementation classes implemented this method. But as a consequence of this change, the implementation class NovelBook needs to be changed, the main method in BookStore also needs to be changed, and the IBook as an interface should be stable and reliable and should not change frequently, otherwise the interface as a contract loses its effectiveness. Therefore, the scheme is negative.

● Modify the implementation class

Modify methods in NovelBook classes to implement discount processing directly in getPrice(). This approach is a good one when the project has a clear charter (intra-team constraints) or a good architectural design, but it has drawbacks. For example, the procurement of books is also to see the price, because the method has realized the discounted price, so the procurement personnel see the discounted price, because of information asymmetry and decision-making errors. Therefore, the scheme is not an optimal one.

● Change through extension

Add a subclass OffNovelBook that overrides the getPrice method. High-level modules (i.e., static module areas) generate new objects through the OffNovelBook class to minimize the development of business changes to the system. The modified class diagram is shown in Figure 6-2.



Offnovelbooks for discounted sales: Simply overrides the getPrice method, extending the new business.

public class OffNovelBook extends NovelBook {
     public OffNovelBook(String _name,int _price,String _author){
             super(_name,_price,_author);
     }
     // Overwrite the selling price
     @Override
     public int getPrice(a){
             / / the original price
             int selfPrice = super.getPrice();
             int offPrice=0;
             if(selfPrice>4000) {// If the original price is over 40 yuan, there is 10% discount
                     offPrice = selfPrice * 90 /100;
             }else{
                     offPrice = selfPrice * 80 /100;
             }
             returnoffPrice; }}Copy the code


Store discount sales class: need to rely on the subclass, slightly modified.

public class BookStore {
     private final static ArrayList bookList = new ArrayList();
     //static a static module initializes data. In real projects, this is usually done by the persistence layer
     static{
             bookList.add(new OffNovelBook("Heavenly Dragon eight Bu".3200."Jin yong"));
             bookList.add(new OffNovelBook(Notre Dame de Paris.5600."Hugo"));
             bookList.add(new OffNovelBook(Les Miserables.3500."Hugo"));
             bookList.add(new OffNovelBook("Golden Vase plum".4300."Lanling smiles."));
     }  
     // Simulate the bookstore to buy books
     public static void main(String[] args) {
             NumberFormat formatter = NumberFormat.getCurrencyInstance();
             formatter.setMaximumFractionDigits(2);
             System.out.println("The records of books sold at ----------- bookstore are as follows: -----------");
             for(IBook book:bookList){
                      System.out.println("Book Title:" + book.getName()+"\ T Book Author:" + book.getAuthor()+ "\t Book Price:" + formatter.format (book.getPrice()/100.0) +"Yuan"); }}}Copy the code


Running results:

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- bookstore sell books record is as follows: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the book title: tian long ba bu & emsp;   Authors: Jin Yong & EMSP;       Book price: ¥25.60Titles of meta-books: Notre Dame de Paris & EMSP; Authors: Hugo & Emsp;       Book price: ¥50.40Title of metabook: Les Miserables & EMSP;   Authors: Hugo & Emsp;       Book price: ¥28.00Titles of yuan books: Jin Ping Mei & EMSP;     Author: LAN Ling Xiaosheng & EMsp; Book price: ¥38.70yuanCopy the code


The open and closed principle is open for extension and closed for modification, but it does not mean that no modification is made. The change of low-level modules must be coupled by high-level modules, otherwise it is an isolated and meaningless code fragment.


Why the open closed principle?


Open and close principle is the most basic principle, the other principles are the specific form of open and close principle, that is to say, the other five principles are the tools and methods to guide the design. To put it another way, according to Java language terminology, the open and closed principles are abstract classes, and the other five principles are concrete implementation classes.


Its importance can be understood in the following ways:

1, the impact of the open and close principle on the test

Take the bookshop example mentioned above, the IBook interface has been written, the implementation class NovelBook has also been written, need to write a test class to test.

Unit tests for fiction:

public class NovelBookTest extends TestCase {
     private String name = "Ordinary world.";
     private int price = 6000;
     private String author = "路遥";      
     private IBook novelBook = new NovelBook(name,price,author);
     // Test the getPrice method
     public void testGetPrice(a) {
             // Original price sales, based on whether the input and output values are equal
             super.assertEquals(this.price, this.novelBook.getPrice()); }}Copy the code


General test method in a way of not less than three, first is to ensure that normal business logic testing, followed by the boundary conditions to test, and then the abnormal test to more important method of the test methods and even more than ten, and unit test is a test of the class, the class methods in the coupling is allowed, under such circumstances, It’s hard to think about changing a method or more method code to make changes.

If you do an extension, you add a new class, you add a new test method, you just make sure that you add the right class.

2. Open and close principle can improve reusability

In object-oriented design, all logic is composed from atomic logic, rather than implementing a single business logic in a single class. Only then can code be reused, and the smaller the granularity, the more likely it is to be reused. So why reuse it? Reduce the amount of code to prevent the same logic from being scattered in multiple corners, and prevent future maintainers from having to search the entire project for relevant code to fix a minor defect or add a new feature. So how do you increase reuse? Reduce the granularity of logic until a logic can no longer be split.


2, open and close principle can improve maintainability

When a piece of software is put into production, the maintenance personnel’s job is not only to maintain the data, but also to extend the program, the maintenance personnel most interested in doing is to extend a class, rather than modify a class.

3, object-oriented development requirements

Everything is an object, we need to abstract everything into an object, and then operate on the object, but everything is moving, there is movement, there is change, there is change, there is a strategy to deal with, how to deal with it quickly? This requires factoring in all possible variations at the beginning of the design, and then leaving the interface waiting for the “might” to turn into “reality.”


How to apply the open close principle?


The open and closed principle is a relatively abstract principle, the first five principles are the specific interpretation of the open and closed principle, but the open and closed principle is not limited to so much, it is more like a slogan, a goal, but does not put forward specific implementation methods. This needs oneself to understand spirit in the job, sum up method.


1. Abstract constraints

The interface or abstract class can constrain a set of behaviors that may change, and it can be open to extension, which contains three meanings: first, the interface or abstract class can constrain extension, and the extension is delimited.it does not allow public methods that do not exist in the interface or abstract class. Second, parameter types and reference objects use interfaces or abstract classes rather than implementation classes. Third, the abstraction layer should be kept as stable as possible and not be modified once determined.


2. Metadata controls module behavior

Use metadata as much as possible to control program behavior and reduce repetitive development. What is metadata? The data used to describe the environment and data, colloquially known as configuration parameters, can be obtained from files or databases. For a very simple example, the login method provides the logic to check whether the IP address is in the list of allowed access, and then determine whether the password needs to be verified in the database (, this behavior is a typical example of metadata control module behavior.


3. Formulate project charter

In a team, it is important to have a project charter, because the charter specifies conventions that all personnel must follow, and conventions are superior to configurations for the project.


4. Encapsulate change

Encapsulating changes has two meanings. First, encapsulate the same change into an interface or abstract class. Second, encapsulate different changes into different interfaces or abstract classes. There should not be two different changes in the same interface or abstract class. Package variations, which are protected variations, identify points where changes are expected or unstable, and create stable interfaces for those points, precisely the changes that are likely to occur in the package, as soon as they are predicted or “sixth sense” detects them. Each of the 23 design patterns encapsulates change from different perspectives.





Reference:

[1] : “Zen of Design Mode” [2] : Open and close principle of six object-oriented principles [3] : Why to use open and close principle [4] : “Big Talk Design Mode”