Android – Should UI and Logic Be in Separate Classes?

androidclass-designjunitui

I currently work on a hobby project which I use to learn more about Android/Java programming and programming in general. Recently, I decided to integrate jUnit into the project. Just getting it in there wasn't much of a problem, but actually using it was. I've read that a unit test should be the definition of what a method (or component) is supposed to do, and that unit tests force you to write good, or at least better code.

But the problems started occurring the moment I wrote the first unit test to test some logic. The method I wanted to test does only logical work, nothing with the UI is done and the results are simply saved in variables for later use. But, in the same class, I have a method to display whatever the first method has worked out. And jUnit doesn't seem to like that; for the second method I need (of course) UI imports, and jUnit complains that it doesn't know any "Android Context class". Until now, I thought that putting the logical and UI parts of a component in one class but seperated methods would be easily understandable and an acceptable practice. But now, because "jUnit forces you to write good code", I'm much less sure about this.

So, should I put the UI and logical parts for one component in seperate classes? They depend on each other, the UI method needs the values from the logical method, but the logical method can't do anything with its computed values without the UI method. But because someone else might think different about this… And that "someone else" is the one who probably has to understand my code somedays afterall.

Best Answer

UI design patterns like Model-View-Controller, Model-View-Presenter and Model-View-ViewModel routinely provide mechanisms (i.e. separate classes) that allow Separation of Concerns between the surface of the UI and the class that manages it, for the same reasons that you've already cited.

Related Topic