Last active
December 25, 2015 13:19
-
-
Save Fluxx/6982443 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
class Person(object): | |
pass | |
person = Person() | |
################################################################################ | |
# Procedural | |
if getattr(person, 'spouse') and person.spouse.birthday == datetime.today(): | |
print "Happy Procedural birthday to your Spouse!" | |
################################################################################ | |
# Duck-typing | |
try: | |
if person.spouse.birthday == datetime.today(): | |
print "Happy Duck-Typed birthday to your Spouse!" | |
except AttributeError: | |
pass # person does not have birthday | |
################################################################################ | |
# Null-Object | |
class NullObject(object): | |
# Imagine a class that returns more NullObjects for every method call and | |
# property access. | |
# | |
# http://en.wikipedia.org/wiki/Null_Object_pattern | |
pass | |
def maybe(value): | |
if value is None: | |
return NullObject() | |
else: | |
return value | |
if maybe(person.spouse).birthday == datetime.today(): | |
print "Happy Null Object birthday to your Spouse!" | |
################################################################################ | |
# Sensible defaults | |
# Ensure that a person.spouse is always SOMETHING, never None. | |
class Nobody(object): | |
birthday = None | |
class Person(object): | |
@property | |
def spouse(self): | |
if not self._spouse: | |
return Nobody() | |
else: | |
return self._spouse | |
if person.spouse.birthday == datetime.today(): | |
print "Happy Sensible Defaults birthday to your Spouse!" | |
################################################################################ | |
# Law of demeter | |
class Person(object): | |
# Add method to person to handle spouse birthday interface | |
def spouse_birthday(self): | |
if hasattr(self, 'spouse'): | |
return self.spouse.birthday | |
if person.spouse_birthday == datetime.today(): | |
print "Happy Law of Demeter birthday to your Spouse!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment