Should you avoid Guavas Ordering.usingToString ()?

This question was asked after reading Joshua Bloch's Effective Java. In particular, in paragraph No. 10, he claims that it is bad practice to parse the representation of the object string and use it for anything other than friendly listing / debugging. The reason is that such use is "error prone, leading to fragile systems that break if you change the format." For me, this is similar to Guava Ordering.usingToString() - this is a place for an example of this. Is it a bad practice to use it?

+4
source share
4 answers

Well, if sorting is only used to determine in which order to display things for the user, I would call it part of a “friendlier listing / debugging”.

If, however, the correctness of your codes depends on the ordering, I would say that this is really a bad idea, depending on toString .

+8
source

As the author of this method, I would agree: this is really just a crutch. For these "views, I just need the cases Ordering<Object> , dammit". It should probably be removed, as you can get its behavior with Ordering.onResultOf(Functions.toStringFunction) anyway.

+3
source

If your program ever used toString() for lexical sorting, using the natural order so that the execution of the program depends on it, then it would be advisable to override the default value of the toString() class, which is extended. In this case, you must make the toString() method final and clearly document that it is used for ordering.

However, it would be much better to create another method that returns String , and create an order based on this result, possibly creating a specific Comparator for sorting. See For example, the last name() method used for enumerations in Java. In general, this creates the same string, toString() , but it is still possible to execute an order with it, even if toString() was canceled.

If you use the latter method, then Ordering.usingToString() will not be very useful.

+1
source

There are some obvious cases where it really makes sense, like StringBuffer, etc. Obviously, for most "business classes" it makes no sense to rely on toString ().

0
source

Source: https://habr.com/ru/post/1498802/


All Articles