You don't need to make an interface for everything. Everything doesn't have to be private. Write code that doesn't allow for or tolerate nulls and stop checking for them all the time.
Doing this is worse than just doing a simple null check, because it's more verbose and you're new'ing up a wrapper object just to immediately unwrap it again. The Optional class has a whole declarative api that you can safely code against, transforming the value within the pipeline and providing default values:
Yes, it's a really blatant example, but just to belabor the point, I'd go so far as to say if you're calling Optional.get() at all, you're probably doing it wrong.
You probably don't ever want to be referencing an Optional object in your calling method. In other words, you shouldn't really ever need to instantiate a variable of type Optional:
Optional<List<Customer>> optCustomers = // Stop here! Don't do this!
customerApi.getAllCustomersByState("CA");
List<String> customerIds = new ArrayList();
if (optCustomers.isPresent()) {
List<Customer> custList = optCustomers.get();
for (Customer cust : custList) {
customerIds.add(cust.getId());
}
}
return customerIds;
Not only is this forcing the declarative Optional api into an imperative pattern, it also ignores the declarative capabilities of the Collection api. Instead:
There's almost always a way to do what you want to the returned value within the Optional api declaratively using operators, then work with the result. Not saying you don't already know all this, but elaborating for the sake of discussion.
117
u/halfanothersdozen Apr 14 '23
You don't need to make an interface for everything. Everything doesn't have to be private. Write code that doesn't allow for or tolerate nulls and stop checking for them all the time.