Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods which return values vs methods which directly set attributes in Python

Which of the following classes would demonstrate the best way to set an instance attribute? Should they be used interchangeably based on the situation?

class Eggs(object):

    def __init__(self):
        self.load_spam()

    def load_spam(self):
        # Lots of code here
        self.spam = 5

or

class Eggs(object):

    def __init__(self):
        self.spam = self.load_spam()

    def load_spam(self):
        # Lots of code here
        return 5
like image 288
D K Avatar asked Aug 22 '11 19:08

D K


1 Answers

I would prefer the second method.

Here's why: Procedures with side effects tend to introduce temporal coupling. Simply put, changing the order in which you execute these procedures might break your code. Returning values and passing them to other methods in need of them makes inter-method communication explicit and thus easier to reason about and hard to forget/get in the wrong order.

Also returning a value makes it easier to test your method. With a return value, you can treat the enclosing object as a black box and ignore the internals of the object, which is generally a good thing. It makes your test code more robust.

like image 157
Johannes Avatar answered Nov 15 '22 05:11

Johannes