samedi 13 août 2022

Should an entity or service be responsible for making API calls?

Let's assume that we are creating a program that interacts with some API. I see two approaches here, but I can't figure out which one is better.

1st approach: entities are making requests to API

type User struct {
    SomeUserId int
    SomeUserToken string
}

func (user *User) UpdateNickname(newNickname string) {
    call_api(...)
}

User{Id: 1, token: "abc"}.UpdateNickname("a")
User{Id: 2, token: "edf"}.UpdateNickname("b")

2nd approach: we have a service that makes these requests

type UserService struct {
    ...
}

func (service *UserService) UpdateNickname(user User, newNickname string) {
    call_api(...)
}

service.UpdateNickname(user1, "a")
service.UpdateNickname(user2, "b")

I guess that the second one is better, assuming that the "entity" is only for keeping some references to the entity that it actually holds, but I do not know how it actually should be. Hope to get an explanation for this.

Aucun commentaire:

Enregistrer un commentaire