3 ms·
So, can anyone explain to me how this: Database.readOrder() .map(OrderEngine::process) .filter(ProcessResult::succeeded) .ifPresent
by breakingcups 10y ago
So, can anyone explain to me how this:
Database.readOrder()
.map(OrderEngine::process)
.filter(ProcessResult::succeeded)
.ifPresent(Database::storeResult);
Is more readable than the supposed "unpleasant old skool":
Order order = Database.readOrder(); //can be null
if(order != null) {
ProcessResult result = OrderEngine.process(order);
if(result != null && result.succeeded()) {
Database.storeResult(result);
}
}
Maybe I'm "old skool" but I find the second much easier to read than the first.
- cytzol 10y agoYou're right, actually -- it's not more readable. Java developers already understand nulls, comparisons, and if statements. However, the second version is a lot more brittle than the first. It's relatively easy to change the code and still get it to compile, whereas you'll have a lot more trouble doing that with the first. For example: 1. If you forget to check 'order' for null, it'll still compile fine, because null is a valid value for type 'Order'. But if you try to feed an Optional<Order> to OrderEngine, it won't compile. 2. If you forget to check 'result' for null, it'll still compile fine, and then throw an NPE when you run 'result.succeeded()'. Again, if you try to call check ProcessResult::succeeded in the first example, it won't compile unless you deal with the empty-result case specifically. 3. Say that later on you want to get your stored values back out of the database... and you find a null in there. Where did it come from? If you forget to check 'result' for null and don't do the 'succeeded()' check, you can put a null in the database. Then your program will work fine until you try to call a method on it, at which point it throws an NPE far, far away from the point where you store it. By using Optional and dealing with the empty case, your code won't compile if you try to store null in the DB. So unfortunately it will be less readable until Java devs adjust themselves to using this new type, but the benefits do exist.
- reitanqild 10y agoI agree but admit it might be down to my lack of experience with functional programming. Background: many moons ago when I was still in school and VB was a valid choice of programming language I thought I new object oriented programming since my VB skills was decent (for a student) and VB had objects. I have learned a lot since then and suspect something similar is happening and will happily admit that good stuff can be waiting for me as soon as it "clicks" when I get time to sit down with it or get a colleague who knows it and explain it (or when someone on HN gives me a good explanation : )