Skip to content

Proposal: "Accept Interfaces, Return Concrete Types" #26

Open

Description

@zombiezen

Attribution (as best as I can tell): Jack Lindamood's article Preemptive Interface Anti-Pattern in Go

Activity

  1. invidian commented on Jun 24, 2022

    @invidian

    Superseded by #37 maybe?

  2. brackendawson commented on Jun 12, 2025

    @brackendawson

    Hands up if you've ever returned an error? ✋

    error is an interface type, possibly the most common return type, and yet it breaks this convention.

    I think "Accept what you need" is a better first half, by which I mean accept the minium that you need. Here's a basic example with a constructor:

    // New is bad because the caller has to have a file on disk but we don't actually need a file on disk.
    func New(fileName string) (Thing, error) {
        input, err := os.Open(fileName)
        if err != nil {
            return fmt.Errorf("error opening input file: %w", err)
        }
        return Thing{i: input}, nil
    }
    // New is better because input can be in memory, or go:embed.
    func New(input io.Reader) (Thing, error) {
        return Thing{i: input}, nil
    }
    
    // NewFromFile serves the original convenience
    func NewFromFile(fileName string) (Thing, error) {
        input, err := os.Open(fileName)
        if err != nil {
            return fmt.Errorf("error opening input file: %w", err)
        }
        return New(input)
    }

    This example does follow the convention, "Accept interfaces". But other examples exist with concrete types, like where you need a string vs []byte. The nugget of advice is to avoid things that look like conversion at the front of your function. "Accept only what you need"?

    The return case is harder, if you can only return one concrete type then you should definitely do that, but if you might return one of several types then you must return an interface. Maybe you're returning what the caller needs? That's harder to predict. I've not found a good pithy phrase for this when I teach Go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions