Created
January 14, 2022 20:15
-
-
Save AntonStoeckl/cf9a4cc39f24978efe3fe678b7c7b60f to your computer and use it in GitHub Desktop.
Example for blog post Go bits: Interfaces and Nil Pointers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package commandhandling | |
import ( | |
"errors" | |
) | |
var ErrCommandIsNilInterface = errors.New("command is nil interface") | |
var ErrCommandIsNilPointer = errors.New("command is nil pointer") | |
var ErrUnknownCommand = errors.New("unknown command received") | |
type CommandHandler struct{} | |
func NewCommandHandler() *CommandHandler { | |
return &CommandHandler{} | |
} | |
func (h *CommandHandler) Handle(command Command) error { | |
var err error | |
switch actual := command.(type) { | |
case *RegisterCustomer: | |
err = h.handleRegisterCustomer(actual) | |
case *ConfirmEmailAddress: | |
err = h.handleConfirmEmailAddress(actual) | |
case nil: | |
return ErrCommandIsNilInterface | |
default: | |
return ErrUnknownCommand | |
} | |
return err | |
} | |
func (h *CommandHandler) handleRegisterCustomer(command *RegisterCustomer) error { | |
if command == nil { | |
return ErrCommandIsNilPointer | |
} | |
// do something useful | |
_ = command.CommandType() | |
return nil | |
} | |
func (h *CommandHandler) handleConfirmEmailAddress(command *ConfirmEmailAddress) error { | |
if command == nil { | |
return ErrCommandIsNilPointer | |
} | |
// do something useful | |
_ = command.CommandType() | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment