기능을 분리하고 각 객체에게 분리한 기능을 제공할 책임을 배분하는 것 (기능은 곧 책임)
[클래스나 메서드가 커지지 않도록 책임을 분배/분리하는 방법]
(역할 분리 시 의도가 잘 드러나는 이름 사용)
public class CashClient {
private SecretKeySpec ketSpec;
private IvParameterSpec ivSpec;
private Res post(Req req) {
String reqBody = toJson(req);
Cipher cipher = Cipher.getInstance(DEFAULT_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
String encReqBody = new String(Base64.getEncoder().encode(cipher.doFinal(reqBody)));
ResponseEntity<String> responseEntity = restTemplate.postForEntity(api, encReqBody, String.class);
String encRespBody = responseEntity.getBody();
Cipher cipher2 = Cipher.getInstance(DEFAULT_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
String encReqBody = new String(cipher.doFinal(Base64.getDecoder().decode(encRespBody)));
return jsonToObj(respBody);
}
}
// 분리
public class CashClient {
private Cryptor cryptor;
private Res post(Req req) {
String reqBody = toJson(req);
String encReqBoddy = cryptor.encrypt(reqBody);
ResponseEntity<String> responseEntitiy = restTemplate.postForEntity(api, encReqBody, String.class);
String encRespBody = cryptor.decrypt(encRespBody);
return jsonToObj(respBody);
}
public class Cryptor {
private SecretKeySpec keySpec;
private IvParameterSpec ivSpec;
public String encrypt(String plain) {
Cipher cipher = Cipher.getInstance(DEFAULT_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return new String(Base64.getEncoder().encode(cipher.doFinal(plain)));
}
public String decrypt(String encrypted) {
Cipher cipher2 = Cipher.getInstance(DEFAULT_TRANSFORM);
cipher2.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(Base64.getDecoder().decode(encrypted)));
}