4 ms·
I don't program much Java, but how expensive are exceptions? Wouldn't it make more sense to expect functions that could return null to instead throw a checked
by matteotom 11y ago
I don't program much Java, but how expensive are exceptions? Wouldn't it make more sense to expect functions that could return null to instead throw a checked exception if something goes wrong?
eg
public dbResult doDatabaseThing(stuff) throws DatabaseException
So if you do
result = doDatabaseThing(stuff)
the compiler will require you to do something about the DatabaseException.
It seems to me that the point of, for example, Option and Result in Rust is to avoid the whole checked exception mess while still passing useful information about things that go wrong. But, given the problems pointed out in this article (lack of pattern matching and algebraic data types mostly), checked exceptions might be a more correct way to do it in Java.
- tel 11y agoAnd of course checked exceptions (wrapped in a try block) are "just" the nomadic effect of the option (or "result") type.
- alkonaut 11y agoYes. In this case the No-result means that the database query was successful, but no record was found. A connection error etc. should almost certainly still be thrown as an exception in Java. Without exceptions you would have to return a value that could discriminate between all 3 possible outcomes: nothing, error, result. In Rust this is the `Result<T, E>` struct.
- matteotom 11y agoIt that case, wouldn't it be better to return something other that `null` for no-result (an empty iterator? an empty list?)? That might be where Optional comes in, but I'm still not sure why a new language feature is needed for that.
- asdfaoeu 11y agoGenerally I would think optional values are not indicating errors but to indicate an absence of something. A null database result would be the item was not found rather than an issue communicating with the database. Moving that to try / catch error would increase the possibility that another unexpected operation is inadvertantly caught. Somewhat similar examples can be found for Result but I do conced you have a better case.