HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Overusing JavaScript closures?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptoverusingclosures

Problem

I've finally gotten around to learning Lisp/functional programming. However, what I've noticed is that I'm trying to bring ideas back into JavaScript.

Example

Before

var myPlacemark,
    myLineString;

myLineString = ge.createLineString('');
myLineString.setLatitude(100);
myLineString.setLongitude(-100);
myPlacemark = ge.createPlacemark('');
myPlacemark.setGeometry(placemark);


After

var myPlacemark;

myPlacemark = (function(point, placemark){
  point.setLatitude(100);
  point.setLongitude(-100);
  placemark.setGeometry(point);
  return placemark;
})(ge.createPoint(''), ge.createPlacemark(''));


Is there any reason I shoudn't be doing it the 2nd way?

Solution

What you have there is actually just a fancy assignment operation. The closure there plays no role. And if you would need to set another placemark, you would have to repeat the code or wrap in one more function.

IMHO, it would be much more pragmatic to use a lot simpler approach:

var createPlacemark = function (point, placemark) {
        point.setLatitude(100);
        point.setLongitude(-100);
        placemark.setGeometry(point);
        return placemark;
    },
    myPlacemark = createPlacemark(ge.createPoint(''), ge.createPlacemark(''));


This way you get reusable routine with a clear name. And if goal of this all was to prevent external sources from adding placemarks, just warp it all in the standard:

(function () {

}());


The bottom line is: you were over-thinking it.

Code Snippets

var createPlacemark = function (point, placemark) {
        point.setLatitude(100);
        point.setLongitude(-100);
        placemark.setGeometry(point);
        return placemark;
    },
    myPlacemark = createPlacemark(ge.createPoint(''), ge.createPlacemark(''));
(function () {

}());

Context

StackExchange Code Review Q#15496, answer score: 13

Revisions (0)

No revisions yet.