Why does the Db operations return an unmodifiable list?

24 views
Skip to first unread message

Thomas Hallgren

unread,
Mar 29, 2012, 11:07:16 AM3/29/12
to web4j-users
I tried to sort a list returned by a Db.list() operation and was
surprised to see that the list was unmodifiable. Why is that? It's a
private copy anyway and modifying it will not cause any harm. Now I
must instead copy the list before I sort it (the sort algorithm is
written in Java and not easy to mimic in SQL).

John O'Hanley

unread,
Mar 29, 2012, 5:32:55 PM3/29/12
to web4j...@googlegroups.com
It's unmodifiable simply as a defensive measure. That's all. The sort order is important, and is almost always done in the SQL's where-clause.

 - John

Thomas Hallgren

unread,
Mar 29, 2012, 11:38:45 PM3/29/12
to web4j...@googlegroups.com
I'm all for defensive measures, but what is it that this defends against?

John O'Hanley

unread,
Mar 31, 2012, 3:09:07 PM3/31/12
to web4j...@googlegroups.com
It defends against inadvertently changing its state.

It just returns the list in an immutable form. Immutables have many benefits (see Effective Java for more details). Many of the classes in web4j are immutable.

Changing the returned list to a mutable form is a one-liner, something like:
List<Thing> newList = new ArrayList<Thing>(oldList);

- John

Thomas Hallgren

unread,
Mar 31, 2012, 4:36:59 PM3/31/12
to web4j...@googlegroups.com
I'm doing exactly that, but even if it's one single line of code, it does waste both memory and CPU cycles. I'd like to
have a valid reason for doing that.

As I wrote before, I'm all for defensive measures when it has significance. In this case, the preservation of the
'state' of the returned list is completely insignificant nobody else is watching it. The method returns a private list.

- thomas

> --
> You received this message because you are subscribed to the Google Groups "web4j-users" group.
> To view this discussion on the web visit https://groups.google.com/d/msg/web4j-users/-/wtn4-DHIlAgJ.
> To post to this group, send email to web4j...@googlegroups.com.
> To unsubscribe from this group, send email to web4j-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/web4j-users?hl=en.

Reply all
Reply to author
Forward
0 new messages