java - How to optimize duplicate parts in multiple methods -


i have old validation methods,and have common part.

@service public class validator implements ivalidator {      @resource     private companyrepository companyrepository;      @override     public void valida(string parama, long id) {          //do logic processing of parama          company company = companyrepository.load(id);         //convert company companydto         companydto companydto = companyparser.fromcompany(company);          //do logic     }      @override     public void validb(string paramb, long id) {          //do logic processing of paramb          company company = companyrepository.load(id);         //convert company companydto         companydto companydto = companyparser.fromcompany(company);          //do logic     }      @override     public void validc(string paramc, long id) {          //do logic processing of paramc          company company = companyrepository.load(id);         //convert company companydto         companydto companydto = companyparser.fromcompany(company);          //do logic     }  } 

now, have new method needs validate number of parameters in 1 go, such as:

    valida(parama, id);     validb(paramb, id);     validc(paramc, id); 

if company big, method of companyparser.fromcompany(company) take long time.

if don't modify old method, there ways optimize?

first, extract out loading , conversion of company/dto, , add overload take companydto instead of id:

@service public class validator implements ivalidator {      @resource     private companyrepository companyrepository;      @override     public void valida(string parama, long id) {         valida(parama, loadcompanydto(id));     }      private void valida(string parama, companydto companydto) {          //do logic processing of parama          //do logic     }      private companydto loadcompanydto(long id) {         company company = companyrepository.load(id);         //convert company companydto         return companyparser.fromcompany(company);     } } 

this refactor not change external interface (contract) of class, , should continue execute normal (your unit tests should still pass).

then can create new method:

public validparams(string parama, string paramb, string paramc, long id) {     companydto companydto = loadcompanydto(id);     valida(parama, companydto);     validb(paramb, companydto);     validc(paramc, companydto); } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -