what is polymorphism

tags: learning software programming go

content

Note

  • the word polymorphism means “many forms or shapes
  • we can think of it as: the underlying data object could have many shapes

Go interface is a good example:

type Animal interface {
	MakeNoise() string
}
 
type Cat struct {
	Name  string
	Breed string
}
func (c Cat) MakeNoise() string {
	return "meow"
}
 
type Fish struct {
	Name string
	Tail string
}
func (f Fish) MakeNoise() string {
	return "blueb"
}
// other code
func (z Zoo) WatchAminal (pet Animal) {
	animal.MakeNoise()
}
  • Cat and Fish both implement MakeNoise method, so they implements Animal interface implicitly
  • But they are different data structures or different objects:
    • one has Breed, the other has Tail
  • For the caller WatchAnimal
    • it doesn’t care about what the underlying data structure for pet is
    • it only cares if pet can MakeNoise
  • this is polymorphism!
    • the word polymorphism means many forms/shapes
    • in this case, we are using the same code to handle different objects!
    • the interface Animal has many forms/shapes

When we don’t need polymorphism:

type Agent struct {
	prompt        string
	tools         *tool.Tools
	hooks         *EventHooks
	maxIterations int
}
 
func (a *Agent) NewMainAgent() {
	tools
}
 
type SubAgent struct {...}
func (a *SubAgent) SystemPrompt() string {...}
func (a *SubAgent) GetTools() []Tool {...}
func (a *SubAgent) GetMaxTurn() int {...}

up

down

reference