| Unmodifiable-Pattern |
Page 1 of 4
The Unmodifiable-PatternBackground:Java rather offers unmodifiable lists but their handling is very tricky. They are implemented by overriding the command operations so that each raises an exception. Thus they appear to be traps in which programmers can easily fall. Therefore the Java solution is very inconvenient. Example for a tricky situation:
Explaination to that example: This simple program creates an empty ArrayList object for strings labeled with the name "strings". Then it is wrapped into an unmodifiable list. The returned listobjects still implements the list interface so that it still offers the command operations like "add(String element)". Howeverthe add-method now raises an exception of the type java.lang.UnsupportedOperationException instead of adding the passed element to the list. Thus the execution of that sample program throws the exception as well. Output of that example:Exception in thread "main" java.lang.UnsupportedOperationException What is the problem of that "solution"? The ugly thing on that solution is the fact that "something is offered which cannot be delivered" relatively "operations are offered which cannot have a sensible implementation". The offer of the capability of calling these operations resembles appears to be a trap for programmers who do not know that the operations throw exceptions. When lists are sequentially passed over several calls, the danger especially increases that programmers forget or oversee that they try to change an unmodifable list. What is the root of the problem? The root of the problem is mixing query and command operations in the collection interface instead of distinguishing between them and putting them to separate interfaces. |
||||||||
| Last Updated on Saturday, 11 June 2011 16:57 |

