Home > Article > Backend Development > Is the Fragile Base Class Issue a Myth in Go?
Go Language: Fragile Base Class Issue - A Myth Debunked?
In object-oriented programming, the fragile base class issue arises when inheriting classes are affected by changes made to the base class. This problem becomes particularly evident when the base class employs virtual methods.
Despite the prevalent use of composition over inheritance in Go, concerns linger about the possible existence of a fragile base class issue within the language. Let's delve deeper into this topic.
The Fragile Base Class Issue Explained
The fragility arises when a base class with virtual methods (overridable methods) is modified. This can potentially break inherited classes if the modified methods' behavior depends on the existence of virtual methods.
However, in Go, polymorphism is absent. When a type is embedded within a struct, its methods are promoted to the wrapper struct, but they cannot be overridden. This means that the original methods defined in the embedded type will always be called.
Demonstrations in Java and Go
To illustrate the fragile base class issue in Java, consider the following example:
<code class="java">class Counter { void inc() { value++; } void incBy(int n) { value += n; } } class MyCounter extends Counter { @Override void inc() { incBy(1); } }</code>
Changing the base class method to use a for loop for incremental increase (incBy(int n)) would cause MyCounter to malfunction due to an endless loop.
In contrast, in Go, the following equivalent code will not encounter the same issue:
<code class="go">type Counter struct { value int } func (c *Counter) Inc() { c.value++ } func (c *Counter) IncBy(n int) { c.value += n } type MyCounter struct { Counter } func (m *MyCounter) Inc() { m.IncBy(1) }</code>
Even if the base class method in Go were modified to the problematic for loop, the embedded type would not be affected as it calls the original method defined in the base class.
Conclusion
While the traditional fragile base class issue is a concern in languages like Java where virtual methods are present, it is largely mitigated in Go due to the absence of polymorphism. The absence of virtual methods ensures that embedded methods always invoke the original implementation defined in the base class, preventing the fragility issue associated with inheritance.
The above is the detailed content of Is the Fragile Base Class Issue a Myth in Go?. For more information, please follow other related articles on the PHP Chinese website!