Should the class have a has-a relationship with the configuration class?

I saw some questions about packing a set of configuration properties in a class, but not about how to use it. Given the configuration class (omitting getters and setters for short):

class ServiceConfiguration {
    private String foo;     
}

Should the service class use configuration directly?

static class SomeServiceB {
    private ServiceConfiguration configuration;

    public SomeServiceB(ServiceConfiguration configuration) {
        this.configuration = configuration;
    }

    public void printIt() {
        System.out.println(configuration.getFoo());
    }
} 

Or should this only concern the actual value of foo? For instance:

static class SomeServiceA {
    private String foo;

    public SomeServiceA(String foo) {
        this.foo = foo;
    }

    public void printIt() {
        System.out.println(foo);
    }
}

I would say SomeServiceA excels due to lower communication and separation of concerns.

+4
source share
1 answer

Both solutions are correct. The important part is that the class only accepts a dependency on the configuration values ​​that it actually uses.

, ApplicationConfiguration, , , , , . : .

, , , , . .

( ) , DI . , , . :

class SomeServiceB {
    public SomeServiceB(IDep1 d1, IDep2 d2, SomeServiceConfig config) {
    }
} 

DI, , , : . , , . .

, , , , . .

0

Source: https://habr.com/ru/post/1682151/


All Articles