mankowitz
asked on
eloquent javascript
What is the best (i.e. most elegant, concise, readable, beautiful, meaningful, expressive, 31337, etc) way of doing error checking on a long string of functions where each one depends on the one before it?
For example, I have a function called findShift(id) which returns an object if the object isn't found, it returns null. I want to access one of the parts of that object.
The problem is that if findshift() returns null, then I get a javascript error about how it can't get the .worker property of null. The same goes if the worker property is null and lastname is null. What I really want is for the whole thing to just assign null if any part of the chain is null. One option is the following:
but that requires me to run the findshift() function three times, which might be expensive. Another option is this:
but I find that to verbose and klunky. Is there a better way to do this? Is Try/Catch the solution?
For example, I have a function called findShift(id) which returns an object if the object isn't found, it returns null. I want to access one of the parts of that object.
var worker = findshift(id).worker.lastname;
The problem is that if findshift() returns null, then I get a javascript error about how it can't get the .worker property of null. The same goes if the worker property is null and lastname is null. What I really want is for the whole thing to just assign null if any part of the chain is null. One option is the following:
var worker = finshift(id) && findshift(id).worker && findshift(id).worker.lastname;
but that requires me to run the findshift() function three times, which might be expensive. Another option is this:
var lastname = null;
var worker = null;
var shift = findshift(id);
if (shift) {
worker = shift.worker;
if (worker) {
lastname = worker.lastname;
}
}
but I find that to verbose and klunky. Is there a better way to do this? Is Try/Catch the solution?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I don't know that this is the most elegant way but I think it is readable!
if (worker = shift.worker == null) return;
if (lastname = worker.lastname == null) return;
// All data available here