Sobes.tech
Junior — Middle

Can you describe your experience applying the Chain of Responsibility pattern in real projects?

sobes.tech AI

Answer from AI

In one of my Go projects, I used the Chain of Responsibility pattern to handle HTTP requests with different levels of validation and authorization. Each handler in the chain checked a specific condition — for example, token validity, access rights, data format — and either processed the request or passed it further down the chain. This allowed for flexible addition of new checks without modifying existing code and improved readability.

A simplified implementation example:

package main
import "fmt"

type Handler interface {
    SetNext(handler Handler)
    Handle(request string)
}

type BaseHandler struct {
    next Handler
}

func (b *BaseHandler) SetNext(handler Handler) {
    b.next = handler
}

func (b *BaseHandler) Handle(request string) {
    if b.next != nil {
        b.next.Handle(request)
    }
}

type AuthHandler struct { BaseHandler }

func (h *AuthHandler) Handle(request string) {
    if request == "valid_token" {
        fmt.Println("Auth passed")
        h.BaseHandler.Handle(request)
    } else {
        fmt.Println("Auth failed")
    }
}

func main() {
    auth := &AuthHandler{}
    auth.SetNext(&BaseHandler{})

    auth.Handle("valid_token")  // Auth passed
    auth.Handle("invalid")      // Auth failed
}

This approach helps to separate responsibilities and simplifies maintenance.

Can you describe your experience applying the Chain… - sobes.tech