」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > S - 單一職責原則(SRP)

S - 單一職責原則(SRP)

發佈於2024-11-06
瀏覽:840

S - Single Responsibility Principle(SRP)

Single Responsibility Principle(SRP)

The Single Responsibility Principle(SRP) is the first of the SOLID principles, which plays an important role in object-oriented programming.

The main point of this principle is: A class or module should have only one responsibility. In other words, a class, module, or function should be used or modified for only one reason.

Detailed Explanation:

  1. Definition of Responsibility:
    Responsibility refers to the specific task or functionality that a class or module performs or manages.

  2. Importance of Single Responsibility:

  • Easy Maintenance: When a class or function has a single responsibility, it's easier to update or modify because the impact of changes is limited.

  • Reusability: Classes or functions with a single responsibility are easier to reuse in other projects or modules.

  • Reduced Complexity: Code complexity is reduced because each class or function has clear and limited tasks.

  • Easy Testing: Small and well-defined classes are easier to test.

For example, let's say we have a class that handles both data processing and file management tasks. This violates the Single Responsibility Principle. In this case, we can create separate classes for data processing and file management. This way, if we need to make changes related to file management in the future, it won't affect the data processing functionality.

Example 1:

Let's say we have a User class that both stores user information and prints that information to the console.

// Java code

public class User {
    private String name;
    private String email;

    // Constructor, Getter, Setter

    public void printUserDetails() {
        System.out.println("Name: "   name);
        System.out.println("Email: "   email);
    }
}

Here, the User class is handling two responsibilities:

  • Storing user information.
  • Printing user information to the console.

According to the Single Responsibility Principle, this class should be divided into two separate classes:

// Java code

// For storing user information
public class User {
    private String name;
    private String email;

    // Constructor, Getter, Setter
}

// For printing user information
public class UserPrinter {
    public void printUserDetails(User user) {
        System.out.println("Name: "   user.getName());
        System.out.println("Email: "   user.getEmail());
    }
}

This way, the responsibility of each class becomes clear and distinct. If we need to change the way information is printed in the future, only the UserPrinter class needs to be modified, while the User class remains unchanged.

Example 2:

Let's say we are building a task management system where a Task class is responsible for creating tasks, updating them, and checking if a task is completed.

// JavaScript code:

class Task {
    constructor(name, completed = false) {
        this.name = name;
        this.completed = completed;
    }
    completeTask() {
        this.completed = true;
    }
    updateTask(name) {
        this.name = name;
    }
    notifyUser() {
        console.log(`Task "${this.name}" is completed!`);
    }
}

const task = new Task('Learn JavaScript');
task.completeTask();
task.notifyUser();

Here, the Task class is handling three different responsibilities:

  • Creating and updating tasks.
  • Completing tasks.
  • Notifying the user when a task is completed.

This violates the Single Responsibility Principle because multiple responsibilities are handled within one class.

Refactoring the code to follow SRP:

Now, we will split these responsibilities into separate classes so that each class has only one responsibility.

// JavaScript code:

// For creating and updating tasks
class Task {
    constructor(name, completed = false) {
        this.name = name;
        this.completed = completed;
    }

    updateTask(name) {
        this.name = name;
    }

    completeTask() {
        this.completed = true;
    }
}

// For notifying the user about task completion
class TaskNotifier {
    notifyUser(task) {
        if (task.completed) {
            console.log(`Task "${task.name}" is completed!`);
        } else {
            console.log(`Task "${task.name}" is not yet completed.`);
        }
    }
}

const task = new Task('Learn JavaScript');
task.completeTask();

const notifier = new TaskNotifier();
notifier.notifyUser(task);

How does this follow the SRP?

  • The Task class is now only responsible for creating and updating tasks. It handles changing the task's name or marking it as completed.

  • The TaskNotifier class is solely responsible for notifying the user about the task's status.

Benefits:

  • If in the future, we need to perform additional actions when a task is completed (e.g., sending an email), only the TaskNotifier class will need to be changed. The Task class remains unchanged.

  • The code is now cleaner, more modular, and easier to maintain.

By following the Single Responsibility Principle, this example shows how breaking the code into smaller, specialized classes can make maintenance easier and improve clarity.

Single Responsibility Principle in React.

Applying the SOLID principles while building a React application can bring significant changes. These principles are fundamental concepts of object-oriented design that provide a strong foundation for writing clean, efficient, and maintainable code. As a result, our React components will not only be functional but also easier to manage and extend.

