samedi 25 novembre 2023

Creating a service layer with Django Rest Framework

I am fairly new to web-development and just studing design patterns and code architecture. Now, I am developing service layer for business logic. And here I have a dillema. One approach is to use command design pattern. Where I have a class which implements user creation and related processes (e.g. sending email, writting logs etc), also this class has one public method (entry point) and private methods, called inside the entry point. Here is the example of what I mean.

class CreateUser:
    def _create_user(self, **data) -> User:
        # here perform creation of user itself, requesting repository layer
        ...

    def _send_email(self, **data) -> None:
        # here I send email

    def _write_logs(self, **data) -> None:
        # writing logs to a file

    def execute(self, **data):
        self._create_user(**data)
        self._send_email(**data)
        self._write_logs(**data)

On the other hand, there is a approach where I create a common service as a class, that handles user authentication and registration and for each user action has one method:

class UserService:
    def create_user(self, **data) -> User:
        # call to repository
        # send email
        # write logs

    def update_user(self, **data) -> User:
        # call to repository
        # write logs

I don't really know what solution I should choose. I suppose that the command pattern is better, however I'm not sure about more complex scenarious. And throughout the project (or application), should I stuck to one design pattern (e.g. the command) or it's okay to alternate them? Maybe there are other approaches?

Sorry if my question seems silly, I am newbie and I feel lost among so much information (especially clean code patterns), so I am looking for help. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire