patternjavascriptMinor
I'm torn between conditionals and abrupt return functions
Viewed 0 times
conditionalsreturntornbetweenandfunctionsabrupt
Problem
Which one of these two is better?
This one:
Or this one:
The function within function thing bothers me a little. But so does setting
This one:
middleware.response_redirect = function(){
return function (req, res, next){
var redirect = function(){
if(req.form.redirect) return url.parse(req.form.redirect);
return {
protocol: "http",
hostname: config.domain,
pathname: "thanks",
}
}();
redirect.query = querystring.stringify({
"status": "success",
"message": req.form.message
});
return res.redirect(url.format(redirect);
}
}Or this one:
middleware.response_redirect = function(){
return function (req, res, next){
var redirect;
if(req.form.redirect){
redirect = url.parse(req.form.redirect);
}else{
redirect = {
protocol: "http",
hostname: config.domain,
pathname: "thanks",
}
}
redirect.query = querystring.stringify({
"status": "success",
"message": req.form.message
});
return res.redirect(url.format(redirect);
}
}The function within function thing bothers me a little. But so does setting
redirect in two places.Solution
How about a ternary operator?
Looks cleaner in my opinion.
var redirect = req.from.redirect
? url.parse(req.from.redirect)
: {
protocol: 'http',
hostname: config.domain,
pathname: 'thanks'
};Looks cleaner in my opinion.
Code Snippets
var redirect = req.from.redirect
? url.parse(req.from.redirect)
: {
protocol: 'http',
hostname: config.domain,
pathname: 'thanks'
};Context
StackExchange Code Review Q#37933, answer score: 8
Revisions (0)
No revisions yet.