Java: method-chaining and dependency injection -


is acceptable use method-chaining, when working service managed dependency injection framework (say hk2)?

i'm unsure if allowed "cache" instance, if within scope of injection.

example service creates pizza:

@service public class pizzaservice {      private boolean peperoni = false;     private boolean cheese = false;     private boolean bacon = false;      public pizzaservice withpeperoni() {         peperoni = true;         return this;     }      public pizzaservice withcheese() {         cheese = true;         return this;     }      public pizzaservice withbacon() {         bacon = true;         return this;     }      public pizza bake() {         // create instance , return     } } 

here service injected jax-rs resource:

@path('pizza') public class pizzaresource {      @inject     pizzaservice pizzaservice;      @get     public response getpizza() {         pizza pizza = pizzaservice             .withpeperoni()             .withcheese()             .bake();          return response.ok(pizza).build();     } } 

what doing has side effect other users of service. share same instance of service, if call withpeperoni change value of boolean have reference service.

what seem want use builder. perhaps service can instantiate new builder have responsibility build perfect pizza you. way avoid possible side effects :

@get public response getpizza() {     pizza pizza = pizzaservice.newpizzabuilder()         .withpeperoni()         .withcheese()         .bake();      return response.ok(pizza).build(); } 

and pizzabuilder :

public class pizzabuilder {      private boolean peperoni = false;     private boolean cheese = false;     private boolean bacon = false;      public pizzabuilder withpeperoni() {         peperoni = true;         return this;     }      public pizzabuilder withcheese() {         cheese = true;         return this;     }      public pizzabuilder withbacon() {         bacon = true;         return this;     }      public pizza bake() {         // create instance , return     } } 

and pizzaservice :

@service public class pizzaservice {      public pizzabuilder newpizzabuilder() {         return new pizzabuilder();     } } 

this solution not perfect, because there not use of service instantiates builder, @ least prevents side effects you'll encounter solution.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -