Hacker News new | ask | show | jobs
by throwaway894345 1515 days ago
Yeah, I think very, very few problems (if any) are better-suited to being modeled with inheritance rather than composition. Go sort of forces you to think about composition, and once you get the hang of it I'd bet you won't go back. When you need reuse, reach for composition. When you need polymorphism, reach for interfaces/callbacks. When you need both (for example, a BookStore that works with both Postgres and SQLite backends) then you reach for both:

    type BookStoreBackend interface {
        GetBook(isbn string) (*Book, error)
        PutBook(*Book) error
        ListBooks() ([]*Book, error)
        DeleteBook(isbn string) error
    }

    // BookStore embeds (i.e., is composed of) a Backend, which is an
    // interface type.
    type BookStore struct {
        // ... other fields

        // Backend supports PostgresBookStoreBackend, SQLiteBookStoreBackend,
        // FileSystemBookStoreBackend, MemoryBookStoreBackend (for testing),
        // etc.
        Backend BookStoreBackend
    }