Fragile Base Class Issue in Go?
Despite embracing composition over inheritance, concerns have been raised whether Go still faces the "fragile base class" issue. This article investigates this topic and explores potential solutions at the language level.
The Fragile Base Class Problem
In classical object-oriented programming, the fragile base class problem arises when a modification to a base class breaks subclasses that rely on its methods. This occurs due to virtual method overriding, where the actual method implementation is determined at runtime.
Composition in Go: Does It Mitigate the Issue?
Go employs composition instead of inheritance, but provides an embedding mechanism that includes the methods of the embedded type in the embedding type. However, method overriding is not supported in Go. All methods of the embedded type are promoted and remain in the embedding type's method set.
Go's Exemption: An Example
To illustrate the difference between Go and languages that face the fragile base class issue, consider the following example:
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) }
In Java
Java's support for method overriding creates the potential for the fragile base class issue. If the Counter.IncBy() method were modified to:
void incBy(int n) { for (; n > 0; n--) { inc(); } }
MyCounter would become unusable due to an endless loop as MyCounter.Inc() calls Counter.IncBy(), resulting in a recursive invocation.
In Go
In Go, the same modification to Counter.IncBy() does not lead to the same problem. MyCounter.Inc() still calls Counter.Inc(), which in turn calls Counter.IncBy(), but this does not create a loop since Counter's Inc() function is being invoked, not MyCounter's. Counter does not have a reference to MyCounter, maintaining its independence.
Conclusion
While Go's composition mechanism and lack of method overriding mitigate the fragile base class issue to a significant extent, it's important to note that it's not entirely eliminated.
The above is the detailed content of Does Go\'s Composition Approach Completely Eliminate the Fragile Base Class Problem?. For more information, please follow other related articles on the PHP Chinese website!