3 ms·
> When a function receives an object, this object might be null. That is, if you see ‘String s’ in your code, you often have no way of knowing whether ‘s’ conta
by commandlinefan 4y ago
> When a function receives an object, this object might be null. That is, if you see ‘String s’ in your code, you often have no way of knowing whether ‘s’ contains an actually String unless you check at runtime. Can you guess whether programmers always check
Actually, my experience is the opposite - they check like hell, all over the place, reflexively, because a null pointer exception is a blaring emergency that has to be fixed RIGHT NOW, so I always see Java code written like this:
if (customer != null && customer.getOrder() != null && customer.getOrder().getLineItemList() != null) {
for (LineItem item : customer.getOrder().getLineItemList()) {
if (item.getProduct() != null && item.getProduct().getPrice() != null && item.getProduct().getPrice().getCurrency() != null) {
...
} // else don't do anything, don't even log an error, just continue on as if an empty product or price object is an ignorable error and create a much harder to diagnose problem than a null pointer exception
- oweiler 4y agoThere is so much wrong with this code...
- commandlinefan 4y agoAnd I've given up arguing with (the 99% of) Java programmers that code this way. They code this way, I shrug my shoulders and deal with it.
- Jenkins2000 4y agoMy solution is to convert to Kotlin, I can't stand working on Java anymore: customer?.order?.lineItemList?.forEach { item -> val currency = item?.product?.price?.currency
- commandlinefan 4y agoIf I'm understanding this correctly, it's still a problem: if the product's price element or the order's line item list is null, for example, that shouldn't just be silently ignored. The transaction should fail, loudly and visibly (like with an exception) so that the root cause of the invalid data can be examined. The way most programmers code it is to just ignore the bad data and potentially ship an item for free, or without charging tax, or charge the customer but not ship the item, etc. etc. This is why so many software development organizations have huge QA departments.
- Jenkins2000 4y agoI still write null checks if needed but for deeply nested objects, it comes down to only checking for null at the end of the chain instead of in Java where you have null checks each step of the way.
- oweiler 4y agoYou can chain Optional exactly the same as Kotlin but without the syntay suger ofc.