According to the Single Responsibility Principle (SRP), a class or component should only change for one reason, meaning it should have only one responsibility or task.

How to Apply SRP in React:

To follow the Single Responsibility Principle (SRP) in React:

  • Each Component Should Have a Specific Task or Functionality:
    Each component should serve a single purpose. For example, a component might only display form data, show a user profile, or render a list of items.

  • Keep Components Small and Specialized:
    This makes it easier to test and update each component individually. Smaller, more focused components can be reused across the application, leading to better maintainability and clarity.

By adhering to these guidelines, you can create a more organized and manageable codebase in your React applications.

Example 1:

Let's say we are building a todo application where one component displays a list of tasks, and another component handles the form for adding new tasks.

Good Design According to SRP:

TaskList Component:

function TaskList({ tasks }) {
    return (
        
    {tasks.map(task => (
  • {task.name}
  • ))}
); }
  • This component is responsible solely for displaying the list of tasks.

AddTaskForm Component:

// JavaScript Code:

function AddTaskForm({ onAdd }) {
    const [taskName, setTaskName] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        onAdd(taskName);
        setTaskName("");
    };

    return (
        
setTaskName(e.target.value)} placeholder="Add a new task" />
); }
  • This component is solely responsible for managing a form to add new tasks.

Why Following SRP is Beneficial?

  1. Increased Reusability of Components:
    If we want to change only the task list, we can simply update the TaskList component. If we need to modify the form for adding new tasks, we only need to update the AddTaskForm component. This separation makes components more reusable across different parts of the application.

  2. Easier Debugging and Maintenance:
    Instead of handling multiple responsibilities, each component performs a single task. This makes it easier to find and fix bugs, as the scope of potential issues is limited to one component.

  3. Improved Code Understandability for Other Developers:
    Components with clearly defined responsibilities are easier to understand. Smaller, focused components make the codebase more approachable for other developers who might work on the project.

By applying the Single Responsibility Principle (SRP), our React application becomes clearer, more modular, and easier to maintain.

Example 2:

In this example, we have created two separate components: UserProfile and AuthManager, each with a specific task or responsibility.

UserProfile.js:

// JavaScript code

const UserProfile = ({ user }) => (
  

{user.name}

{user.bio}

);

Responsibility of the UserProfile Component:

  • The UserProfile component is solely responsible for displaying the user's profile. It shows the user's name and bio.

AuthManager.js:

// JavaScript code 
const AuthManager = () => (
  
{/* Authentication logic here */} Login Form
);

Responsibility of the AuthManager Component:

  • The AuthManager component is created to handle authentication. It displays the login form and manages the logic required for authentication.

Why This Follows the Single Responsibility Principle (SRP)?

  • Each Component Has a Specific Responsibility:
  • The UserProfile component focuses solely on displaying profile information.

  • The AuthManager component is dedicated to handling authentication logic.

  • Components Are Separate, Manageable, and Testable:
  • If we need to make changes related to displaying profile information, we only need to modify the UserProfile component.

  • Similarly, any updates regarding authentication can be made exclusively within the AuthManager component.

  • Increased Code Reusability:
  • We can reuse the UserProfile and AuthManager components in various parts of our application since they perform specific responsibilities.

By adhering to the Single Responsibility Principle, each component is assigned a single responsibility, which makes the code clean, modular, and easier to maintain.

Disadvantages of the Single Responsibility Principle (SRP)

Disadvantages of the Single Responsibility Principle (SRP)
While the Single Responsibility Principle (SRP) offers numerous advantages, there are also some limitations and challenges that developers may need to consider. Here are some of the key drawbacks:

  1. Increased Number of Components or Classes:
    Following SRP requires creating separate components or classes for each task or responsibility, which can lead to a rapid increase in the number of components or classes in the application. This can make the codebase harder to manage.

  2. Increased Complexity:
    The proliferation of small components or classes can complicate their coordination. Passing data and facilitating communication between various components may become challenging.

  3. Excessive Abstraction:
    Overzealous application of SRP can sometimes result in unnecessary abstraction. Creating too many small components or classes may make the code harder to read and understand, especially if each component's role is trivial.

  4. Learning Curve:
    New developers may find it difficult to fully understand and apply SRP. It requires experience and a clear understanding of how to break down an application into smaller, reusable components.

  5. Overhead in Testing:
    With many small components being created, there is a need to write separate tests for each one. This can increase the time and complexity involved in writing test code.

  6. Balance in Applying SRP:
    It may not always be practical to apply SRP strictly. Sometimes, it can be more effective for a component or class to handle a few closely related responsibilities. Applying SRP excessively can unnecessarily complicate the code, making it more difficult to read and maintain.

