Question about If/else/switch in Clean Architecture

Viewed 74

I was reading Uncle Bob's blog, especially his article on if-else-switch. I wanted to go deeper to know if I understood what he means.

Let's imagine that I have a web app with Users, I want to display User's profil depending his sex. Some would simply do :

if(user.sex == 'female') return renderFemaleProfil(user)
if(user.sex == 'male') return renderMaleProfil(user)
return renderUnknownSexProfilError()

But to respect Clean Architecture Robert C Martin recommend to do DIP : enter image description here

If I clearly understood : I need an interface User. To create a fabric that return a polymorphic object Implementing User based on User's sex (class Male and class Female) as User

Done that, how do I display my profil ? I put a renderProfil() function in both classes that return a html string ? And just do user.renderProfil() ?

And what if I just have a single part that is different in the Male and Female profils ? Do I create renderPart1(), renderPart2() and renderPart3Male() for Male class and renderPart3Female() for Female class ? And call them in a single function renderProfil() ?

And is it worth it ?

Thank to enlighten me on those points :)

1 Answers

I guess your User is an clean architechture entity. Keep these entites clean from details like html rendering. Rendering a user to html is a detail. Thus you should either create a UserRenderer and pass it a User. E.g.

interface UserRenderer {
    String render(User user);
}

You can then implement an HTMLUserRenderer or an JSONUserRenderer or whatever renderer you like.

Either the UserRenderer can do the if/then/else

String render(User user){
  if(user.sex == 'female') return renderFemaleProfil(user)
  if(user.sex == 'male') return renderMaleProfil(user)
  return renderUnknownSexProfilError()
}

or you can implement a UserRendererFactory or UserRendererRegistry that will return an appropriate renderer.

These renderers belong to the outer circle of the clean architecture. So the dependency rule from the outer circle to the inner ones is honored. But you bypass the use case layer.

Maybe it would be better to introduce use cases and response models and let the renderer use the response model.

If you now go a little bit further you will recognize that a presenter is a more general renderer. Maybe the presenter uses renderers.

Related