3

I have this function in an AngularJS service:

self.IsValid = function (entity) {
    if (entity == undefined || entity == "undefined")
        return false;

    if (entity == null)
        return false;

    if (entity == "00000000-0000-0000-0000-000000000000")
        return false;

    return true;
}

A working sample here.

Is there anything I can do to improve on this? Or maybe there's a better way altogether?

PS: Resharper says that the entity == null check is always false, but that doesn't feel right, I could have passed null.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Spikee
  • 3,967
  • 7
  • 35
  • 68

2 Answers2

2

You can use

self.IsValid = function(entity) {
    return (entity !== "undefined" && entity !== "00000000-0000-0000-0000-000000000000") && !!entity;
};
  1. entity !== "undefined" && entity !== "00000000-0000-0000-0000-000000000000": Checks if the value of entity variable is not 'undefined' and '00000000-0000-0000-0000-000000000000'. If the expression evaluates to false the result will be returned.
  2. !! will cast the value to Boolean. See What is the !! (not not) operator in JavaScript?

Updated Plunker

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Downvoted. I guess some condition is failing, Can you please add some description, so that the answer can be improved. – Tushar Nov 19 '15 at 09:09
  • What do you check with `!!entity` that checking `undefined` or `null` doesn't already cover? – Spikee Nov 19 '15 at 09:12
  • @Spikee Didn't get you, you can read more http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – Tushar Nov 19 '15 at 09:15
  • I mean, generally speaking, an object is undefined when it's `null`. For Javascript, I think because it's weakly typed, it's decided to have `undefined` as well. But, what other state would there be that you need to check with `!!entity`? – Spikee Nov 19 '15 at 10:20
  • 1
    @Spikee [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). The values here will return `false` when used with double bang `!!` i.e. coerced to boolean. All other values will be [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). – Tushar Nov 19 '15 at 10:22
1

If you can identify all of the invalid cases, then you can simply list them in an array and then check the entitity against them

var invalid = [undefined, "undefined", null, "0000-..."];
var isInArray = invalid.indexOf(entity) >= 0;
return isInArray;

This will be easier to maintain than a large compound boolean expression. You could even move this list out into a separate config file, to be shared and injected into your separate services.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120