Software Design/Extract Wrapper Object
Appearance
Extract Wrapper Object is a refactoring primarily aiming at removing logic duplication in the code as per DRY principle. Extract Wrapper Object is related to Extract Class and Introduce Parameter Object refactorings.
Examples
[edit | edit source]If there is some code working with coordinates x
and y
and repeatedly performing operations such as negation:
x = -x
y = -y
The coordinates could be grouped into a Point
object on which negate()
function can be defined:
data class Point(var x: Double, var y: Double) {
fun negate() {
x = -x
y = -y
}
}
For another example, there may be a class with several operations and in some cases some aspect should be attached to calling those operations, such as logging or notifying some listener:
class Container {
fun add(elem: Element) { ... }
fun remove(elem: Element) { ... }
}
// Code repeated in multiple places within some other class:
container.add(elem)
listener.notifyAdded(elem)
// ...
container.remove(elem)
listener.notifyRemoved(elem)
Then a decorator class such as ListeneableContainer
can be extracted to gather the repetition of the aspect's logic in one place:
class ListeneableContainer(val container: Container, val listener: Listener) {
fun add(elem: Element) {
container.add(elem)
listener.notifyAdded(elem)
}
fun remove(elem: Element) {
container.remove(elem)
listener.notifyRemoved(elem)
}
}
Why not
[edit | edit source]Related refactorings and practices
[edit | edit source]Sources
[edit | edit source]- Refactoring: Improving the Design of Existing Code (2 ed.). 2018. ISBN 978-0134757599. https://martinfowler.com/books/refactoring.html. Chapter 3, "Data Clumps" section