which approach is better for implementing canvas in html5? - javascript

I want to know differences between the two following approaches from efficiency or any other point of views:(these codes are written using HTML5 Canvas)
first one has separate functions including drawScreen() function and event handling functions which all call the drawScreen().
the other one has a function canvasApp() which contains all the functions including drawScreen() inside along with other functions for handling the events. these function again call the drawScreen function inside themselves.
the codes are so long but if the explanation is not clear enough I will put the codes.

It sounds like you either want to have one function that takes a parameter which indicates which function to call, or you want to simply call each function directly. Please correct me if I am wrong.
I would personally go with the separate options. I don't see what encapsulating them inside a global function would bring in terms of functionality or simplicity. As long as the functions are clearly defined and documented I believe this is probably the best approach.
I would be more than happy to give you a more detailed answer, but you are going to have to enlighten us a bit more on your overall architecture (maybe with some pseudocode).

This is a rather religious question.
Javascript is a programming language which combines concepts from procedural, functional and object-oriented programming, so it allows to work in a lot of different programming paradigms.
Option one would be the procedural approach, while two would be the object-oriented approach. We could now have an endless discussion about which programming paradigm is the best, but we would never come to a result.
You have to know for yourself which programming style suits you best and suits your application best.

Related

Hooking Function Constructor (JavaScript)

Does anyone know of a way to detect when a new function is created?
I know you can hook the function class constructor but that will only detect new Function() calls, not function func(){} declarations.
I assume the JS engine just creates a default function class when it sees a function declaration instead of looking at the global Function class.
Does anyone know if this is the case or if you can intercept function declarations.
Example function to hook :
function add(x,y){return x+y}
A hook should get the function when it is defined and hopefully redefine it to be able to capture the arguments, this, and return value.
(V8 developer here.)
No, there is no way to intercept all function declarations.
FWIW, this isn't up to individual engines to decide; the JavaScript language provides no way to accomplish this, and engines aim to implement the language without any custom deviations (i.e. neither adding nor removing features).
I can offer two alternative ideas that may or may not serve your purposes:
(1) V8 has a --trace flag which logs all function entries and returns to stdout. Be warned: this tends to produce a lot of output.
(2) You could feed the source of the app you are interested in to a JavaScript parser, and then run whatever analysis (and/or transformation) you want over the AST it produces. This won't catch dynamically generated and eval-ed functions, but it will find all function func() {...} declarations.
The need is game hacking.
In the interest of helping you ask better questions (so that you may get more helpful answers), I'd like to point out that that's not the level of detail that #Bergi was asking for: the general area in which you are active does not provide any hints for possible alternative approaches. Wanting to hook function declarations so that you can capture their arguments and return values is a search for a specific solution. #Bergi's question is: what is the specific problem that you are trying to solve by intercepting all functions?
That said, "game hacking", while being very vague, does sound sufficiently shady that I'd like to humbly suggest that you not only think about whether you could, but alse give sufficient thought to whether you should.

Is there a set of restrictions I can use to simulate functional programming in JavaScript?

