DEV Community


Discussion on: Factory Pattern 🏭

rafaacioly profile image
Rafael Acioly

Nice post Shubam, but there's some problems with this implementation;

  • You cannot use Dog literal (type Dog) as type Pet in return argument, your interface Pet expect getAge method to return a string and you'r returning a int on your pet struct.

possible solution:

Change the interface to return a int on getAge or make your pet string return a string

  • The parameter type is wrong on your GetPet method because type is a keyword on golang

  • The method GetPet will fail if the "type" parameter is not "dog" or "cat", someone could pass "bird" to it.

possible solution:

func GetPet(kind string) (Pet, error) {
    availablePets := map[string]Pet{
        "cat": &Cat{},
        "dog": &Dog{},

    if pet, exist := availablePets[kind]; exist {
        return pet, nil

    return nil, fmt.Errorf("there's no pet type \"%s\" available", kind)
shubhamzanwar profile image
Shubham Zanwar Author

Ah, good catch! You're right about the type on the interface and the type keyword as an argument. Making the changes :D