Saturday, April 28, 2012

Re: keep models simple ? where to put the business logic ?

First of all, I think your function is too big if it is doing all of these things. Are you able to unit test the function?

In my view, the logic for extract should not be in the model. I would create a class specifically for data extractions. I am assuming that the _store does not DB saves to the Feed model, so that logic should not be inside Feed. A model should only perform operations on its own model. If you want to do operations on 2 different models, then have a helper function to do so or put it in the manager of the model, not the model itself.

In your case, since the data is stored in 2 different storages, I would put the logic in a helper class inside helpers.py.
# helpers.py
class Feeder(object):
def store(data):
#  logix for storing to DB and any other storage.

@classmethod
def extract(cls, url, etag):
try:
#sub-logic here
return data, etag
except (.., ..) as ex:
# handle exceptions

@staticmethod
def extract_feed(feed)
data, etag = Feeder.extract(feed.url, feel.etag)
feed.update_etag(etag)

# models.py
class Feed():
def update_etag(self, etag):
if self.etag != etag:
self.etag = etag
self.save()

I strive for modular code and put business logic in its own classes. I unit test each code, so smaller the function, easier to test it and it is much more easier to use the code. In the above code, you could test it Feeder class without having a Feed model. As a side benefit, by having logic be independent of a specific model, you are able to much more easily use same piece of code for multiple purposes. i.e If you wanted to allow extracting for a specific url and etag from a VIEW or a specific feed from a view, you would be able to do both.

Overall, it comes down to what makes sense to you. Once you accept a certain way of coding, it is meant to PREVENT YOU from doing guess work as to where you placed a specific logic. So when a bug happens and need to find the code, you are not opening/closing files to find the logic, you know where you put the logic.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/r9aBzSOftAMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment