Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Anti Patterns

Generic Interface over Function

We should create generic interfaces only if they are adding value and increasing readability of the code.

export interface MessageTranslator<A, B> {
  to(from: A): B;
}
export class Processor {
  private detectIntentRequestTranslator: MessageTranslator<DetectIntentRequestDF, DetectIntentRequest>;
  private detectIntentResponseTranslator: MessageTranslator<DetectIntentResponse, DetectIntentResponseDF>;

  constructor() {
    this.detectIntentRequestTranslator = new DetectIntentRequestTranslator();
    this.detectIntentResponseTranslator = new DetectIntentResponseTranslator();
  }

  doSomething(): number {
    const request: DetectIntentRequest = this.detectIntentRequestTranslator.to(call.request);
    const resposne: DetectIntentResponse = this.detectIntentResponseTranslator.to(call.response);
    // do something
    return 1;
  }
}

The code above could look like this. We could just create the transformation functions and use them directly, because they are pure functions.

function toIntentRequest(request): DetectIntentRequest {
  return new DetectIntentRequest();
}

function toIntentResponse(request): DetectIntentResponse {
  return new DetectIntentResponse();
}

export class Processor {

  doSomething(): number {
    const request = toIntentRequest(call.request);
    const response = toIntentResponse(call.response);
    // do something
    return 1;
  }
}
PreviousOver Patternized

Last updated 5 years ago

Was this helpful?