Home  >  Article  >  Backend Development  >  How to Achieve Polymorphism in Go Without Inheritance: A Practical Example

How to Achieve Polymorphism in Go Without Inheritance: A Practical Example

DDD
DDDOriginal
2024-11-18 20:44:02502browse

How to Achieve Polymorphism in Go Without Inheritance: A Practical Example

Understanding Polymorphism in Go: Debunking Common Misconceptions

While polymorphism is a fundamental concept in object-oriented programming, it takes a different form in Go. Let's clarify the matter by addressing a specific issue related to implementing polymorphism in your code.

In Go, polymorphism is achieved through interfaces, which define a set of methods that a type must implement. Instead of using inheritance like in object-oriented languages, Go uses composition to create types with shared behaviors.

In your code, you're trying to create a "base" type BaseTX that contains common fields for different types of transactions. However, composition should be used instead of inheritance, so we'll create a Metadata struct that stores the shared fields:

type Metadata struct {
    Field1 string
    Field2 string
}

Our transaction types will then embed Metadata:

type RewardTX struct {
    Metadata 
}

type AllowanceTX struct {
    Metadata 
    AddField string
}

To perform common operations on these transaction types, we'll define a logicAndSaveTX method for Metadata that handles the shared logic:

func (tx Metadata) logicAndSaveTX() {
    // Logic on Metadata fields
    tx.Field1 = "overwritten"
    tx.Field2 = "logic done"
}

And then define custom logicAndSaveTX methods for RewardTX and AllowanceTX that extend the common behavior:

func (tx RewardTX) logicAndSaveTX() {
    // Call Metadata's logicAndSaveTX()
    tx.Metadata.logicAndSaveTX()

    // Additional logic unique to RewardTX
}

func (tx AllowanceTX) logicAndSaveTX() {
    // Call Metadata's logicAndSaveTX()
    tx.Metadata.logicAndSaveTX()

    // Additional logic unique to AllowanceTX
    tx.AddField = "more stuff"
}

By composing Metadata into transaction types and implementing specific methods for each type, we achieve the desired behavior without relying on inheritance or base classes. This is the "proper Go way" to handle polymorphism through interfaces and composition.

The above is the detailed content of How to Achieve Polymorphism in Go Without Inheritance: A Practical Example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn