I'm wondering how to choose between those "patterns" - please forgive me if I don't use the right terms - when having to deal with complex object coming from the front I want to process.
Simple Beans
Simple beans means the separation between data structures and logic, like this:
class Post(val title: String, val content: String)
class CreatePost(private val repository: Repository) {
fun invoke(post: Post) = repository.savePost(title = post.title, content = post.content)
}
Functional beans
Beans that also have functions that can execute logic,
class Post(private val title: String, private val content: String) {
fun save(repository: Repository) = repository.savePost(title = title, content = content)
}
class CreatePost(private val repository: Repository) {
fun invoke(post: Post) = post.save(repository)
}
On the one hand, the first approach is simpler, but the second one offers a few advantages:
- decoupling between Post and CreatePost. CreatePost does not have to know the internal of a Post, only that it offers a save function. Post has more control over its internals and use cases.
- thus it is easy to add a new member to Post and CreatePost will not have to be updated. it makes it less likely to forget to update the save function in those cases.
On the other hand:
- the flow of the code is more convoluted.
- the use case naming convention seems less relevant, since CreatePost does not actually do any logic and just calls another function
- there is no separation of concerns.
As an alternative I can see this approach :
class CreatePost(private val title: String, private val content: String) {
fun invoke(repository: Repository) = repository.savePost(title = title, content = content)
}
And my controller would just call invoke :
@RestController
class CreatePostResource(private val repository: Repository) {
@PostMapping
fun createPost(createPost: CreatePost) = createPost.invoke(repository)
}
This seems like the most relevant approach, but are there any downsides to it? I assume I must not be the first one to ask myself those kind of questions.