RE: RE: How to write better code with Guard Clauses
You are viewing a single comment's thread from:

RE: How to write better code with Guard Clauses

Words
141
Reading
1 min
Listen
Play
6y

I usually just make some big if conditions haha.

I also use something I love, I'll show it here.

Let's say you want to extract "avatar" from this object:

{
  id: 123456,
  data: {
    type: "message",
    user: {
      "name": "user123",
      "user_id": 1235612,
      "avatar": "https://example.com/avatars/user123_afk20s_3a.jpg"
    },
    body: "test"
  }
}

It could be problematic if there is no response.data.user because it's a system message, for example, or it's not a message, or if the user has no avatar, etc. Whenever the API's are poorly made and somewhat inconsistent on the keys, there is a very easy solution.

Instead of doing this:

let pfp;
if (response && response.data && response.data.user && response.data.user.avatar) {
  pfp = response.data.user.profile_picture;
}

We can do it all more easily like this:

const pfp = ((((response||{}).data||{}).user||{}).profile_picture||"https://example.com/avatars/default.jpg)

At any failure, instead of throwing an error, it goes to undefined and picks the empty object, and if the last property is still undefined, it grabs the default.

edit: (this is obviously not made for features that require you to display a specific error of what is lacking from the input)