避免else
並利用早期的return
可以防止代碼變得太深嵌套。哪個示例看起來更可讀?
function doStuff (thing) {
if (thing.foo) {
alert ("thing.foo is alive and well");
if (thing.foo.bar) {
alert ("thing.foo.bar is alive and well");
if (thing.foo.bar.baz) {
alert ("thing.foo.bar.baz is alive and well");
// TODO: stuff with thing.foo.bar.baz
} else {
alert ("thing.foo.bar.baz doesn't exist!");
}
} else {
alert ("thing.foo.bar doesn't exist!");
}
} else {
alert ("thing.foo doesn't exist!");
}
}
或
function doStuff (thing) {
if (!thing.foo) {
alert ("thing.foo doesn't exist!");
return;
}
alert ("thing.foo is alive and well");
if (!thing.foo.bar) {
alert ("thing.foo.bar doesn't exist!");
return;
}
alert ("thing.foo.bar is alive and well");
if (!thing.foo.bar.baz) {
alert ("thing.foo.bar.baz doesn't exist!");
return;
}
alert ("thing.foo.bar.baz is alive and well");
// TODO: stuff with thing.foo.bar.baz
}
...我覺得第二個是更可讀!
您使用哪種語言? – ChaosPandion 2010-07-12 23:40:40