简体   繁体   中英

Composition over Inheritance usage

I was having an argument with a colleague of mine.

Which of the following 2 code snippets feels better to you considering that "composition should be used instead of inheritance"?

1)

class JsonToSpecificTransformer implements Transformer {

    private final JsonToObjectTransformer jsonTransformer = Transformers.fromJson(Specific.class);

    @Override
    public Message<?> transform(Message<?> message) {
        return jsonTransformer.transform(message);
    }
}

2)

class JsonToSpecificTransformer2 extends JsonToObjectTransformer {
    public JsonToSpecificTransformer2() {
        super(Specific.class);
    }
}

The specific class would show something like this:

@Data
class Specific {
    private int field1;
    ...
}

I will comment a little bit about these 2 code snippets:

1) uses composition and keeps and inner object so that it doesn't get reinitialized every time.

2) uses inheritance.

Thanks!

Edit:

I am using a DSL IntegrationFlow something like:

@Autowired
private JsonToSpecificTransformer jsonToSpecificTransformer;

@Bean
public IntegrationFlow flow() {
   return IntegrationFlows.from("myChannel")
      .transform(Transformers.fromJson(service2.Specific.class)
      or
      .transform(jsonToSpecificTransformer)
      ...
}

Hope this previous code clarifies a little bit about my intentions.

And trying to summarize:


@Bean
public JsonToObjectTransformer jsonToSpecificTransformer() {
   return Transformers.fromJson(Specific.class);
}

---
@Autowired
//@Qualif...
private JsonToObjectTransformer  jsonToSpecificTransformer;

@Bean
public IntegrationFlow flow() {
   return IntegrationFlows.from("myChannel")
      .transform(jsonToSpecificTransformer)
      ...
}

Indeed. Doesn't look like you should abuse framework classes for this reason. They may change in the future breaking your code.

IMHO no inheritance, no composition at all.

You simply can have a bean like this:

@Bean
JsonToObjectTransformer jsonToSpecificTransformer() {
    return Transformers.fromJson(Specific.class);
}

And use it as a plain Transformer reference whenever you need. What is good in this that you don't need to have any extra classes to support at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM