Comparison with possibly non-existent properties

ساخت وبلاگ

Vote count: 0

My background is more in strongly-typed languages than not, so I will state up front that I have a bias against treating undefined objects in a casual manner. That said, I was considering a simple question of assigning a Boolean value to a variable, where said Boolean comes from the property of some object, and while the object will always exist the property may not.

That sounds more complicated than it really is. Take a look. We start with spinning up some objects early in the code, covering the three possible scenarios:

var object1 = {};
object1.IsDisplayed = true;
var object2 = {};
object2.IsDisplayed = false;
var object3 = {};
// notice we do *not* create the IsDisplayed property here

Sometime later we call the process() function that takes a single argument. Let's call this baseline Solution A.

Solution A

This being JavaScript, that actually works as expected for object1, object2, and object3. But it seems to have a bit of a code smell to me; it is not clear that the author has considered a possibly non-existent property.

function process(renderedItem) { var rendered = renderedItem.IsDisplayed; if (rendered) { // do some stuff here }
}

I see two possible ways to make this more robust:

Solution B

I like this solution because it is both robust and clear to even the most casual reader that the undefined case has been properly considered. On the downside it is wordy, not nearly as compact as solution C, and it uses a string name of a property, which I have a strong distaste for.

function process(renderedItem) { var rendered = renderedItem.hasOwnProperty('IsDisplayed') ? renderedItem.IsDisplayed : false; if (rendered) { // do some stuff here }
}

Solution C

I like this solution because it is robust and compact; it explicitly takes into account a possibly non-existent property; however, it is not nearly as obvious as solution B. I remember early on reading some colleagues' code and thinking,"What the heck?" and suggested deleting the === true as redundant. Also, it still is technically referencing an undefined value (in the case of passing in object3).

function process(renderedItem) { var rendered = renderedItem.IsDisplayed === true; if (rendered) { // do some stuff here }
}

Is there a clear "best practice" amongst these three variations?

asked 1 min ago

back soft...
ما را در سایت back soft دنبال می کنید

برچسب : نویسنده : استخدام کار backsoft بازدید : 128 تاريخ : دوشنبه 24 خرداد 1395 ساعت: 4:40