我有两个类似的函数,它们都需要相同的参数检查
function doThis(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// ... some other checks and enforcements...
// Output as alert
alert(foo + bar);
}
function doThat(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// ... some other checks and enforcements...
// Output on console
console.log(foo + bar);
}
什么是干燥的正确方法?我想出了这个:
function paramsCheck(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// maybe some other checks and enforcements...
return { foo: foo, bar: bar };
}
function doThis(foo, bar) {
var params = paramsCheck(foo, bar);
// Output
alert(params.foo + params.bar);
}
function doThat(foo, bar) {
var params = paramsCheck(foo, bar);
// Output
console.log(params.foo + params.bar);
}
但我对此并不满意。我宁愿将参数作为引用传递给paramsCheck()
,所以我可以直接修改它们而不是返回一个新对象。