Passing in private attributes into a utility function

29 Views Asked by At

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:

  1. Define merge_util as a method of each class, but then I'd be duplicating code for each class.

  2. 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?

1

There are 1 best solutions below

7
smwh On

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.

class Merger:
    def __init__(self):
       # some settings here
    
    def merge_util(self, src, dest):
       # your logic

class FirstClass:
  def __init__(self, ...):
    self.merger = Merger()
    # and so on

you can instantiate it inside or pass from outside to support modularity.