How to treat a function that is only used by one function - javascript

When a function that calls one or more other functions, and these functions being called are only ever used by the one calling function, how should the code be structure?
For example if you have funcB() and funcC() which are only ever called by funcA() should funcB() and funcC() be anonymous functions or nested functions or if they are part of a class should they simply be declared private or placed in inner class?
I'm currently working with JavaScript but have encountered the same situation while using other languages such as C++ and Java.
According to Wikipedia JavaScript does have nested functions though I've never seen it used?

When I'm starting a project, I tend to avoid encapsulating functionality until things are getting stable.
As Dancrumb pointed out, function calls aren't free, so you might need some minor refactoring down the line. But when you're looking at code you haven't touched in months, that nice clean organization will be good for your mental health. And that's exponentially more true when you're working in a team :)

If funcB() and funcC() do not conceptually make sense alongside funcA() then you should not make the public.
Traditional OOP would say you should make them private.
It's my opinion that nearly always there is another concept to which funcB() and funcC() belong. You should make them public methods on different class. Whatever holds funcA() holds a private instance of that class.
It's difficult to make a compelling case for this while talking abstractly about A, B and C. But I would say if they do not conceptually belong with funcA() then there is something else that they do conceptually belong to. If you agree with that premise and agree that composition is better than inheritance, the conclusion is to make them public on some other class.

There are a number of approaches here.
Javascript supports anonymous functions that can be defined and assigned to a variable anywhere in your code.
Thus, you could write:
function foo() {
var bar = function() { /* some code */ };
bar();
}
And bar would not be available anywhere else. This might be useful for encapsulating functionality, but I don't think it's a very scalable model for development.
There's a school of thought that suggests that any function that is called only once could, in the future, be something worth calling more than once. In this case, you can create functions that are 'private':
var Foo = (function() {
var Foo = function() {
/* some constructor code */
};
var private = function() { /* a private function */ };
Foo.prototype.public = function() {
private();
/* And some other stuff */
};
return Foo;
})();
var foo = new Foo();
foo.public(); /* Includes a call to the private method */
In this, your private method is truly private, so you don't have to expose inner workings to the world.
But really, that's more of a discussion of how to implement access modification. There's plenty of information out there to answer that question. The bigger, design question is whether to implement separate functions, or whether to just inline them.
My choice is generally to tuck cohesive pieces of function into... well, into functions. The cost of a function call is non-zero, but worry about that after the fact... if you identify that the function call is a performance bottleneck, then you can worry about whether you're calling too much and whether you should refactor your code to use fewer calls.
Until that time, write your functions, call them and revel in clear code. Just make sure you use good method names :)

If funcB and funcC are created as a closure inside your class and you don't 'expose' these to the interface, then they can change (be removed, added, return different values, etc...) without worrying about how they've been implemented outside the Class.
Once they are exposed all bets are off and they might need to be unit tested, supported, etc. This is a well known rule.
A closure is simply a function declared within the scope where its going to be used.
Method A
function MyClass(){
function funcA(i){
funcB(i);
funcC(i);
}
function funcB(i){
//...
}
function funcC(i){
//...
}
return {funcA:funcA}
}
va mc = new MyClass()
for(var i = 0;i<100000;i++){
mc.funcA(i);
}
Method B:
function MyClass(){
function funcA(){
function funcB(){
}
function funcC(){
}
for(var i = 0;i<100000;i++){
funcB();
funcC();
}
// funcB, funcC are created before and then released after this
}
return {funcA:funcA}
}
va mc = new MyClass()
mc.funcA();
Method B might be less preferred when funcA is called many times because assignment is optimally expensive.
Method B might be preferred when considering memory. Although it's debatable since funcA and funcB are resident in both MyClass and MyClass.funcA.

Related

Javascript Modular Prototype Pattern

