I have 3 classes with a merge operation that does identical operations with different arguments.
Here's the skeleton code of what I currently do:
class FirstClass:
def __init__(self):
# define constructor
def merge(self, other):
# merge other into self
merge_util(src=other, dest=self)
class SecondClass:
def __init__(self):
# define constructor
def merge(self, other):
# merge other into self
merge_util(src=other, dest=self)
# ThirdClass defined identically
merge_util is defined as follows:
def merge_util(src, dest):
# merge src's private attributes (an array, list, and database table) into dest
The problem is this design seems to violate encapsulation. An external function is accessing private/protected attributes.
I've thought of 2 solutions:
Define
merge_utilas a method of each class, but then I'd be duplicating code for each class.Use inheritance. These classes have few similarities otherwise hence why I didn't use inheritance from the beginning and want to avoid this.
Are there other approaches I can consider?
what about composition?
define some kind of Merger with merge_util and pass it to your classes' constructors. calling it from inside a class won't violate encapsulation since your private attrs won't flow away to external function but internal Merger instance.
you can instantiate it inside or pass from outside to support modularity.