By considering these disadvantages, developers can make informed decisions about when and how to apply the Single Responsibility Principle in their projects.

In summary, SRP (Single Responsibility Principle) is a powerful principle that helps keep code clean, modular, and maintainable. However, it should be applied with its limitations in mind. Sometimes, excessive use of the principle can have the opposite effect, so it is important to maintain balance according to the specific needs of the code.

版本聲明 本文轉載於:https://dev.to/nozibul_islam_113b1d5334f/s-single-responsibility-principlesrp-h4g?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 為什麼我的CSS背景圖像出現?
    為什麼我的CSS背景圖像出現?
    故障排除:CSS背景圖像未出現 ,您的背景圖像儘管遵循教程說明,但您的背景圖像仍未加載。圖像和样式表位於相同的目錄中,但背景仍然是空白的白色帆布。 而不是不棄用的,您已經使用了CSS樣式: bockent {背景:封閉圖像文件名:背景圖:url(nickcage.jpg); 如果您的html,cs...
    程式設計 發佈於2025-03-11
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-03-11
  • 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    使用http request 上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    程式設計 發佈於2025-03-11
  • 可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    可以在純CS中將多個粘性元素彼此堆疊在一起嗎?
    [2这里: https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> { display:grid; grid-template-...
    程式設計 發佈於2025-03-11
  • 如何使用組在MySQL中旋轉數據?
    如何使用組在MySQL中旋轉數據?
    在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。 Let's consider the following ...
    程式設計 發佈於2025-03-11
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript [#1089-不正確的前綴鍵在嘗試在表中創建一個prefix鍵時會出現。前綴鍵旨在索引字符串列的特定前綴長度長度,可以更快地搜索這些前綴。 了解prefix keys `這將在整個Movie_ID列上創建標準主鍵。主密鑰對於唯一識...
    程式設計 發佈於2025-03-11
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-03-11
  • 如何克服PHP的功能重新定義限制?
    如何克服PHP的功能重新定義限制?
    克服PHP的函數重新定義限制在PHP中,多次定義一個相同名稱的函數是一個no-no。嘗試這樣做,如提供的代碼段所示,將導致可怕的“不能重新列出”錯誤。 但是,PHP工具腰帶中有一個隱藏的寶石:runkit擴展。它使您能夠靈活地重新定義函數。 runkit_function_renction_...
    程式設計 發佈於2025-03-11
  • 大批
    大批
    [2 數組是對象,因此它們在JS中也具有方法。 切片(開始):在新數組中提取部分數組,而無需突變原始數組。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    程式設計 發佈於2025-03-11
  • 如何在Java字符串中有效替換多個子字符串?
    如何在Java字符串中有效替換多個子字符串?
    在java 中有效地替換多個substring,需要在需要替換一個字符串中的多個substring的情況下,很容易求助於重複應用字符串的刺激力量。 However, this can be inefficient for large strings or when working with nu...
    程式設計 發佈於2025-03-11
  • 為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    程式設計 發佈於2025-03-11
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, attributeError:SomeClass實...
    程式設計 發佈於2025-03-11
  • 如何干淨地刪除匿名JavaScript事件處理程序?
    如何干淨地刪除匿名JavaScript事件處理程序?
    刪除匿名事件偵聽器將匿名事件偵聽器添加到元素中會提供靈活性和簡單性,但是當要刪除它們時,可以構成挑戰,而無需替換元素本身就可以替換一個問題。 element? element.addeventlistener(event,function(){/在這里工作/},false); 要解決此問題,請考...
    程式設計 發佈於2025-03-11
  • 如何使用不同數量列的聯合數據庫表?
    如何使用不同數量列的聯合數據庫表?
    合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
    程式設計 發佈於2025-03-11
  • Java是否允許多種返回類型:仔細研究通用方法?
    Java是否允許多種返回類型:仔細研究通用方法?
    在Java中的多個返回類型:一種誤解類型:在Java編程中揭示,在Java編程中,Peculiar方法簽名可能會出現,可能會出現,使開發人員陷入困境,使開發人員陷入困境。 getResult(string s); ,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但這確實是如此嗎...
    程式設計 發佈於2025-03-11

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3