I have an (android) application and decided that the presentation layer will get data only through strict interfaces from the controller. I am at the point where some basic objects need to be passed to the presentation layer, but the objects itself must be in strict read-only mode, because all changes will be handled by the controller.
To make a simple example, imagine a ToDo-App, where the screen needs to display a list of todo items.
The Todo-Item has the fields "title" and "content" with respective getters and setters. Even if I pass an unmodifiable list, the objects in it can be changed. I can think of these alternatives:
- put controller and data in one package and make the setters protected.
- add an interface to the todo item containing only the getters and passing these objects.
- add an interface only to the controller and put all getters there.
for 1)
public class TodoItem {
private String title; private String content;
public String getTitle() ...
protected String setTitle(..) ...
}
for 2)
public interface ITodoItem {
public String getTitle();
}
public class TodoItem implements ITodoItem {
private String title; private String content;
@Override
public String getTitle() ...
public String setTitle(..) ...
}
I wonder now what is the more common, smarter etc. option (or are there more?) and what are the arguments?
Alternative 1) for my feeling depends to much on the fact, that the items have to be in the same package making it to difficult to expand the program.
Alternative 2) looks odd to me, because all tiny objects would now become an interface with the getter methods. I am using it and technically I am satisfied (as it prevents me from accidantally changing an object). However, it is not immutable, as the object may be cast back to ToDo-Item and then the original is changed. So this is not good for public apis. Do I really have to clone every object if I want immutability?
Alternative 3) gets messy quick because one controller would then contain all the getters of the tiny objects. This does not comply to "let the object do the work".
What are your experiences and thoughts on this?