java - How to refactor validators -


i thinking implementation validators. service method starts this:

if(badsituation()){     return response.status(400).entity("bad situtaion").build(); } if(badsituation2()){     return response.status(400).entity("bad situtaion2").build(); } ... if(badsituationn()){     return response.status(400).entity("bad situtaionn").build(); } 

since validators multiply fast have decided refactor them design pattern. thinking chain of responsibility or composite, had problem practical realization. can suggest how code should refactored?

you can use cor pattern validation "behavior" : each of validators implement base chainedvalidator interface (some of behavior can moved parent abstract class same chain members):

    public class myfirstvalidator implements chainedvalidator{         //this cor implementation has 'composite' background         chainedvalidator nextvalidator;          @override         private void dovalidate(request request) throws validationexception         {               if(badsituation){                     //throw validation exception               }         }          @override         public void dochainvalidate(request request) throws validationexception         {//this method can moved parent abstract class               dovalidate(request);               if(nextvalidator!=null){                     nextvalidator.dochainvalidate(request);               }         }          private void attachvalidator(chainedvalidator newvalidator) throws validationexception         {//same previous method               if(nextvalidator!=null){                     nextvalidator.attachvalidator(request);               }else{                     nextvalidator=newvalidator;               }         }         //setters & other methods     } 

on controllers/web tier service classes, can inject first chainedvalidator of validation chain , call dochainvalidate :

public class webtierservice{      chainedvalidator validator;      public response servicemethod(request request){         try{             //...             validator.dochainvalidate(request);             //...         }catch(validationexception e){              return response.status(400).entity(e.getmessage()).build();         }      } } 

as can see, logic 'fluid' (no if else check depending on type of validation error) , adding new validator relatively simple (validator.attachvalidator()) makes logic extensible , clean.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -