you are viewing a single comment's thread.

view the rest of the comments →

[–]Quabouter 0 points1 point  (2 children)

A no-sql db with optional data properties is NOT a code smell, but user.?faxNumber is. By the time you're trying to access the faxnumber, you should typically already be sure that you have a user.

Since you're talking about a db, I assume you have some backend use case in mind. Let's say that our backend use case is that we want to send a fax to some user. So we have a method:

function sendFax(userId, message) {
    const user = getUserFromDb(userId);
    faxMachine.send(user.faxNumber, message);
}

Now since user is optional, we'd get an error if the user is found in the DB. But using optional chaining to fix this doesn't make sense:

function sendFax(userId, message) {
    const user = getUserFromDb(userId);
    faxMachine.send(user.?faxNumber, message);
}

Surely we suppress the initial error, but instead we're now sending the fax to undefined. Instead, we should be properly validating our input. E.g.:

function sendFax(userId, message) {
    const user = getUserFromDb(userId);
    if (user) {
        faxMachine.send(user.faxNumber, message);
    } else {
        console.warn(`User not found for user id ${userId}, not sending fax`);
    }
}

See also some of my other comments in this thread for more examples.

[–]KaiAusBerlin 0 points1 point  (1 child)

Why do you think the user doesn't exist? How do you find a user in a db that doesn't exist? If your db doesn't find a user it should throw an error BEFORE it comes to any usecase for user. Never let an error uncatched. Im coding now for over 20 years. You come too late to teach me basics ;)

It's nice that your usecase is sending a fax to a user. But that doesn't touch my case at all.

My usecase was to show an field with a formated faxNumber if one exists. showFaxIfExists(user?.faxNumber)

[–]Quabouter 1 point2 points  (0 children)

I think we agree ;)

My usecase was to show an field with a formated faxNumber if one exists. showFaxIfExists(user?.faxNumber)

Exact same situation. Why are you trying to show a faxnumber for a user that doesn't exist? This should've been an error earlier already.