Hacker News new | ask | show | jobs
by rzwitserloot 2014 days ago
I'm not sure what these snippets are really supposed to show. This one:

    if (file == null) throw new Error("File must exist");
is literally one character less code than this one:

    let file = file.ok_or(Error::new("File must exist"))?;
and seems to be easier to 'read', but that's of course in the eye of the beholder.

More generally, accepting an optional file seems a bit bizarre; shouldn't the job of dealing with am missing file value be done by the caller?

3 comments

The character count isn't the important point.

The point is that there's no way to use a `Option<File>` type as a `File` without first checking for null. And once you do get a `File` you know that from then on it can't be null.

On the other hand, using a nullable `File` requires that you remember the null check. And that you remember it for every function that takes a `File`. Yes, that last part shouldn't be necessary with sufficient care but historically people do make mistakes that go unnoticed when refactoring or generally just editing code or reusing functions in large projects.

But it doesn't require "remembering" the null check since TypeScript will error when you try to access a member of a nullable value?
In typescript, the type of 'file' implicitly changes, which is more information to keep track of.

In the rust example, a new variable is explicitly introduced—though, granted, it shadows the old by using the same name—and every variable has a static type for the entirety of its lifetime.

Which being said, I don't have a preference for either of those styles.

> More generally, accepting an optional file seems a bit bizarre;

Yes, but in languages where all types are nullable, you cannot opt out.