Refactor without breaking API compatibility
Refactor without breaking API compatibility
Refactoring changes internal structure while preserving externally observable behavior. Keep exported names, signatures, promised error categories and documented semantics stable. Add characterization tests (tests capturing intended existing behavior) before changing implementation. An unchanged signature can still return different results.
package main
import ( "fmt" "strings")
func normalize(s string) string { return strings.ToLower(strings.TrimSpace(s)) }func Label(s string) string { return normalize(s) }func legacyLabel(s string) string { return strings.ToLower(strings.TrimSpace(s)) }func main() { for _, s := range []string{" TEA ", "", "Coffee"} { fmt.Printf("%t %q\n", Label(s) == legacyLabel(s), Label(s)) }}Label remains the public entry point and delegates to a new helper. This comparison checks representative inputs, including empty text, not all inputs. Preserve documentation and add tests for whitespace and Unicode behavior if callers depend on them. Do not silently change a public return type to simplify a new implementation.
Expected output:
true "tea"true ""true "coffee"Add a capability without widening an old interface
package main
import ( "fmt")
type Reader interface{ ReadName() string }type Named string
func (n Named) ReadName() string { return string(n) }func display(r Reader) string { return r.ReadName() }
type DetailedReader interface { Reader Detail() string}type Detailed struct{ Named }
func (d Detailed) Detail() string { return "detail" }func main() { fmt.Println(display(Named("old"))) fmt.Println(display(Detailed{Named("new")})) var d DetailedReader = Detailed{Named("new")} fmt.Println(d.Detail())}Adding a method to an existing public interface can break third-party implementations. A separate extended interface lets new consumers opt in without requiring all implementers to change. Adding a field to a public struct may break external unkeyed literals. If an incompatible library change is necessary, plan migration and an appropriate major version. The companion module tests an external consumer against both implementations.
Expected output:
oldnewdetailTry it locally
Keep a public function MilesToMeters(miles int) int using the documented educational approximation of 1609 meters per mile for 0 to 100 miles. Move multiplication to a private helper. Print results for 0, 1 and 3.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 07: Refactor without breaking API compatibility
Check the lesson objective before moving on.
Can an unchanged exported signature still break clients?
How can an optional capability be added without widening an old interface?