Solid Design Principle # Single Responsibility

Chiwa Kantawong (Pea)
1 min readDec 25, 2019

--

ผมจะไม่อธิบายยืดยาวนะครับ ให้ดูที่โค้ดกันก็คงจะเข้าใจ ผมจะพยายามเขียนให้ simple และเข้าใจง่ายที่สุด

Single Responsibility

  • There should never be more than one reason to change the class.
  • Focused on one functionality
package solid.singleresponsibiligy;


public class Customer {

private String name;
private String address;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}


}
package solid.singleresponsibiligy;

import java.util.HashMap;
import java.util.Map;

public class Store {

private Map<String, Customer> customerMap = new HashMap<String, Customer>();

public void save(Customer customer) {
customerMap.put(customer.getName(), customer);
}

}
package solid.singleresponsibiligy;


import org.apache.commons.lang3.StringUtils;

public class CustomerController {

Store store = new Store();

public boolean createCustomer(Customer customer) {

if (!validCustomer(customer)) {
return false;
}

store.save(customer);
return true;
}

private boolean validCustomer(Customer customer) {
if (StringUtils.isEmpty(customer.getName()) || StringUtils.isEmpty(customer.getAddress())) {
return false;
}
return true;
}
}

จากโค้ดข้างบน CustomerController จะมีการ validation Customer ด้วย ซึ่งไม่ถูกหลักการของ Single Responsibility ใช่ไหมครับ เราจะแก้ไขยังไง ก็ย้าย vlidatCustome ไปไว้อีกคลาสหนึ่งครับ

package solid.singleresponsibiligy;

import org.apache.commons.lang3.StringUtils;

public class CustomerValidation {

private boolean validCustomer(Customer customer) {
if (StringUtils.isEmpty(customer.getName()) || StringUtils.isEmpty(customer.getAddress())) {
return false;
}
return true;
}
}

แล้วก็แก้ไข CustomerController เป็น

package solid.singleresponsibiligy;


public class CustomerController {

private Store store = new Store();
private CustomerValidation customerValidation = new CustomerValidation();

public boolean createCustomer(Customer customer) {

if (!customerValidation.validCustomer(customer)) {
return false;
}

store.save(customer);
return true;
}
}

ซึ่งต่อไปในอนาคตจะมีการเปลี่ยแปลงการ validate data ยังไง คลาสอื่นๆ ก็ไม่ต้องแก้ไข หรือว่าจะมีการเก็บข้อมูลยังไง ก็แก้ไขเฉพาะ Store class เท่านั้น จะไม่กระทบกับคลาสอื่นๆ อีกเช่นกัน

--

--

Chiwa Kantawong (Pea)
Chiwa Kantawong (Pea)

Written by Chiwa Kantawong (Pea)

Software Development Expert at Central Tech

No responses yet