Detailed description of object-oriented design principles: single Responsibility Principle

Source: Internet
Author: User

Definition: for a class, there should be only one reason for its change.

That is to say, a class only does one thing and only focuses on what it must be concerned about. In philosophical languages, it only focuses on the main contradictions. If a class assumes too many responsibilities, it means that this class and otherProgramSet, or other classes always affect each other, which may cause confusion of the entire program logic, which is not conducive to program robustness or later maintenance. Therefore, before the design, you must plan the responsibilities of each class and each assembly. The display interface only cares about the interface display, and do not display the interface class to process what needs to be done in the background; to read and write database classes, you only need to read and save the data, instead of considering how to display the interface. The control layer only controls these operations. Complex operations in these processes,AlgorithmWhat about it? Then create a new class. Follow one principle. This class only does one thing, and only one place can affect it.

What are the benefits of doing so? I think there are two main points.

1. Refine the tasks and clarify the ideas. A slightly larger project contains thousands or even tens of thousands of lines of code. If you do not abide by the single responsibility principle, when you create a class, it will result in no rational difference between the class and the class.CodeIt is very difficult. Once someone takes over or maintains it, it will make others spend a lot of energy to familiarize themselves with your process. Besides, modifying the code will also cause a chain reaction. The old bug is gone, and the new bug is coming again. The process will be clear and the code will be read more smoothly if the class is detailed according to its responsibilities.

For example, to fulfill the following requirements,

 
A text file: Nokia = n8 Motorola = me525 + Huawei = honorhtc = a3366/t9299 Xiaomi = m1

Button to trigger an event, read the <key, value> in the file and display it in RichTextBox. Effect.

some people may write like this. For example, when I first started writing code, I thought like this. All the operations are in form:

Public partial class form1: FORM {public form1 () {initializecomponent ();} private void button#click (Object sender, eventargs e) {string filepath = application. startuppath + @ "\ configure \ test.txt"; dictionary <string, string> contentdictionary = new dictionary <string, string> (); If (! File. exists (filepath) {return;} filestream = NULL; streamreader = NULL; try {filestream = new filestream (filepath, filemode. open, fileaccess. read); streamreader = new streamreader (filestream, encoding. default); filestream. seek (0, seekorigin. begin); string content = streamreader. readline (); While (content! = NULL) {If (content. contains ("=") {string key = content. substring (0, content. lastindexof ("= ")). trim (); string value = content. substring (content. lastindexof ("=") + 1 ). trim (); If (! Contentdictionary. containskey (key) {contentdictionary. Add (Key, value) ;}} content = streamreader. Readline () ;}} catch {} finally {If (filestream! = NULL) {filestream. Close ();} If (streamreader! = NULL) {streamreader. close () ;}string rctboxtext = "read content:" + system. environment. newline; foreach (string key in contentdictionary. keys) {rctboxtext + = Key + @ "=" + contentdictionary [Key] + system. environment. newline;} This. richtextbox1.text = rctboxtext;} // public static dictionary <string, string> readlinefile ()//{//}}

Write the read part into a method. So we can see how much responsibility the interface has taken on: Display, read, and maintain the file path. If the file to be read is put somewhere else, you need to open the code modification on the interface. In addition, it is unreasonable to reference the IO assembly in the read part. What is the relationship between the interface and IO? The interface should focus on the display series. So let's modify it. Separate by duties.

Common class, responsible for maintaining paths and other public variables or methods.

 
Public class common {public static string startuppath {get {return application. startuppath + @ "\ configure \";}}}

The readfilemanager class is only responsible for reading. The main interface does not care about the process. The main interface only needs results. In this way, even if an error occurs in the readfilemanager class, the program will not crash and only result errors will be reflected on the interface.

The interface is only responsible for displaying,

Public partial class form1: FORM {public form1 () {initializecomponent ();} private void button#click (Object sender, eventargs e) {dictionary <string, string> contentdictionary = readfilemanager. readlinefile (); string rctboxtext = "read content:" + system. environment. newline; foreach (string key in contentdictionary. keys) {rctboxtext + = Key + @ "=" + contentdictionary [Key] + system. environment. newline;} This. richtextbox1.text = rctboxtext ;}}

This is just a simple requirement. For complex programs, for example, there are many main interface controls, you need to create another class formmanager, which is responsible for managing the main interface. Like the above Code, the main interface should not directly call readfilemanager. readlinefile (), but be directly handed over to formmanager.

2. A single task improves program robustness. This is easy to understand. If a class completes only one task, the immediate operation fails, and the impact is very small. For example, if an error occurs during the reading process like the method previously modified, the program may be suspended directly. Take me as an example. In the first project, there is no design pattern or programming principle when writing code. All operations are often performed on the main interface, even SQL statements are directly in the Form class. As a result, there are many main interface controls, and each control operation is also written in the main interface. It includes some minor functions: pallets, determining network connections, and dragging the interface. They are all put together. After the project is completed, there are more than 10 thousand lines of classes on the main interface, and thousands of lines of code on other subforms are also supported. As a result, when the bug was modified, the bug was changed and another one appeared. Very tired.

Of course, the single responsibility principle does not mean that only one responsibility can be defined for the class, but emphasizes that the relationship between the responsibility and the object must be considered when defining the class responsibility. The responsibility must properly express the behavior of the object, so as not to undermine the beauty of harmony and balance, or even be out of fit. In other words, the single responsibility described in this principle refers to a set of public responsibilities closely related to the object. For example, if you want to add a file writing function in the preceding example, you can reorganize and create a new filemanager class, which includes the existing readlinefile (), wriete (), other methods related to file operations, such as reading files to write a class, writing files to write a class, because from the perspective of responsibility, the two methods of reading and writing files are cohesive and fully comply with the requirements of "only one thing for a class" in the single responsibility principle.

 

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.