The problem with functional inheritance is that if you want to create many instances then it will be slow because the functions have to be declared every time.
The problem with prototypal inheritance is that there is no way to truly have private variables.
Is it possible to mix these two together and get the best of both worlds? Here is my attempt using both prototypes and the singleton pattern combined:
var Animal = (function () {
var secret = "My Secret";
var _Animal = function (type) {
this.type = type;
}
_Animal.prototype = {
some_property: 123,
getSecret: function () {
return secret;
}
};
return _Animal;
}());
var cat = new Animal("cat");
cat.some_property; // 123
cat.type; // "cat"
cat.getSecret(); // "My Secret"
Is there any drawbacks of using this pattern? Security? Efficiency? Is there a similar pattern out there that already exists?
Your pattern is totally fine.
There are a few things that you'd want to keep in mind, here.
Primarily, the functions and variables which are created in the outermost closure will behave like private static methods/members in other languages (except in how they're actually called, syntactically).
If you use the prototype paradigm, creating private-static methods/members is impossible, of course.
You could further create public-static members/methods by appending them to your inner constructor, before returning it to the outer scope:
var Class = (function () {
var private_static = function () {},
public_static = function () {},
Class = function () {
var private_method = function () { private_static(); };
this.method = function () { private_method(); };
};
Class.static = public_static;
return Class;
}());
Class.static(); // calls `public_static`
var instance = new Class();
instance.method();
// calls instance's `private_method()`, which in turn calls the shared `private_static();`
Keep in mind that if you're intending to use "static" functions this way, that they have absolutely no access to the internal state of an instance, and as such, if you do use them, you'll need to pass them anything they require, and you'll have to collect the return statement (or modify object properties/array elements from inside).
Also, from inside of any instance, given the code above, public_static and Class.static(); are both totally valid ways of calling the public function, because it's not actually a static, but simply a function within a closure, which also happens to have been added as a property of another object which is also within the instance's scope-chain.
As an added bonus:
Even if malicious code DID start attacking your public static methods (Class.static) in hopes of hijacking your internals, any changes to the Class.static property would not affect the enclosed public_static function, so by calling the internal version, your instances would still be hack-safe as far as keeping people out of the private stuff...
If another module was depending on an instance, and that instance's public methods had been tampered with, and the other module just trusted everything it was given... ...well, shame on that module's creator -- but at least your stuff is secure.
Hooray for replicating the functionality of other languages, using little more than closure.
Is it possible to mix functional and prototypical inheritance together and get the best of both worlds?
Yes. And you should do it. Instead of initializing that as {}, you'd use Object.create to inherit from some proto object where all the non-priviliged methods are placed. However, inheriting from such a "class" won't be simple, and you soon end up with code that looks more like the pseudo-classical approach - even if using a factory.
My attempt using both prototypes and the singleton pattern combined. Is there a similar pattern out there that already exists?
OK, but that's something different from the above? Actually, this is known as the "Revealing Prototype Pattern", a combination of the Module Pattern and the Prototype Pattern.
Any drawbacks of using this pattern?
No, it's fine. Only for your example it is a bit unnecessary, and since your secret is kind of a static variable it doesn't make much sense to me accessing it from an instance method. Shorter:
function Animal(type) {
this.type = type;
}
Animal.prototype.some_property = 123;
Animal.getSecret = function() {
return "My Secret";
};

Is it better to exit from a Function to cut-down on Activation Objects, than recursively or calling nested functions?

In JavaScript and other languages, I've heard about Activation Objects being created as you invoke a method / function. In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Now if there's no way around it and you must call multiple methods, is it better to call one method after another, like this:
myFunc1();
myFunc2();
myFunc3();
// or...
var myFuncs = [myFunc1, myFunc2, myFunc3];
for(var a=0, aLen=myFuncs.length; a<aLen; a++) {
myFuncs[a]();
}
OR, to nest them like this:
function myFunc1() {
// Do something...
myFunc2();
}
function myFunc2() {
// Do Something else...
myFunc3();
}
function myFunc3() {
//Do one last thing.
}
//Start the execution of all 3 methods:
myFunc1();
I'm assuming it makes more sense to go with the 1st technique, since it comes back to the previous scope and releases the last Activation Object... but if someone could confirm this,
I would really like to know!
Thanks
In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Yes and no. Functions (or more generally, subroutines) are there to be called, and not doing so makes no sense. If you can make your code more DRY by introducing another function, do so.
The only place where not using them is reasonable are high-performance loops which run thousands of times doing little work, and function calls would add a noticable overhead. Do not try to prematurely optimize!
Also, there are some languages which handle recursion not well and where you will need to translate recursive function calls to loops, preventing stackoverflow exceptions. However, this is a rare case as well.
is it better to call one method after another, or to nest them?
That depends, since the two techniques do different things. With #1, there are just 3 independent functions which are called after each other. In contrast, #2 defines functions that always call each other - you can't get myFunc2 without myFunc3. Is that intended?
If it is, there's nothing wrong with this nesting. The two additional stack layers will not harm your performance.
For information concerning Activation Objects, please refer to http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#more-546
This is not an optimization level concern however, as the concern you listed is an example of EXTREME pre-optimization and your time is not worth that type of investment. And actually, the example you listed above, there is little to no savings when you are looking at Activation Objects alone.
As for proper use however, I try to encapsulate as much as I can. If a function doesn't have to go in the global scope, and can live within the scope of another function, then that's where it should be declared.
for example, for better scoping.
var f2 = function() {
}
var f1 = function() {
f2()
}
// is not as nice as:
var f1 = function() {
var f2 = function()
f2()
}
// or even better..
var f1 = function() {
function() {
}() ; execute
}
Separation of responsibility:
private function myFunc1(): void
{
}
private function myFunc2(): void
{
}
private function myFunc3(): void
{
}
private function doAllFunc(): void
{
myFunc1();
myFunc2();
myFunc3();
}

What is a proper, modern and cross-browser safe method of creating JavaScript classes?

I am confused with hundreds of ways of creating JS classes. One says that I should use prototypes, while others say that noone uses prototype beacuse it is "bad". On the other hand CoffeeScript uses prototypes but wraps a construction with a function whick returns itself (or something). I've seen function that returns an object, function that returns a function that returns an object etc..
I think it should be easy and no frameworks should be needed to create classes in a language - maybe I'm missing something.
There are also two (al least) ways of creating methods : foo: function() {} and function foo() {}. I've even seen those two ways in single class. The problem is that the first way results in creating annonymous functions (wich happens to be assigned to a field of an object) and debuggers say that error happened in annonymous function called by annonymous function etc.
I understand that JS is intended to be functional rather than OOP, but sometimes a class is the best way to describe a concept (e.g. a UI widget wants to be a class).
I'd be grateful for an example of proper constructed class with few words of explanation.
I think this article explains it well:
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
This is (I believe) the correct way to use classes in a prototype based language like javascript, and gives a good explanation of the concepts. I use this approach in my projects, and it seems to work in all modern browsers.
I think you can consider the code that CoffeeScript produces "good":
// Create a "class" named Foo = create a variable that contains whatever the
// self-invoking anonymous function returns (the function avoids the pollution
// the global namespace).
var Foo = (function() {
// Create the "class" = the constructor function that is supposed to be used
// with the "new" keyword to create instances (objects).
function Foo() {}
// Add a method "bar" (that's what the prototype is for!)
Foo.prototype.bar = function(baz) {
// Assign the value to a member variable of the current instance (this)
this.foobar = baz;
};
// ...add more stuff.
// Return only the function, every other local variable stays in this scope.
return Foo;
})();
If you are confident in using CoffeeScript, it has solid approach to classes, and gives you much clear syntax, compared to any other OOP framework at the same time.

Javascript global context’s variable object vs function activation object

Here are two samples of js code:
A. function _foo is defined within the global context
function _foo(){ //some code here
}
//... some unrelated code here
var foo = function(){
var result = _foo();
return result;
}
B. function _foo is defined within the function context
var foo = function(){
function _foo(){ //some code here
}
var result = _foo();
return result;
};
Which one of them is a better programming practice in terms of memory management? Since the function foo will be called many times in the application, is it better to keep _foo in the global context (of the app) and not create it within the function context everytime foo is called? Or since _foo will be (mostly) used inside foo, it makes sense to keep it part of the activation object?
C: Caching
var foo = (function(){
function _foo(){ //some code here
}
return function() {
var result = _foo();
return result;
}
}());
Foo is immediately executed and the function _foo is only declared once.
In modern browsers this is 5% slower then a "global" function.
Relevant Benchmark
To answer your question directly, if you're going to have to instantiate an object of foo every time that you want to call it, then declaring it at global scope would certainly be a faster alternative.
However, in JavaScript there will almost certainly be quicker wins from a performance perspective, most often pertaining to DOM interaction.
In these sorts of examples, I would recommend you stick with best programming practice. What would you do if this were C#, Java or some other more strongly-typed language? Well, you wouldn't be able to declare a global function, so you would put it in a class, either as a static method, or as a public method:
var foo = function(){};
//static method
foo._foo = function(){
alert("_foo");
};
//public method
foo.prototype._foo2 = function(){
alert("_foo2");
};
//calling static method
foo._foo();
//instantiating and calling public method:
var f = new foo();
f._foo2();
//note: this won't work (as we would expect!)
foo._foo2();
Most things like this are a trade-off, favouring style and structure here over performance is a good one.
Try an create your functions on the global context and use closure functions as asynchronous callbacks specific to the original functional request. You can potentially get into nasty memory leaks with too many anonymous function calls, because javascript will hold onto the top level variables that you use within the closure.
You may also want to use closure functions if you're trying to design in an OO style for private members. Do some Google/Stackoverflow searches on 'object oriented javascript' and your get more design help on that particular topic.
A quote From MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
Closures can use up a lot of memory. The memory can be freed only when the returned inside is no longer accessible...
Because of this inefficiency, avoid closures whenever possible, i.e. avoid nesting functions whenever possible.
Again, considering OO design is good... wrapping your functions into an object so that you can call them statically or via an object reference is a good design as well.

Declaring functions in JavaScript [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed last year.
What's the difference between these two ways of declaring a function?
function someFunc() { ... }
var someFunc = function() { ... }
I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.
I am on different opinion with most of the people here. Technically this syntax may mean the same for declaring functions both ways
(I stand incorrect on my last statement. I read up on a diff post why they are technically diff and I'll add in the end, why)
; but the way they play a role in evolving patterns is massive. I would highly recommend "Javascript: The Good Parts" by Doughlas Crockford.
But to prove my point in a subtle and a simple manner; here is a small example.
//Global function existing to serve everyone
function swearOutLoud(swearWord) {
alert("You "+ swearWord);
}
//global functions' territory ends here
//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
name : "squarePants",
swear : function(swearWord) {
name = "spongy";
alert("You "+ swearWord);
return this;
}
}
//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
alert("Hey " + this.name + ", I'm sorry man!");
return this;
}
//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());
if you look at the code above I declared a function with a name swearOutLoud. Which would take a swear word from any object or a call and will give you the output. It can do operations on any object using the "this" parameter that is passed to it and the arguments.
However second declaration is declared as an attribute of object called "spongeBob". This is important to note; as here I am moving towards an object driven behavior. While I am also maintaining "cascading effect" as I return "this" if i have nothing else to return.
Somthing similar is done in jquery; and this cascading pattern is important if you are trying to write a framework or something. You'll link it to Builder design pattern also.
But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.
To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.
I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.
But thats just me! Take it or leave it. :)
EDIT:
So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.
//success
swearOutLoud("Damn");
function swearOutLoud(swearWord) {
alert("You " + swearWord)
}
Above code will work properly. But code below will not.
swear("Damn!");
var swear = function(swearWord) {
console.log(swearWord);
}
One advantage of using function someFunc() { ... } is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.
Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :
var myObject=new Object();
myObject.someFunc=function() { ... };
Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable
this.someFunc = function() { ... }
...
someFunc: function() { ... },
However, as also mentioned it's anonymous and therefore the name does not appear when profiling.
Another way to declare the function is as follows which gets you the best of both worlds
var someFunc = function someFunc() { ... }
Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTo function thusly:
if (document.addEventListener) {
function addEventListenerTo(target, event, listener) {
....
}
} else if (document.attachEvent) {
function addEventListenerTo(target, event, listener) {
....
}
} else {
function addEventListenerTo(target, event, listener) {
....
}
}
on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programming techniques using anonymous functions assigned to variables.
var fib = memoize(function (n) {
if (n < 0) return 0;
if (n < 2) return 1;
return fib(n-1) + fib(n-2);
});
...
// patch the $ library function
if (...) {
$ = around($, fixArg, fixResult);
}
It is both true that the first form:
function test() { }
is a more recognized syntax and that the second form:
var test = function() { ... }
allows you to control the scope of the function (through the use of var; without it, it would be global anyway).
And you can even do both:
var test = function test() { ... test(); ... }
This allows you to define a recursive function in the second form.
For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.
For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function() or function someFunc()?
Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.
I know this is a non-technical answer, but it's harder for humans to read code than computers.
When you write
function Test() {
}
JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.

Categories

Resources