Skip to content

Instantly share code, notes, and snippets.

// Step 2
export class Renderer {
private readonly brush: GDIBrush;
private readonly renderingRoots: Point[];
private readonly colors: ColorMatrix;
private readonly selection: Point[];
constructor(
brush: GDIBrush,
// Step 1
export class GDIBrush {
private colorId: number;
// A long method
public draw(renderingRoots: Point[], colors: ColorMatrix, selection: Point[]): void {
// !!! -> we wrote this line and used the IDE to generate the new class
new Renderer(this, renderingRoots, colors, selection);
// some more code in the method
export class GDIBrush {
private colorId: number;
// A long method
public draw(renderingRoots: Point[], colors: ColorMatrix, selection: Point[]): void {
// some more code in the method
for (const point of renderingRoots) {
// a lot more code in the loop
this.drawPoint(point.x, point.y, colors.getColor(this.colorId));
}
export class RSCWorkflow {
private static MAX_LENGTH: number = 200;
//... more code
public validate(packet: Packet): void {
if (packet.getOriginator() === "MIA"
|| packet.getLength() > RSCWorkflow.MAX_LENGTH
|| !packet.hasValidCheckSum()) {
throw new InvalidFlowException();
@trikitrok
trikitrok / IntroduceInstanceDelegator2.ts
Created March 21, 2025 18:41
Alternative using Parameterize Constructor
// Alternative using Parameterize Constructor
export class User {
private readonly id: number;
private readonly bankingServices: BankingServices;
//!! We used Parameterize Constructor to inject a BankingServices instance to User
constructor(id: number, bankingServices: BankingServices) {
this.id = id;
this.bankingServices = bankingServices;
@trikitrok
trikitrok / IntroduceInstanceDelegator1.ts
Created March 21, 2025 18:38
Alternative using Parameterize Method
// Alternative using Parameterize Method
export class User {
private id: number;
constructor(id: number) {
this.id = id;
}
// more code...
// a utility class :(
export class BankingServices {
public static updateAccountBalance(userId: number, amount: Money): void {
// some code to update the account balance
}
// more methods...
}
export class User {
export class MessageRouter {
public route(message: Message): void {
//!! ouch... x(
ExternalRouter.getInstance().sendMessage(message);
}
}
export class ExternalRouter {
private static instance: ExternalRouter | null = null;
export class MessageRouter {
public route(message: Message): void {
//!! ouch... x(
ExternalRouter.getInstance().sendMessage(message);
}
}
export class ExternalRouter { // another Singleton! x(
private static instance: ExternalRouter | null = null;
// After applying Subclass & Override Method
class RegisterSale {
// more code...
public addItem(code: Barcode): void {
const newItem = this.getInventory().getItemForBarCode(code);
this.items.push(newItem);
}