Skip to main content
added 67 characters in body
Source Link

This is another option in addition to amon's answer

Use Builders:

 class Foo { private Bar bar; private Qux qux; private Foo() { } public Foo(Builder builder) { this.bar = builder.bar; this.qux = builder.qux; } public static class Builder { private Bar bar; private Qux qux; public Buider setBar(Bar bar) { this.bar = bar; return this; } public Builder setQux(Qux qux) { this.qux = qux; return this; } public Foo build() { return new Foo(this); } } } // in production: Foo foo = new Foo.Builder() .setBar(new Bar()) .setQux(new Qux()) .build(); // in test: Foo testFoo = new Foo.Builder() .setBar(new BarMock()) .setQux(new Qux()) .build(); 

This is what I use for dependencies. I don't use any DI framework. They get in the way.

This is another option in addition to amon's answer

Use Builders:

 class Foo { private Bar bar; private Qux qux; private Foo() { } public Foo(Builder builder) { this.bar = builder.bar; this.qux = builder.qux; } public static class Builder { private Bar bar; private Qux qux; public setBar(Bar bar) { this.bar = bar; } public setQux(Qux qux) { this.qux = qux; } public Foo build() { return new Foo(this); } } } // in production: Foo foo = new Foo.Builder() .setBar(new Bar()) .setQux(new Qux()) .build(); // in test: Foo testFoo = new Foo.Builder() .setBar(new BarMock()) .setQux(new Qux()) .build(); 

This is what I use for dependencies. I don't use any DI framework. They get in the way.

This is another option in addition to amon's answer

Use Builders:

 class Foo { private Bar bar; private Qux qux; private Foo() { } public Foo(Builder builder) { this.bar = builder.bar; this.qux = builder.qux; } public static class Builder { private Bar bar; private Qux qux; public Buider setBar(Bar bar) { this.bar = bar; return this; } public Builder setQux(Qux qux) { this.qux = qux; return this; } public Foo build() { return new Foo(this); } } } // in production: Foo foo = new Foo.Builder() .setBar(new Bar()) .setQux(new Qux()) .build(); // in test: Foo testFoo = new Foo.Builder() .setBar(new BarMock()) .setQux(new Qux()) .build(); 

This is what I use for dependencies. I don't use any DI framework. They get in the way.

Source Link

This is another option in addition to amon's answer

Use Builders:

 class Foo { private Bar bar; private Qux qux; private Foo() { } public Foo(Builder builder) { this.bar = builder.bar; this.qux = builder.qux; } public static class Builder { private Bar bar; private Qux qux; public setBar(Bar bar) { this.bar = bar; } public setQux(Qux qux) { this.qux = qux; } public Foo build() { return new Foo(this); } } } // in production: Foo foo = new Foo.Builder() .setBar(new Bar()) .setQux(new Qux()) .build(); // in test: Foo testFoo = new Foo.Builder() .setBar(new BarMock()) .setQux(new Qux()) .build(); 

This is what I use for dependencies. I don't use any DI framework. They get in the way.