toString() and MVC

1362 views java

The API documentation for toString() states:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

(emphasis mine)

With that in mind, I wrote a toString() for a Building type class that was essentially (some implementation stripped)

public String toString(){
Stringbuilder sb = new StringBuilder("<p>");
sb.append (this.getDesc());
sb.append ("which contains: <br> <ul>"); 
for (Room r: this.getRooms()){
return sb.toString();

Giving something like:

A self contained student flat which contains:

  • A basic study
  • A basic living area
  • A basic bathroom
  • A basic bedroom

I think this is a "concise but informative representation that is easy for a person to read" but it seems to fly in the face of MVC as I understand it. The Building and Room class are both in the Model and surely that sort of output formatting belongs in the view?

I'm not certain whether I'm overthinking this, whether the Java API isn't written with MVC in mind or whether there's something I haven't understood. Can presentation matters go in the toString()? Would I be better having a seperate displayBuilding() or similar?

answered question

You could theoretically also use typeclasses and provide an implementation for the Show typeclass

2 Answers


toString() is mostly used as a tool in java world for debugging or displaying data in the log.

For the purpose mentioned by you, it is very much clear that toString() is definitely not the tool.

You should be very specific on the data that has to be displayed in the view and may be use a different model all together and then set values in that from the Building model and then send that model to UI.

posted this

You are using toString() to produce HTML code for your view. This is not the intended use of the toString() method. I think, it is mainly intended to produce debugging information e.g. for use in logfiles or in the debugger. This is meant by "easy for a person to read". HTML is a more technical representation for being included in the webpage. The name of such a method would rather be something like render().

posted this

Have an answer?


Please login first before posting an answer.