btbam91 btbam91 - 6 months ago 8x
Java Question

Is it conventional for Java Bean Classes to have more functionality than just getters/setters?

Quick background:

I am looking at refactoring one of my previous class projects as a fun exercise. The project was creating a Course Registration system and using .txt files as the database. As an exercise for myself, I've been learning how to work with SQL databases. From watching videos, I downloaded and installed MAMP where I am using Apache Server and mySQL database.

With that said, one of the requirements of the project was for the list of Courses to be displayed in alphabetical order. I had a class that implemented Comparable. I implemented compareTo(Course course) and that allowed me to call Collections.sort(coursesArrayList) on an ArrayList.

On initialization, my code did the following steps:

  1. Read in lines from a Course.txt database.

  2. Create Course objects and insert into an ArrayList

  3. Call Collections.sort() on the arraylist.


As I was learning about Java Beans in the videos and doing a little research online, it made me question whether it is "conventional" to implement Comparable and compareTo() in a Java Bean Class. If it is NOT conventional, how do you recommend going about sorting an ArrayList which consists of Java Beans?

Thanks for the help!


It would not be against the JavaBeans specification to implement Comparable in a JavaBeans class. (The spec requires a default constructor, getters and setters according to naming conventions, and being Serializable.)

However, I would not implement Comparable based on the title order just because your assignment included printing in that order. Most likely, a course will have an id, and sorting based on that might be just as desirable. Or the number of attendants.

But being a JavaBean, your Course can be sorted any old way just by

courses.sort( Comparator.comparing( Course::getTitle ) );          // by title
courses.sort( Comparator.comparing( Course::getAttendantCount ) ); // by attendant count

(This requires Java 8.)