「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > 単一責任の原則

単一責任の原則

2024 年 11 月 9 日に公開
ブラウズ:364

Single Responsibility Principle

すべてのソフトウェア コンポーネントは 1 つの責任のみを持つ必要があります

ソフトウェア コンポーネントはクラス、メソッド、またはモジュールにすることができます

例: スイスアーミー ナイフはソフトウェア開発の単一責任原則に違反する多目的ツールですが、代わりにナイフは単一責任に従う良い例です (スイスアーミー ナイフとは異なり切断にしか使用できないため)切る、缶を開ける、マスターキー、ハサミなどとして使用できます)

現実世界でもソフトウェア開発でも変化は絶え間なく続くため、単一責任原則の定義もそれに応じて変わります

すべてのソフトウェア コンポーネントには、変更する理由が 1 つだけあるはずです


以下のクラス Employee

で変更が発生する理由は 3 つあります。
  1. 従業員属性の変更
  2. データベースの変更
  3. 税金計算の変更
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * Employee class has details of employee
 * This class is responsible for saving employee details, getting tax of
 * employee and getting
 * details of employee like name, id, address, contact, etc.
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

    public void save() {
        String insert = MyUtil.serializeIntoString(this);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values ("   insert   ")");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void calculateTax() {
        if (this.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (this.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

SRP (単一責任原則) は、クラス内の変更理由を 1 つだけ 推奨しているため、Employee クラスにいくつかの変更を加える必要があります


希望小売価格による変更

従業員クラスで変化が起こる理由は 1 つだけです

変更理由: 従業員属性の変更

/**
 * Employee class has details of employee
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

    public void save() {
       new EmployeeRepository().save(this);
    }

    public void calculateTax() {
       new TaxCalculator().calculateTax(this);
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

また、EmployeeRepository クラスで変更が発生する理由は 1 つだけです

変更の理由: データベースの変更

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class EmployeeRepository {

    public void save(Employee employee) {
         String insert = MyUtil.serializeIntoString(employee);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values ("   insert   ")");

        } catch (Exception e) {
            e.printStackTrace();
        }
}

}

最後に、TaxCalculator クラスで変更が発生する理由は 1 つだけです

変更理由: 税金計算の変更

public class TaxCalculator {

    public void calculateTax(Employee employee) {
        if (employee.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (employee.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }
}

注: 3 つのクラスはすべて単一責任原則に従い、両方の定義に従います

クラスまたはソフトウェア コンポーネントを作成するときは、次の点に留意してください: 高い凝集性と疎結合を目指す

すべてのソフトウェア コンポーネントは 1 つの責任のみを持つ必要があります および
すべてのソフトウェア コンポーネントには、変更する理由が 1 つだけあるはずです

リリースステートメント この記事は次の場所に転載されています: https://dev.to/prashantrmishra/single-responsibility-principle-m8n?1 侵害がある場合は、[email protected] に連絡して削除してください。
最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3