Skip to content

Instantly share code, notes, and snippets.

@patrickbucher
Created January 30, 2021 08:48
Show Gist options
  • Save patrickbucher/bb389615d036330df50241467938169b to your computer and use it in GitHub Desktop.
Save patrickbucher/bb389615d036330df50241467938169b to your computer and use it in GitHub Desktop.
Object-Oriented Programming vs. Functional Programming: Trivial Example in Python
#!/usr/bin/env python3
# Object-Oriented Programming:
# - verbose
# - mutable state
class Rounding:
def __init__(self, granularity):
self._granularity = granularity
def roundTo(self, x):
return round(x * 1 / self._granularity) * self._granularity
# Functional Programming:
# - less code
# - no mutable state
def rounding(granularity):
def roundTo(x):
return round(x * 1 / granularity) * granularity
return roundTo
if __name__ == '__main__':
rounder = Rounding(0.05)
print(rounder.roundTo(1.06))
print(rounder.roundTo(1.02))
print(rounder.roundTo(0.99))
print(rounder.roundTo(0.92))
roundTo = rounding(0.05)
print(roundTo(1.06))
print(roundTo(1.02))
print(roundTo(0.99))
print(roundTo(0.92))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment