Skip to content

Instantly share code, notes, and snippets.

@jMyles
Last active August 29, 2015 14:21
Show Gist options
  • Save jMyles/56810d1dcdd545c725dc to your computer and use it in GitHub Desktop.
Save jMyles/56810d1dcdd545c725dc to your computer and use it in GitHub Desktop.
Literal / Expressive - more DRY?
# Which is more DRY..
# Option 1
x = 1
y = '1'
z = 1.0
# Or option 2
x = 1
y = str(x)
z = float(x)
# The answer is probably 'neither,' because these don't express the same logic.
# For example, in the case of the option 2 (less literal but more expressive)
# You may well have had something like this happen earlier in the program
str = int
float = long
# ...
x = 1
y = str(x)
z = float(x)
'''
Now, this may be DRY in the sense that it doesn't repeat the literal value of x
However, it is not, in any sense, a dehydrated version of option 1 because it expresses
completely different logic.
You might say, "Yeah, but who secretly overrides the type caster built-ins?"
And you're right; that's bad behavior.
However, a likely real-world situation is overriding the __str__ on a complex object.
In this case, you're back to the same question and the same answer.
'''
# So, the most reasonable way to explain which is more DRY to is say that
# Option 1 is the DRYest literal way to express the logic
# Option 2 is the DRYest expressive way to express the logic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment