#Template Method Pattern

1 messages · Page 1 of 1 (latest)

rich quarry
#

I have classes that look something like this:

public abstract class EmitterBase {
  protected Boolean shouldEmit(Metadata metadata, ...){//Implementation and uses metadata twice
  String config = metadata != null ? metadata.getConfig() : extractConfig();
return isEmittingEnabled(metadata, ...) && 
// config related stuff
}

private String extractConfig(){//Implementation}
}

@RequiredArgsConstructor
public Emitter extends EmitterBase {
  private final UserFactory userFactory; // injected by spring

  public emit(Metadata metadata, ...) {
if(shouldEmit(metadata, ...))
// Emits stuff}
}

I want to refactor the class to use the template method pattern to something like this

@RequiredArgsConstructor
public abstract class EmitterBase {
// Moved factory here
private final UserFactory userFactory;
// Got rid of metadata
  protected Boolean shouldEmit( ...){

}
public void final templateMethod() {
if (shouldEmit()){
doSomething();
foo();
bar();
emitSegment();
}
private abstract void emitSegment();
}

public Emitter extends EmitterBase {
  Metadata metadata;
  public Emitter(Metadata metadata, ...}
}

Since that metadata is coupled to everything and is used with null checks. However, im not sure if this is correct and not sure how we can inject metadata into spring since it needs to be changed dynamically.

sleek roseBOT
#

<@&1004656351647117403> please have a look, thanks.

sleek roseBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.