def get_cached_user_by_id(id):
user = cache.get_user_by_id(id)
if not user:
user = db.get_user_by_id(id)
cache.set_user(user)
return user
def get_cached_user_by_username(username):
user = cache.get_user_by_username(username)
if not user:
user = db.get_user_by_username(username)
cache.set_user(user)
return user
def get_cached_user(user_id = None, username = None):
user = None
if user_id:
user = get_cached_user_by_id(user_id)
else if username:
user = get_cached_user_by_username(username)
if not user:
raise ValueError('User not found')
return user
(Thanks for the .__name__ tip... I have not use python for a while) def cache(function_to_cache):
'''
A Decorator that caches a function result
'''
def wrapper(param):
cache_key = function_to_cache.name + " on " + param
if cache.contains(cache_key):
return cache.get(cache_key)
else
value = function_to_cache(param)
cache.set(cache_key, value)
return value
return wrapper
@cache
def get_cached_user_by_id(id):
return db.get_user_by_id(id)
@cache
def get_cached_user_by_username(username):
return db.get_user_by_username(username)
def get_cached_user(user_id = None, username = None):
user = None
if user_id:
user = get_cached_user_by_id(user_id)
else if username:
user = get_cached_user_by_username(username)
if not user:
raise ValueError('User not found')
return user
Inheritance is a form of code reuse in OOP. Composition is another one which is often preferred since it does not have the issues you mention here.
Note that just a couple of days ago this was posted on HN: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay... It's the definition that basically the inventor of Object Oriented Programming gave of OOP itself. One of the nice things he says is that he left out inheritance on purpose because he "didn't like it" the way it was done and wanted to "understand it better".
Regardless, I think your advice of learning other programming paradigms is great.