


An introduction to the seven principles of object-oriented design in C#
1: Single Responsibility Principle (SRP)
1. Definition: An object should only contain a single responsibility, and the responsibility is completely encapsulated in a class
Or: As far as a class is concerned, there should be only one reason for its change.
2. Analysis: The more responsibilities a class (or as large as a module or as small as a method) bears, the less likely it is to be reused, and if a class bears too many responsibilities, it will be quite Due to coupling these responsibilities together, when one of the responsibilities changes, it may affect the operation of other responsibilities. The responsibilities of a class mainly include two aspects: data responsibilities and behavioral responsibilities. Data responsibilities are reflected through its attributes, while behavioral responsibilities are reflected through its methods. The single responsibility principle is a guideline for achieving high cohesion and low coupling. It can be found in many code refactoring techniques. It is the simplest but most difficult principle to apply. It requires designers to discover the different responsibilities of classes and Separating them and discovering the multiple responsibilities of classes requires designers to have strong analysis and design capabilities and relevant refactoring experience.
3. Example:
The example shows that the "login function" of a Java-based C/S system is implemented through the following login class (Login):
The single responsibility principle is now used for it Refactor.
2: Open-Closed Principle (OCP)
1. Definition: A software entity should be open to extensions and closed to modifications. That is to say, when designing a module, the module should be extended without being modified, that is, the behavior of the module can be changed without modifying the source code.
2. Analysis: The opening and closing principle was proposed by Bertrand Meyer in 1988. It is one of the most important principles in object-oriented design. In the definition of the open-closed principle, a software entity can refer to a software module, a partial structure composed of multiple classes, or an independent class. Abstraction is key to the Open/Closed Principle. The opening and closing principle can also be described by a more specific "Principle of Encapsulation of Variation". The Principle of Encapsulation of Variation (EVP) requires finding the variable factors of the system and encapsulating them.
3: Liskov Substitution Principle (LSP)
1. Definition: If for every object o1 of type S, there is an object o2 of type T, So that the behavior of all programs P defined with T does not change when all objects o1 are replaced with o2, then type S is a subtype of type T
Or: all reference base classes (parent Class) must be able to transparently use objects of its subclasses.
2. Analysis: The Liskov substitution principle was developed by Barbara Liskov, the 2008 Turing Award winner, the first female doctor of computer science in the United States, professor at MIT, and Professor Jeannette Wing at Carnegie Mellon University. Proposed in 1994.
The Liskov substitution principle can be expressed in a popular way: if you can use base class objects in software, then you must be able to use its subclass objects. If the base class is replaced with its subclasses, the program will not generate any errors or exceptions. The reverse is not true. If a software entity uses a subclass, it may not be able to use the base class. The Liskov substitution principle is one of the important ways to implement the opening and closing principle. Since subclass objects can be used wherever base class objects are used, try to use base class types to define objects in the program, and then use them at runtime. Determine its subclass type and replace the parent class object with the subclass object.
4: Dependence Inversion Principle (DIP)
1. Definition: High-level modules should not rely on low-level modules, they should all rely on abstraction. Abstraction should not depend on details, details should depend on abstraction
Or: Program for interfaces, not implementations. (Program to an interface, not an implementation.)
2. Analysis: The Dependency Inversion Principle is the third column of Engineering Notebook written by Robert C. Martin for "C++ Reporter" in 1996, and was later added To his classic book "Agile Software Development, Principles, Patterns, and Practices" published in 2002.
Simply put, the principle of dependency inversion means: code should depend on abstract classes, not concrete classes; programming should be for interfaces or abstract classes, not for concrete classes. The key to realizing the opening and closing principle is abstraction, and concrete implementation is derived from abstraction. If the opening and closing principle is the goal of object-oriented design, then the dependency inversion principle is the main method of object-oriented design.
One of the common ways to implement the dependency inversion principle is to use abstract classes in the code and place concrete classes in the configuration file.
Coupling between classes
Zero coupling relationship
Concrete coupling relationship
Abstract coupling relationship
Dependency inversion principle requires the client Depend on abstract coupling Coupling in an abstract way is the key to the dependency inversion principle.
Dependency Injection
Constructor Injection: Inject instance variables through the constructor.
Setter Injection: Inject instance variables through the Setter method.
Interface Injection: Inject instance variables through interface methods.
5: Interface Segregation Principle (ISP)
1. Definition: The client should not rely on interfaces that it does not need. Note that the interface in this definition refers to defined method.
Or: Once an interface is too large, it needs to be divided into smaller interfaces. The client using the interface only needs to know the methods related to it.
2. Analysis: The principle of interface isolation refers to using multiple specialized interfaces instead of using a single total interface. Each interface should assume a relatively independent role, no more and no less. It should not do things that it should not do, but should do everything that should be done.
(1) An interface only represents one role, and each role has its own specific interface. This principle can be called the "role isolation principle".
(2) The interface only provides the behaviors that the client needs, that is, the required methods. The behaviors that the client does not need are hidden. The client should be provided with a separate interface as small as possible instead of providing Large overall interface.
When using the interface isolation principle to split an interface, you must first satisfy the single responsibility principle, define a set of related operations in an interface, and on the premise of meeting high cohesion, the fewer methods in the interface The better. You can use customized services when designing the system, that is, providing interfaces with different widths for different clients, only providing the behaviors that users need, and hiding the behaviors that users do not need.
6: Composite Reuse Principle (CRP), also known as Composition/ Aggregate Reuse Principle (CARP)
1. Definition: Use objects as much as possible Composition rather than inheritance to achieve reuse. (Favor composition of objects over inheritance as a reuse mechanism.)
2. Analysis: The principle of composition and reuse refers to using some existing objects in a new object through association relationships (including combination relationships and aggregation relationships) existing objects, making them part of a new object; the new object achieves the purpose of reusing its existing functions by delegating and calling methods of existing objects. In short: Use composition/aggregation relationships as much as possible and inheritance less often.
In object-oriented design, existing designs and implementations can be reused in different environments through two basic methods, namely through composition/aggregation relationships or through inheritance.
Inheritance and reuse: simple to implement and easy to extend. Destroys the encapsulation of the system; the implementation inherited from the base class is static, cannot be changed at runtime, and does not have enough flexibility; it can only be used in limited environments. ("White box" reuse)
Combination/aggregation reuse: The degree of coupling is relatively low, and the operations of member objects are selectively called; it can be done dynamically at runtime. ("Black box" reuse)
Combination/aggregation can make the system more flexible, reduce the coupling between classes, and changes in one class have relatively little impact on other classes, so combination/aggregation is generally preferred. To achieve reuse; secondly consider inheritance. When using inheritance, you need to strictly follow the Liskov substitution principle. Effective use of inheritance will help understand the problem and reduce complexity, while abuse of inheritance will increase system construction and maintenance. The difficulty and complexity of the system require careful use of inheritance reuse.
7: Law of Demeter (LoD), also known as Least Knowledge Principle (LKP)
1. Definition:
(1 ) Don’t talk to “strangers.” The English definition is: Don't talk to strangers.
(2) Only communicate with your direct friends. The English definition is: Talk only to your immediate friends.
(3) Each software unit has minimal knowledge of other units and is limited to those software units that are closely related to its own unit. The English definition is: Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
2. Analysis: Demeter's law comes from Northeastern University in the autumn of 1987 ) a research project called "Demeter". Simply put, Demeter's Law means that a software entity should interact with other entities as little as possible. In this way, when one module is modified, it will affect other modules as little as possible, and expansion will be relatively easy. This is a restriction on communication between software entities. It requires limiting the width and depth of communication between software entities.
The above is the detailed content of An introduction to the seven principles of object-oriented design in C#. For more information, please follow other related articles on the PHP Chinese website!

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.