Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String vs. A new Data class

Tags:

java

types

I overheard two of my colleagues arguing about whether or not to create a new data model class which only contains one string field and a setter and a getter for it. A program will then create a few objects of the class and put them in an array list. The guy who is storing them argue that there should be a new type while the guy who is getting the data said there is not point going through all this trouble while you can simple store string.

Personally I prefer creating a new type so we know what's being stored in the array list, but I don't have strong arguments to persuade the 'getting' data guy. Do you?

Sarah

like image 990
sarahTheButterFly Avatar asked Jun 29 '10 23:06

sarahTheButterFly


1 Answers

... a new data model class which only contains one string field and a setter and a getter for it.

If it was just a getter, then it is not possible to say in general whether a String or a custom class is better. It depends on things like:

  • consistency with the rest of your data model,
  • anticipating whether you might want to change the representation,
  • anticipating whether you might want to implement validation when creating an instance, add helper methods, etc,
  • implications for memory usage or persistence (if they are even relevant).

(Personally, I would be inclined to use a plain String by default, and only use a custom class if for example, I knew that it was likely that a future representation change / refinement would be needed. In most situations, it is not a huge problem to change a String into custom class later ... if the need arises.)

However, the fact that there is proposed to be a setter for the field changes things significantly. Instances of the class will be mutable, where instances of String are not. On the one hand this could possibly be useful; e.g. where you actually need mutability. On the other hand, mutability would make the class somewhat risky for use in certain contexts; e.g. in sets and as keys in maps. And in other contexts you may need to copy the instances. (This would be unnecessary for an immutable wrapper class or a bare String.)

(The simple answer is to get rid of the setter, unless you really need it.)

There is also the issue that the semantics of equals will be different for a String and a custom wrapper. You may therefore need to override equals and hashCode to get a more intuitive semantic in the custom wrapper case. (And that relates back to the issue of a setter, and use of the class in collections.)

like image 135
Stephen C Avatar answered Sep 23 '22 16:09

Stephen C