Can anyone shed light on why you would want to return an immutable list (or map, or set)?
Just spent the afternoon working on a legacy system that had some sweet logic like:
Which, years later, was used like:
And everything worked until BarImpl's constructor got passed an null. Of course, there were a bunch more layers between the constructor call and the attempt to add to the immutable List.
As I contemplate replacing a bunch of emptyList() with ArrayList<>() so that no one can accidentally add to an immutable List I'm left to wonder when does it make sense to create an immutable List and how would you stop future users of your class from making the same mistake as above?
You use immutable list when you don't want the list to be modified.
This is really bad. You should not expose the internals of your class like this.
With this code it is very easy to violate invariants of your class. Try this:Now you have an Integer in your list!
If you need to add messages to the list then create a method in Bar to handle this.
If you need to get the list, return a safe copy so it won't get modified.
Make a copy of the list in the constructor. It helps in two ways. One, there won't be any reference to the list outside of the class. Two, you'll be sure the list is mutable.
You shouldn't accept nulls in the constructor in the first place.
Another thing is that method doesn't return null. If you have no List to have anything in, return an empty List. Returning null will produce problems if the user tries to iterate the List or anything like that. In fact almost any use of that List can produce a null pointer exception.