Skip to content

Instantly share code, notes, and snippets.

@anapaulagomes
Last active March 26, 2019 15:13
Show Gist options
  • Save anapaulagomes/55067a80f776008ce761bd704d0726d4 to your computer and use it in GitHub Desktop.
Save anapaulagomes/55067a80f776008ce761bd704d0726d4 to your computer and use it in GitHub Desktop.
Code smell Temporal coupling example
class PrivateClassesView:
def post(self):
# code omitted for readability sake
data = {
'to': ['[email protected]'],
'body': 'blablabla',
'scheduled_for': datetime(2019, 3, 30, 11, 1, 0)
}
if subject:
data['subject'] = subject
email = Email.objects.create(**data) # database object
email.send() # has important logic on email flow
class GroupClassesView:
def post(self):
# code omitted for readability sake
data = {
'to': ['[email protected]'],
'body': 'blablabla',
}
if subject:
data['subject'] = subject
email = Email.objects.create(**data)
email.send()
class IntensiveClassesView:
def post(self):
# code omitted for readability sake
data = {
'to': ['[email protected]'],
'body': 'blablabla',
}
if subject:
data['subject'] = subject
email = Email.objects.create(**data)
email.send()
"""
Only this method would know the logic behind Email.
Consumers, like our views, shouldn't think about Email implementation details.
"""
def schedule_email(to, body, subject='My default subject', scheduled_for=None):
data = {
'to': ['[email protected]'],
'body': 'blablabla',
'subject': subject,
}
if scheduled_for is None:
data['scheduled_for'] = now()
email = Email.objects.create(**data)
email.send()
class PrivateClassesView:
def post(self):
# code omitted for readability sake
schedule_email(to, body, subject, scheduled_for)
class GroupClassesView:
def post(self):
# code omitted for readability sake
schedule_email(to, body, subject)
class IntensiveClassesView:
def post(self):
# code omitted for readability sake
schedule_email(to, body)
@jpaulorio
Copy link

I don't see the main point here being about getting rid of repetition though. Instead, my understanding is that her point is about encapsulating the logic of how to send an email or, to be more generic, how to make sure we're following the Single Responsibility Principle. The way I see it is that side effects to the main action of a given class/method should belong somewhere else. In her example, sending an email is a side effect of whatever the main classes are supposed to do, thus it's not the responsibility of those classes to know the steps required to send an email.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment