2 ms·
> But, having null checks here and there makes your code unreadable. if user is not None:
by okasaki 6y ago
> But, having null checks here and there makes your code unreadable.
if user is not None:
balance = user.get_balance()
if balance is not None:
balance_credit = balance.credit_amount()
if balance_credit is not None and balance_credit > 0:
can_buy_stuff = True
else:
can_buy_stuff = False
Actually I think that's very readable
user: Optional[User]
can_buy_stuff: Maybe[bool] = Maybe.from_value(user).map( # type hint is not required
lambda real_user: real_user.get_balance(),
).map(
lambda balance: balance.credit_amount(),
).map(
lambda balance_credit: balance_credit > 0,
)
Much better, isn't it?
No?!? That's much worse.
- cellularmitosis 6y agoYeah, I'd much rather read this: def can_buy_stuff(user): if user is None: return False balance = user.get_balance() if balance is None: return False balance_credit = balance.credit_amount() if balance_credit is None: return False return balance_credit > 0 Edit: something like Swift's optionals and nil-coalescing syntax might make this easier to read: def can_buy_stuff(user): return (user?.get_balance()?.credit_amount() ?? 0) > 0