I was watching a talk on clean code by Misko Hevery, and he mentioned trying to write a program with no if statements in them (well, as few as humanly possible) in order to simulate working on... Smalltalk or some such language, where polymorphism is preferred over inline conditional behavior.
To my limited understanding, functional programming is hard for only-imperative-so-far programmers like me - because our state changing methodologies don't have a way to be expressed in functional programs. A function only takes a value and returns a value and knows nothing about state.
I have also seen JS being hailed as being able to support a functional model.
So is there a simple set of restrictions, similar to my first paragraph, which will enable me to try out the functional paradigm in a language I know and love - rather than learn a full new language (I'll do that eventually but I want to try the ethos right now)?
There are two meanings to the term "functional programming".
The first meaning is the ability of a program to manipulate functions. Not all languages can do this but javascript is one of the languages that can. Languages that can assign functions to variables, pass functions to arguments and return functions are called functional programming languages so javascript is functional as is.
In this sense, if you look at any modern javascript code with prevalent use of callbacks then you're already doing functional programming.
The second meaning of functional programming is the style of programming where the primary method of program composition is functions rather than variables. In this sense almost any language can be used in a functional style by avoiding variable assignments and loop structures (use recursion instead).
When you look at the functional community, what they mean by functional is the first meaning plus a very strong version of the second meaning -- that is, variables are not only avoided but banned. Languages like Haskell don't have the concept of variables. To handle side-effects and mutable state like I/O they use a concept called monads.
You don't have to go that far. Classical functional languages like Lisp and Forth allowed variables. You just have to avoid them where possible.
Lisp and Forth style functional programming is heavily driven by processing lists/arrays without assigning anything to temporary variables. To some people, this style is easier to read. Where in imperative style you'd do this:
var a = [1,2,3];
var b = 0;
for (var i=0;i=a.length;i++) {
b += a[i] * 2;
}
// result is in b
in functional style you'd do this:
[1,2,3].
map(function(x){return x*2}).
reduce(function(x,y){return x+y},0);
Conceptually, functional style makes it look like you're applying filters to the array instead of iterating through the array. If you've ever used command line tools like grep then you'd find this concept very familiar.
Notice that we haven't introduced any variable assignments at all in the functional style.
The three core array methods/functions in the functional style are: map, reduce and filter. With them you can avoid something like 90% of for-loops.
Great question.
For an in-depth answer, check out this classic (and awesome) paper by John Hughes -- Why Functional Programming Matters.
First, Hughes explains what functional programming is not about, and cites some weak arguments that proponents of FP use. Good stuff (but too long to quote here).
Second, Hughes explains what FP is about:
It is now generally accepted that modular design is the key to successful programming, and recent languages such as Modula-II [6] and Ada [5] include features specifically designed to help improve modularity. However, there is a very important point that is often missed. When writing a modular program to solve a problem, one first divides the problem into subproblems, then solves the subproblems, and finally combines the solutions. The ways in which one can divide up the original problem depend directly on the ways in which one can glue solutions together. Therefore, to increase one’s ability to modularize a problem conceptually, one must provide new kinds of glue in the programming language. Complicated scope rules and provision for separate compilation help only with clerical details — they can never make a great contribution to modularization.
We shall argue in the remainder of this paper that functional languages provide two new, very important kinds of glue. We shall give some examples of programs that can be modularized in new ways and can thereby be simplified. This is the key to functional programming’s power — it allows improved modularization. It is also the goal for which functional programmers must strive — smaller and simpler and more general modules, glued together with the new glues we shall describe.
(emphasis mine)
So to get back to the original question, in order to do FP in Javascript, you'll want to build programs by implementing separate modules, then gluing them together. Javascript comes with some nice glue, and you can build even more glue on your own -- check out combinators.
You should try to avoid features that prevent you from using glue to combine modular pieces of code, for example:
mutable state -- especially if it's global
statements -- you can't pass while-loops as function arguments
some kinds of syntax, such as operators or property access -- you can't assign + to a variable or pass it as an argument
(These issues can, of course, be mitigated to a certain extent -- check out Javascript FP libraries for examples.)
On the other hand, features that aren't functions -- such as classes, objects, inheritance, prototypes, etc. -- don't necessarily stop you from using Javascript's glue, so there's no reason, from an FP standpoint, not to use them.

Any way to check whether a function has external side-effects (or enforce that it won't)?

I am interested in Javascript frameworks like Rivertrail, which provides a parallel programming abstraction, but only provides well defined semantics if the functions you pass in to do the work have no external side effects.
I'm wondering if there is any way to either write a check that a passed in function is side-effect free? or to hide everything in the environment from a function (so that it has nothing to modify)? or temporarily declare everything in the environment "const" (but just for the scope of the definition of the function?) (Or any other crazy idea that would give me the equivalent of simply declaring __attribute__ ((pure)) in gcc.)
Parallel programming is one of those places where "pure" functional programming can really make a difference. Without pure functions defining reasonable semantics for parallel programs gets really hard (check out the semantics of C++ where they had to define what a data-race is so that they could declare that any program that has one is undefined.)
I can imagine other places where someone might find this useful, if it were possible. It might be useful to allow users of a web-page to pass in guaranteed pure no-side-effect Javascript functions that check for certain conditions during a query, for example.
write a check that a passed in function is side-effect free?
This is "effect analysis" - a form of type checking.
Since Javascript doesn't have a type and effect system, any approach to detecting side effects will necessarily be approximate and rely on heuristics. There's no way to do this in general for Javascript.

Avoiding Nested Anonymous Functions in JavaScript / Sencha Touch / ExtJS

I've started using the Sencha Touch / ExtJS JavaScript framework and have am noticing a wide use of nested, anonymous functions. For example, this is a common way to start your app:
Ext.setup({
blah: blah,
onReady: function() {
my
fairly
long
startup
code }
});
It's been a while since I've done JavaScript programming; to me, defining a nested anonymous function like this--inside of a function call--is not as easy to read as the following:
Ext.namespace('myvars');
myvars.onReadyFcn = function() {
my
fairly
long
startup
code
};
Ext.setup({
blah: blah,
onReady: myvars.onReadyFcn
});
I understand there are some real benefits to using anonymous functions in certain situations (e.g., maybe it's one-time code, maybe you don't want to add another function to the global namespace, etc.). That said, is there anything technically wrong/detrimental to using this latter (perhaps more verbose) method if you find it easier to read?
Thanks!
I use both ways all the time without thinking too much about what is better. And I believe that in terms of performance if you are worried about a mobile device download time or parsing time then you will end up using some JS Minifier (or maybe Google's Closure Compiler).
Anyway, I do have a criteria that seems helpful to me to decide whether the function should be anonymous or not:
If I had a really good name for the function then it shouldn't be anonymous
What I mean is if your function will be named onSetupReady then the function is not explaining what it does, instead, its name is defining where it should be used (and that would usually be one only place which will call that function). So if that is the case then you can choose to make the function anonymous or not. I usually choose anonymous.
But, if your functions does one just one thing, and that thing in not really obvious, and you are tempted to put a single line comment in the first line of the function (or whatever) to explain what it does. then I won't do that, and I would choose a good name for this function. And I emphasize this rule, even more, when the event which triggers this function is not obvious for that function. Examples:
Anonymous OK
Ext.Window({
listernes: {
beforeclose: function() { // This function has only one purpose and
Ext.Msg.show({ // can be named, but I think it's OK. Because
title:'Close?', // it is really easy to see what it does.
msg: 'Are you sure?',
fn: function(btn) {
if (btn === 'cancel') {
return false;
}
},
animEl: 'elId',
icon: Ext.MessageBox.QUESTION
});
}
}
}).show();
Anonymous NOT Recommended
var insertExtraToolbar = function() {
var containerNbar = theGrid.getBottomToolbar().getEl().parent().dom;
theGrid.elements += ',nbar';
theGrid.createElement('nbar', containerNbar);
};
theGrid.on('render', insertExtraToolbar);
I don't think there is anything wrong using separate functions, depending on the purpose. For a setup function or onReady functions I will like anonymous functions, for callback functions that are really small piece of code like 1 or 2 simple line I will use anonymous functions. For callbacks I often like to use a separate function however, I find it easier to read and especially with most frameworks giving an easy way to pass parameters to the callbacks when making XHR.
However, one advantage nested anonymous functions gives you is the closures around variables that sometimes you might end up needing to pass as parameters if you separate the function.
It is a very tough question to answer because it will be a question of style, performance, purpose that will be different depending what is the purpose of the code you're writing.
I used to have the same feelings you did when I first started encountering nested anonymous functions.
Now that I've gotten much more used to them I actually find nested anonymous functions much easier to read as long as they're only used in one spot. When code is written that way, all the code I'm interested in is in a single spot and I don't have to jump around the file nearly as much to figure out what the code is trying to do.
Keep in mind, though, that my opinion only applies if the code is only used in one location. If you keep repeating the same anonymous function in multiple places...I still prefer to break it out like your second example.
In a way, you may have answered your own question. The OnReady function is only run once. for maintainability, it might be a good idea to separate out your code so that you have a section for layout, a section for events, and a section for business logic in your code.
One thing to consider perhaps is that Sencha Touch is geared towards mobile devices that may sometimes have limited resources for you to work with. With that in mind, it might be necessary to structure your code to make it as small and efficient as possible. Your proposed code snippet may be ignoring those constraints that mobile platforms have to deal with.

anonymous functions considered harmful? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
The more I delve into javascript, the more I think about the consequences of certain design decisions and encouraged practices. In this case, I am observing anonymous functions, a feature which is not only JavaScript-provided, but I see strongly used.
I think we can all agree on the following facts:
the human mind does not deal with more than 7 plus minus two entities (Miller's law)
deep indentation is considered bad programming practice, and generally points out at design issues if you indent more than three or four levels. This extends to nested entities, and it's well presented in the python Zen entry "Flat is better than nested."
the idea of having a function name is both for reference, and for easy documentation of the task it performs. We know, or can expect, what a function called removeListEntry() does. Self-documenting, clear code is important for debugging and readability.
While anonymous functions appears to be a very nice feature, its use leads to deeply nested code design. The code is quick to write, but difficult to read. Instead of being forced to invent a named context for a functionality, and flatten your hierarchy of callable objects, it encourages a "go deep one level", pushing your brain stack and quickly overflowing the 7 +/- 2 rule. A similar concept is expressed in Alan Cooper's "About Face", quoting loosely "people don't understand hierarchies". As programmers we do understand hierarchies, but our biology still limits our grasping of deep nesting.
I'd like to hear you on this point. Should anonymous functions be considered harmful, an apparent shiny syntactic sugar which we find later on to be salt, or even rat poison ?
CW as there's no correct answer.
As I see it, the problem you're facing is not anonymous functions, rather an unwillingness to factor out functionality into useful and reusable units. Which is interesting, because it's easier to reuse functionality in languages with first-class functions (and, necessarily, anonymous functions) than in languages without.
If you see a lot of deeply nested anonymous functions in your code, I would suggest that there may be a lot of common functionality that can be factored out into named higher-order functions (i.e. functions that take or return ("build") other functions). Even "simple" transformations of existing functions should be given names if they are used often. This is just the DRY principle.
Anonymous functions are more useful functionally than they are harmful legibly. I think that if you format your code well enough, you shouldn't have a problem. I don't have a problem with it, and I'm sure I can't handle 7 elements, let alone 7 + 2 :)
Actually, hierarchies help to overcome 7+/-2 rule the same way as OOP does. When you're writing or reading a class, you read its content and nothing of outside code so you are dealing with relatively small portion of entities. When you're looking at class hierarchies, you don't look inside them, meaning then again you are dealing with small number of entities.
The same if true for nested functions. By dividing your code into multiple levels of hierarchy, you keep each level small enough for human brain to comprehend.
Closures (or anonymous functions) just help to break your code into slightly different way than OOP does but they doesn't really create any hierarchies. They are here to help you to execute your code in context of other block of code. In C++ or Java you have to create a class for that, in JavaScript function is enough. Granted, standalone class is easier to understand as it is just easier for human to look at it as at standalone block. Function seems to be much smaller in size and brain sometimes think it can comprehend it AND code around it at the same time which is usually a bad idea. But you can train your brain not to do that :)
So no, I don't think anonymous functions are at all harmful, you just have to learn to deal with them, as you learnt to deal with classes.
Amusingly, JavaScript will let you name "anonymous" functions:
function f(x) {
return function add(y) {
return x+y;
};
}
I think closures have enormous benefits which should not be overlooked. For example, Apple leverages "blocks"(closures for C) with GCD to provide really easy multithreading - you don't need to setup context structs, and can just reference variables by name since they're in scope.
I think a bigger problem with Javascript is that it doesn't have block scope(blocks in this case referring to code in braces, like an if statement). This can lead to enormous complications, forcing programmers to use unnecessary closures to get around this Javascript design limitation.
I also think anonymous functions (in latest languages often referred as closures) have great benefits and make code often more readable and shorter. I sometimes am getting really nuts when I have to work with Java (where closures aren't first class language features).
If indentation and too many encapsulated function-variables are the problem then you should refactor the code to have it more modular and readable.
Regarding java-script I think that function-variables look quite ugly and make code cluttered (the encapsulated function(...){} string makes java-script code often less readable). As an example I much prefer the closure syntax of groovy ('{}' and '->' chars).
If a function is not understandable without a name, the name is probably too long.
Use comments to explain cryptic code, don't rely on names.
Who ever came up with the idea of requiring functions to be bound to identifiers did every programmer a disservice. If you've never done functional programming and you're not familiar with and comfortable with functions being first-class values, you're not a real programmer.
In fact, to counter your own argument, I would go so far as to consider functions bound to (global) names to be harmful! Check Crockford's article about private and public members and learn more.

Categories