lundi 23 novembre 2015

Should I pass the object in or build it in the constructor?

Perhaps this doesn't really matter, but I have a hunch I should 'pass in the object', but I'm not sure why.

Situation

I have some Record objects that are being created by reading a text file (e.g. a CSV file). One of the fields defines possible actions to perform on this record.

For example:

class Action:
    def __init__(self, create, update, delete):
        self.create = create
        self.update = update
        self.delete = delete

    @staticmethod
    def parse_from_string(actions):
        return Action('c' in actions, 'u' in actions, 'd' in actions)

Which of these two is better design?

class Record1:
    def __init__(self, actions_string, name, ...etc):
        self.action = Actions.parse_from_string(actions_string)
        ...

class Record2:
    def __init__(self, actions, name, ...etc):
        self.action = actions

With the difference in their use being:

action_string, name_string,... = read_details_from_file()

record1 = Record1(action_string, name_string, ...)

# vs.
actions_obj = Actions.parse_from_string(actions_string)
record2 = Record2(actions_obj, name_string, ... )

I think I am leaning to the second model, but I don't know why? Also, should I enforce that the object passed to the Record2 constructor is of the correct type?

Aucun commentaire:

Enregistrer un commentaire