3 ms·
As soon as you start protecting yourself from the dangers of the unidentified dumbfool programmer, you get exactly this. In that case you can't do pretty much a
by yason 16y ago
As soon as you start protecting yourself from the dangers of the unidentified dumbfool programmer, you get exactly this. In that case you can't do pretty much anything without wrapping it around read only collections or iterators or accessors first, whereas what you really want is just to return a list of damn things.
Java seems to be the breeding pit for such practices: it's a supposedly secure virtual machine that allows you to hide stuff so deep in your rear end that you can barely access it yourself any longer without a delicate assessment of numerous design patterns. That sort of capability allows you to get on that encapsulation-road far enough that it might not be feasible to ever back down and rewrite things in a sensible way.
But the truth is, all you need is the array holding the important values and all you need to do is document the function appropriately. "Don't modify the returned list" would be a good start.
Then you want your developers have the skills to understand each part of that sentence. On the other hand, if someone won't it's not your problem since you documented the behaviour.
Some languages, such as C, allow you to tell that more explicitly with the 'const' keyword and even have the compiler act as a gatekeeper. The developer can still write the returned value into a non-const variable and mess around with that but he's already broken the contract by that time. In Java, it should be more than sufficient to cast it into a type denoting a read-only array or collection but I don't see a common, real reason to not eventually return that single array.
- Chris_Newton 16y ago> But the truth is, all you need is the array holding the important values and all you need to do is document the function appropriately. "Don't modify the returned list" would be a good start. I agree that over-engineering is both common and unhelpful in software development. On the other hand, I think you are too quick to dismiss encapsulation techniques. The sort of defensive programming tools you mentioned aren't there because dumb programmers don't know any better. They are there because smart programmers know that sometimes they will still make mistakes anyway. See also: failing to free dynamically allocated memory, failing to check return codes or handle exceptions, failing to exit a loop under the correct conditions, creating deadlocks in multithreaded code, etc.