You program must break when something is not right because shitty lasts forever.
Immutable objects are great but you need to validate them when you construct them and throw an exception when something is not right.
And functions should return what you would expect.
For example, this:
function GetEntitryById(int id):Entity
{
var entity = [action to get an entity];
if(entity == null) {
throw new Exception("Entity not found");
}
return entity;
}
is better than:
function GetEntitryById(int id):Entity?
{
var entity = [action to get an entity];
return entity;
}
Or use Option/Maybe or Either to represent this and let callers explicitly handle this rather than catching an exception. Is an entity not being found truly an exceptional case?
In the case that you're providing an explicit id as an argument, yes. If it were a query, no. It's dangerous to use an empty value for all failed lookups, as you can't differentiate between "not found because it doesn't exist" versus "not found because the database went offline for a minute".
I think that code example depends on the type system. In elm, the compiler forces you to handle both cases if you return a Maybe. In Java everything can be null and blow up which is bad. In Kotlin you have to handle the possible null, but it's a bit brittle when calling into Java code.
But yeah, better to fail fast. That's why I want tools to catch stuff as I write the code, not when I run it, as I cannot run all cases so then it won't hit until prod.
You program must break when something is not right because shitty lasts forever.
Immutable objects are great but you need to validate them when you construct them and throw an exception when something is not right. And functions should return what you would expect.
For example, this:
is better than: