I come from a background in Haskell. I'm very used to getting things done with recursive functions and the typical higher-order functions (folds, maps, filters, etc) and composing functions together. I'm developing in node.js now, and I'm seriously tempted to write my own modules implementing these functions so I can use them in my code in a way that makes sense to me.
My question is, basically: is Javascript set up to handle this type of burden? I understand that the aforementioned recursive functions can be easily refactored into iterative ones, but often times I find myself calling a lot of functions within functions, and I don't know if Javascript can handle this type of thing well. I know that things like Underscore exist and implement some FP principles, but my question basically boils down to: is it good practice to program functionally in Javascript? If not, why not?
I also apologize if this question is a little too soft for SO, but I don't want to start putting together my own tool set if it's just going to break everything once it gets too large.
In my opinion, the short answer to your question is yes -- applying functional programming principles is viable in Javascript! (I believe that this is also true for most other languages -- there's usually something to be gained from applying FP principles).
Here's an example of a functional parser combinator library I built in Javascript. (And here it is in action). It was important to be functional because: 1) it allows me to build parsers by composition, which means I can build and test small parsers independently, then put them together and have confidence that the behavior will be the same, and 2) it makes backtracking super easy to get right (which is important because the choice operator backtracks when an alternative fails).
So these are FP principles (note the absence of recursion, folds, maps, and filters from this list) that I found extremely useful in building my library:
avoiding mutable state
pure functions (i.e. output depends only on input)
composition: building complex apps by gluing together simple pieces
It's usually quite easy and pleasant to apply these in Javascript because of Javascript's support for:
first-class functions
anonymous functions
lexical closures
but here are some things to watch out for:
lack of popular library of efficient functional data structures
lack of tail-call optimization (at least at the moment)
partial application is more syntax-heavy than in Haskell
lots of popular libraries are not especially functional
the DOM is not functional (by design)
However, your last comment -- "I don't want to start putting together my own tool set if it's just going to break everything once it gets too large" -- is a good one. This is basically a problem for every approach, and I can't tell you whether FP in Javascript will be more problematic than "mainstream" techniques when things get too large. But I can tell you that in my experience, FP in Javascript helps me to prevent things from getting too large.
Related
I have some procedural javascript code that I have written for an open-source application and I'd Like to refactor it into OOP and since I have very little experience with javascript frameworks I have trouble finding a one suitable for my needs, though I haven't tried anything yet, I just read about AngularJS, Backbone.js and Knockout.
I want to structure the code, because, at the moment, there's a mess, global variables and functions scattered around.
I have to mention that all the business logic is handled at the server level, so the client-side code handles just the UI using the data it receives or requests from the server.
The code can be found here:
https://github.com/paullik/webchat/blob/asp.net/webchat/Static/Js/chat.js
Do you have any suggestions?
Object-Oriented JavaScript is not necessarily the answer to all your
problems.
My advice is to be careful the choice you pick on this topic.
In practice, OO-JS can add more complexity to your code for the sake of trying to be more like traditional object-oriented languages. As you probably know, JS is unique.
It is important to know that there are Design Patterns that will structure your code and keep implementation light and flexible.
It is Design Patterns that I see structuring advanced JS
implementations, not OO. To paraphrase Axel Rauchmeyer - "Object
Oriented methodology does not fit into basic JavaScript syntax, it is
a twisted and contorted implementation, and JS is far more expressive
with out it."
The root of this analysis boils down to the fact that JS has no class. In essence, since everything is an object, you already have object-oriented variables and functions. Thus the problem is slightly different than the one found in compiled languages (C/Java).
What Design Patterns are there for JavaScript?
An excellent resource to check is Addy O' Somani and Essential Design Patterns.
He wrote this book on Design Patterns in JavaScript.
But there is more... much more.
A. require.js - There is a way to load modules of JS code in a very impressive way.
These are generally called a module loaders, and are widely considered the future of loading js files since they optimize performance at runtime. yepnope and others exist. Keep this in mind if you are loading more than a few js files. (moved to top by request).
B. MVC - There are dozens of Model View Controller frameworks to help you structure code.
It is a Pattern, but may be unreasonable for your purposes. You mentioned backbone, knockout and angular... Yes. These can do the trick for you, but I would be concerned that they might be 1) high learning-curve, and 2) overkill for your environment.
C. Namespace or Module Pattern. Are probably the most important for your needs.
To solve global variables just wrap them in a namespace and reference that.
These are very good patterns that give rise to module loaders.
D. Closure - You mentioned OO JS. On piece of this that is useful is the notion of closures to provide yourself with... private members. At first this is a cryptic idea, but after you recognize the pattern, it is trivial practice.
E. Custom Events - It becomes very important to not use hard references between objects. Example: AnotherObject.member; This is because it will tightly couple the two objects together and make both of them inflexible to change. To solve this, trigger and listen to events. In traditional Design Patterns this is the Observer. In JS it is called PubSub.
F. The Callback - The callback pattern is what enabled AJAX and it is revolutionizing development in terms of Window 8, Firefox OS, and Node.js - because of something called non-blocking-io. Very important.
Do not be afraid. This is the direction to go for long-term and advanced JavaScript implementations.
Once you recognize the patterns, it is down hill from there.
Hope this helps.
I'm trying to make a large (~10K lines) javascript code base more maintainable. Pretty much all of the code is contained in one massive class. I want to do some refactoring, but I don't want to completely rewrite the code.
I have two ideas for how to re-organize the code, but I'm not sure which one is best. (I'm very open to other ideas too) What do you think about each of these approaches? How would you decide which is best?
Idea 1 – Decouple markup from business logic.
We have a somewhat complicated set of rules for what and how things should be displayed to users. This approach would split that into "What do we display?" and "How do we display it?"
Idea 2 – Break apart separate components into their own class.
There are several somewhat disjoint components in this code. If this code base were Facebook's – this approach would involve pulling apart the code for photos and the newsfeed.
If we are talking about Javascript, chances are you are using it in a browser. That being the case, most of your code is about views. A MVC pattern won't help you that much because most of your code will handle views.
Remember Javascript is not class based but prototype based. It is also functional. Functional programming excels in manipulating data. Try using the functional aspects of Javascript when doing so.
I suggest you try to split your project into a common framework for retrieving, manipulating and pushing data for all your views; and then splitting your view code into components.
If we are talking about 10k lines, you had to develop some sort of backbone to handle common tasks. If you don't use jQuery, after reorganizing your code, compare your implementation to jQuery's solutions and if you see an improvement, you can start refactoring inside your code.
If you have a chance take a look at Ext JS source code: http://www.sencha.com/products/extjs/download/ext-js-4.0.2a/213
To answer your question: Yes.
I'm not sure what you mean by 'refactor, but not rewrite'. Refactoring code shouldn't change external behaviour, but refactoring will certainly involve some sort of moving code around and whatnot.
Generally, separating the markup from the business logic is a good idea: it's following the model-view-controller pattern, effectively making your markup code 'view' code, and your business logic 'controller' code.
Breaking your code apart into separate components is likewise a good idea. Breaking your code into individual classes supports the idea of having classes with high cohesion and low coupling, and generally moves you towards more SOLID object-oriented design.
If you're asking which one will be more beneficial, that's something that can't be evaluated by the SO community, that's something you have to decide.
Oversimplified, you need to first figure out, in technical terms, what your desired architecture definition is. What is your main file (high-level) responsible for, what your low-scale modules are, and how they will be communicating (directly or vicariously). Should you abstract away the external frameworks at this stage? I am a fan of EDA's (Event-Driven Architectures), Fractal Hierarchies, and Mediation (Mediator Pattern), but many other definitions exist. Choose one that suits the scale of your project and can scale out.
Derive a blueprint and procedure for how you'll get your architecture from A to B. You may want an Abstract Procedure to entail a convention. For instance, "Redundancies: use Decorators" and so on. Do you favor composition over inheritance? However, you should have a Concrete Procedure for how to execute your game plan. E.g: "Replace references to 'X' with Mediator", "Let Save() dispatch a signal on the 'validation' channel", etc.
Make sure you're reflecting your views precisely with your JavaScript compositions. Because it's always a pain to balance unparallel hierarchies -- this ALWAYS leads to entropy. And try to embrace the (noted above) SOLID principles.
I wished to elaborate more, but I hope this is a good start for you.
I'm seeing a rise in the number of projects online that require additional "short" syntax to generate underlying code (commonly HTML and JS), and every time I see another pop up I wonder if I'm missing something.
Surely the additional time taken to learn and remember these shortcodes is lost when passing projects between different team members (designers et al) who then have to relearn basic languages such as HTML and JS?
Point in question: YAML being used for generating templates, and projects (such as) CoffeeScript used to generate Javascript. I'm just wondering if other Stackoverflow folk think that there's major benefits to this granular level of abstraction, or if there's a feeling that these types of projects have any lifespan, considering the improvements in the base technologies (I'm thinking HTML5 / CSS / JQuery) here. Have markup languages not evolved enough to really warrant these?
Realise this isn't really a question as such, but would be interested to hear the community viewpoint. I'm sure there are genuinely good reasons for these types of projects when creating self generating code, but outside of that, I'm puzzled - with many folks using them day to day. Is this a bandwagon worth jumping on?
Personally I don't think that it's worth it as most things you can do in javascript are already simplified by libraries such as jQuery. As far as their lifespan goes it's hard to tell. However, as long as you know javascript, and you understand the code output, moving to a new project that isn't using CoffeeScript for example is a simple matter of taking the output code with you.
Any sufficiently complicated program contains an implementation of Lisp.
This is the ideology that Lisp and friends promote over many years. Basically, you're discouraged to code any application logic in a "raw" language. Raw languages are universal and low level, so your logic quickly gets verbose and contaminated with lots of code needed to support the language itself.
Instead, create a DSL that suits your application best and code your logic, and nothing but the logic, in this DSL. Hide all nasty language details behind the DSL. This makes the logic much easier to improve and support.
On the other side, things like Coffescript, Groovy etc are IMO the wrong way to go. They are basically trying to create new universal languages but with a "better" syntax, however, this doesn't solve the fundamental problem - these languages still describe abstract calculations rather than your problem domain. A more productive way is to have a very basic underlying language and a well-developed macro facility that would simplify creating DLSs. This is how lisp itself works, another example of this approach is Haxe/Neko.
In my opinion I prefer jQuery for writing short JS instructions and prevent everyone from bloating the final product. I don't like css frameworks because we are building huge portals and you don't always need all of the stuff hidden inside these. I prefer writing modular css based on some common rules like using clearfix for clearing an using a css reset. :)
We have a CMS built on Java and it has Mozilla Rhino for the server side JS. At the moment the JS code base is small but growing. Before it is too late and code has become a horrible mess I want to introduce some best practices and coding style.
Obviously the name space control is pretty important. But how about other best practices - especially for Java programmers?
Here's some tips from the front lines:
Like Java, use docblocks in Doxygen/JsDoc style for functions
Unit test. Personally like JsTestDriver, as it can be executed automatically from CI server too.
Use JSLint. It will nitpick about bad code
Consider using Google Closure Compiler. It will nitpick about code like JSLint, but it can be helpful for spotting poor doc blocks etc.
Make sure everyone on your team understands how closures work. Otherwise it'll lead to headaches
As you mention, namespaces are important especially if you want your code to work nice with other JS libraries (var myns = myns || {};)
Personally I find using a library which provides OOP helpers like classes etc. helpful. You could use prototypal inheritance but it's often a bit trickier that way.
As Douglas Crockford likes to say, JavaScript is the worlds most misunderstood programming language. Though many people don't know it, there is a right way to code in JavaScript. I have no doubt that if you let Java developers start coding before understanding how to write good JavaScript you will run into serious trouble.
The first thing to do would be to make sure everyone has read Mozilla's excellent article, A re-introduction to JavaScript (https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript). One of the biggest problems with JavaScript is that there are many ways to do most common tasks, and this article should get people on the same page. Another essential reference is Douglas Crockford's work, including JavaScript: The Good Parts.
One other thing that gets a lot of Java/C++ programmers is that JavaScript uses function scope NOT block scope. This can cause some very tricky problems. There's a great article about this issue at A List Apart called Binding in JavaScript.
To summarize the major issues talked about in the above resources, the most crucial differences to learn are
how to write object oriented code using prototypal inheritance (vs.class based inheritance)
how to use closures and lambdas
how to utilize the power of dynamic objects
how to write function-scoped code
Since you have a JS engine in Java, make it a habit to write unit tests for your JS code. Select a coding style and apply it vigorously. If possible, use tools to check that the code submits to the coding style.
I am looking get to grips with functional programming concepts.
I've used Javascript for many years for client side scripting in web applications and apart from using prototypes it was all simple DOM manipulation, input validation etc.
Of late, I have often read that Javascript is one of the languages that supports functional programming.
With my familiarity and experience with Javascript, my preference is to use it to learn functional programming. I expect I would be able to concentrate more on the main functional concepts and not get bogged down or distracted by a completely new syntax.
So in summary, is Javascript a good choice to learn functional programming concepts? What capabilities in Javascript are relevant/support functional programming?
JavaScript supports first class functions. See Use functional programming techniques to write elegant JavaScript.
Higher Order Javascript is a great way to get familiar with the functional aspects of javascript. It's also a relatively short read in case you want to get your feet wet without diving into a larger book.
I would say that although you can quickly grasp some functional programming concepts with JavaScript, using JavaScript consistently like a functional programming language is not a common practice. At least not obviously common. Most people don't post tutorials that pinpoint how to do functional programming with JavaScript -- the one marxidad pointed out is actually a pretty decent example, but you won't find a lot of that. The functional aspects are not often apparent, just like when people use closures in JavaScript, but are unaware that they are doing it.
The idea that you would pass two functions through as arguments to a third function, and then have the return value be some execution related to the first two functions is an advanced technique that almost always appears only in the core of full-blown libraries like jQuery. Self executing anonymous functions and the like have gained ground, but are still not used consistently. The majority of tutorials often focus instead on JavaScript's OO capabilities, like how to create properties and methods, scope, access control and also how to use the prototype property of constructors. Honestly, if functional programming is what you want, then I would choose a language known strictly for this capability.
I don't remember who said it, but javascript has been called "Scheme with Algol syntax". So for learning Scheme/Lisp, Javascript isn't a bad start. Note though that functional languages like Lisp are quite different from pure functional languages, such as Haskell.
Apart from "first-class functions" (Meaning that functions are values, that can be assigned to variables), lexical scope is also an inherent part of what makes a functional language.
Higher Order Javascript and The Little Javascripter has been mentioned already. They are both excellent texts. In addition, Higher Order Programming in Javascript may be an easier start.
Although javascript supports FP to some degree, it does not directly encourage it. That's why projects like Oliver Steele's Functional exist, to fill in the gaps. So I wouldn't recommend it for learning FP. Check out F# instead.
I would recommend reading The Little Schemer, which is a fairly slim book about recursion and is a good introduction to the functional style. Whilst it's focused on Scheme it can easily be applied to JavaScript, see http://javascript.crockford.com/little.html. I found it really helpful in my javascript development, although it gets quite tricky towards the end.
Javascript is a multi-paradigm language. If your goal is to learn functional language concepts, try starting with a pure functional language like OCaml or Haskell.
Also, Eloquent JavaScript: Functional Programming chapter.