Home A better way to check if something is valid in BrightScript
Post
Cancel

A better way to check if something is valid in BrightScript

If there is one thing I’ve learned from working in code for so long it’s that negative conditions in if statements can easily trip people up. That’s why when possible, I try to use positive conditions instead of negative conditions.

Obviously, this doesn’t always make sense, but in BrightScript, there is one fundamental condition we can apply this code style to and it greatly improves code readability.

In BrightScript, you will need to frequently check if a variable is not invalid. In most of Roku’s documentation and sample code you’ll see this check written as:

1
2
3
if variable <> invalid
    doSomething()
end if

This works just fine; however, place several of these checks in a chain or in a function and it can get messy quick!

Here’s a simple helper method I made to save a few characters and make the code a little easier to read at a glimpse.

1
2
3
function isValid(input as dynamic) as boolean
    return input <> invalid
end function

It doesn’t get much simpler than that. Now instead of using the negative condition to check if something is not invalid, we can use a positive condition to check if something is valid.

1
2
3
if isValid(variable)
    doSomething()
end if
This post is licensed under CC BY 4.0 by the author.

Trending Tags