Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the convention with Java beans, and implementing interfaces like Comparable?

Java Beans, as far as I know, should always:

  1. Have only an empty constructor
  2. Have only fields, and getter/setter methods for these fields.

However, I am wondering what the convention is for Java beans to implement interfaces like Comparable? I could leave the java bean pure, meaning absolutely no behaviour, only data, and write a custom comparator-class. Implementing comparable is easier though.

Are there any conventions when it comes to implementing simple common interfaces like Comparable to Java Beans? I cannot find any consequences myself, but it feels like I might breaking some rules, and that there might be something I haven't thought of.

like image 272
jumps4fun Avatar asked Sep 30 '22 11:09

jumps4fun


1 Answers

IMHO this question is mostly not about conventions but about the needs.

You are right that separation of bean stuff from any business logic is a good style. I'd add here that this typically a good practice because relationship between your beans and comparators are many-to-many, i.e.

  1. You will probably hold several comparators for one bean class and use them in different contexts
  2. Sometimes you can re-use one comparator for several different classes or make hierarchy of comparators.

However you are right that writing comparison logic into class itself is less verbose and in some cases preferable. The choice completely depends on the author taste and requirements of the application he/she is working on.

like image 123
AlexR Avatar answered Oct 07 '22 19:10

AlexR