Resource for Refactoring tips geared towards JavaScript - javascript

I'd like to start a discussion on the best resources for refactoring tips, with an eye towards Front-End JavaScript refactoring.
A friend whose opinion I respect suggests this book, though it uses examples in Java. I understand that the principles of OO refactoring should translate to another language.
Let's talk about refactoring in general and JS refactoring specifically.

Check out Martin's Clean Code for some inspiration. The examples are in Java but the ideas should translate to JavaScript as well.
In order to refactor properly, you'll need to test your code well as having proper tests in place is a prerequisite for it. Try finding testing tools that give you code coverage as this will be extremely valuable.
In case your code hasn't been tested yet you can think testing as a method of learning. You write tests to prove or disprove your assumptions about it. Once you are done and covered it adequately you should be able to refactor the code using various patterns provided.
As Ira mentioned having a tool to detect clones may be valuable. That's definitely one way to look at it.
I think that often having proper perspective is half the solution. If you can state your design in clear terms, you'll end up with better results. Try not to over-engineer it too much by applying every possible pattern you find. :)

Not specifically a refactoring tool, but a tool to detect the number one smell in code: our CloneDR automatically finds duplicated code (copy/paste/edit) and shows you the precise locations and a reasonable abstraction of each clone. You have to resolve the clones by hand, but knowing where they are and having been provided that first cut at an abstraction, is a big help.
EDIT: This is directly a resource for refactoring of Java and JavaScript code. CloneDR works for both of them, using langauge-precise parsing to give precise analysis of clones.
You can see sample clone detection results on Google's Javascript Closure package.

Related

Removing jQuery for performance reasons justified?

I am on a new project and our job is to rewrite an e-commerce website that is having performance problems on mobile devices.
We are re-writing the javascript based on a more object-oriented/modular architecture which I think is great! However my team lead said that we should remove all the jQuery calls and replace with javascript like so domElem.querySelectorAll(query) , which has better performance. I understand jQuery does some kind of caching in the background which can create memory issues.
I am a little sceptical of this, firstly because it seems like a case of 'premature optimization', that is, we should find the bottle-necks first before we re-write anything. And secondly I haven't found anything on the internet that says that jQuery has significant performance problems.
The current website does have a lot of overlapping dom branch queries which I think creates a lot of redundancy. That is there is too much querying happening, and on our new architectual approach we are restricting our object/module to fewer dom queries and more targeted dom queries which is great. This does need to be re-written.
But whether or not we use domElem.querySelector(query) or $(domElem).find(query), I can't see there as being much of a difference. Is my thinking right?
Some tests are done here (check other revisions as well). Good detailed discussion is done here over pros and cons of using jquery over javascript.
Also want to point out that jquery doesn't do any caching of selectors.
The thing we often forget because of using Javascript frameworks all the time is that jQuery is not a framework.
Obviously, if you do the exact same one-operator action using the jQuery '$' object and using a direct DOM method like getElementById, the latter will be noticeably faster as jQuery itself is written in Javascript and does a lot of background stuff.
However, nothing (except code readability) prevents you, as a developer, from combining jQuery with plain Javascript: using plain Javascript wherever possible and only using jQuery functions that provide complex functionality and take some time to write and optimize from scratch. There are a lot of those in jQuery: providing browser-independent css, serializing object and doing lots of other cool stuff.
It depends on the application but usually performance troubles are related to badly-designed algorithms, not the use of jQuery.
In any case, if your application does a lot of DOM-manipulation, it may be worthwhile to re-write it using plain Javascript and test. Keep the library, just don't use it for simple operations you can easily write without it.
If your application is heavily-reliant on jQuery functions with complex functionality, removing it is out of the question.
I myself use this combined approach: everything simple written in Javascript with jQuery functions for stuff that is difficult to implement.
Also, a good place to dig around if the app has troubles with performance is the DOM-manipulation. Those operations are very heavy compared to almost everything else in Javascript. You may be able to cut down on time by rolling several operations into one, building finished objects with one constructor, instead of creating empty ones and assigning properties one-by-one, etc.
Sorry, if the answer is a bit vague but it's difficult to be precise in this case without seeing the code and running tests.
Let me quote Uncle Bob about this discussion "Architecture is about intent, we have made it about frameworks and details"
Premature optimizations needs to be considered carefully.
They often result architectural decisions that are not easily revertible.
They introduce code optimizations that are usually specific to the problems they solve, which makes the code less abstract thus hard to
maintain, and more complicated thus prone to more bugs.
They tend to be prejudice and not objective, sometimes without any real comparison to other alternatives.
The problems they are trying to solve tends to be overestimated, to the degree of non-existent.
I'm not a big expert on Web development but if possible, you should always push this kind of decisions to the end by separation of concerns, and good abstraction.
For example over the parts that generate the java-script code you can have an abstraction of JavaScriptWriter, and use different frameworks. This way you can use JQuery at the beginning, test the system and only then replace parts you know to be inefficient.

Generating modern js-based rich client from server side?

I am working on a intra-net project, which uses javascript for client side effects/widgets, like tree, grid, dragging. We are thinking about to use jquery/backbone plus some jquery ui.
The problem is, with great flexibility of jquery/backbone, our low experienced developers are almost certained to make code MESSY. And I hate that.
To reduce the chance they can make code messy, I am going to build a server-side program to parse xml (those developer will write xml instead of javascript when possible) and generate javascript at runtime. By doing this, I can force restriction on the xml. And xml tends to be less messy.
But before jumping into that, I want to ask is there any similar existing framework? Preferably the javascript generated also make use of model/view/controller pattern.
Or what else can I do to prevent the project from being messy?
ps: I want to educate the developer. But that is a long term job. Not really helpful for current project.
Thank you guys/girls.
Alright, a terrible idea I think. So besides training my developers (for long term), what else can I do? Especially in short term because the project is rolling on?
I like your goal but I think that trying to enforce coding standards in a programmatic way is over-solutionising the problem. The following steps help to steer you in the right direction though:
Use a version control system such as SVN or Git. Not only does this allow you to pinpoint who is messing up your code and educate them, but it gives you the option to roll back changes that completely break your project. It shouldn't be seen as a "blaming" mechanism, but is certainly a reliable way to identify the culprit. You may also find that your developers are less likely to commit code that isn't up to scratch after they realise their work is open to such scrutiny.
Documentation - and I don't necessarily mean having a 300 page wiki on how your project is organised and how functions should be written. But even something as simple as commenting every function will often encourage others to do the same. The important thing is that the developer sees the standard of work they are expected to deliver in your work. Developers with potential will take their cues from you.
Paired programming - get into the habit of sitting with your developers while they code. Not 100% of the time, but often enough that you are aware of their strengths and weaknesses. Teach them the way you want them to code.
If all else fails, resort to tools that help developers with their standards, such as the Resharper plugin for Visual Studio. While this is primarily designed for C# usage, it also provides code hints etc. for Javascript that will help inexperienced developers adopt a set of practices that should improve the readability of their code.
I don't think there is any substitute for a good tutor, and providing any sort of automated solution is likely to cause a lot of headaches for you without ever really improving the skills of those you are hoping to teach.

unknown JS obfuscation tool

I have seen many obfuscated codes, however, recently I came across this code: paste2.org. The latter uses arguments.callee.toString().replace(/[\s\'\"\)\}\]\[\;\.\{\(]/g, "").length; to prevent programmer from simply replacing eval() with document.write or something similar. I was wondering how do I obfuscate the code this way myself? Is there any tool for that? (p.s. note that arguments.callee.toString().repl[..] is called two times) Going deeper. Even when you get trough this stage, the code is complete mess. Variable/function names are randomized, while the strings are complete mess and look something like this: $(kj49f+4kd+fgdff+hgd25+fh2fg5+adb5) which evaluates to simply $('.wrapper .foo[name"bar"]'). What was used to do that? I have recently came across jscrambler.com which is paid JS obfuscation service. I was wondering if it is the thing that was used to obfuscate the code.
After few weeks of research, I've discovered that the program used to obfuscate the code in example is http://jscrambler.com/. This is actually a commercial software. Do I recommend it? Hm. Not sure, as I am writing this comment (May 21, 2011), it is still in pretty early stage of development & I've faced multiple issues. Though, they are quite quick to sort them out once reported.

Learning JavaScript for a total non-programmer

I code CSS/XHTML like it should be my mother language, and I do write valid, semantic code following guidelines of accessibility and such.
But I want to learn Unobtrusive JavaScripting, but with a total non-programmer brain I need some motivation / tips / etc., like what's the best way to learn it, and how long does it take/did it take you before you could feel the power of knowledge? :)
PS: I do have an understanding on how JavaScript works and changes the DOM etc.. I think it's more about learning the syntax by head instead of having to look it up.
See also:
Suggestions for someone starting javascript programming.
Just use it. Really, the more time you spend reading and writing the language, the more natural it becomes. Use Firebug or an equivalent console to test short ideas; take an existing web page and wire up events interactively from the command line, get used to the idea of writing behavioral code as a separate process from writing markup.
If you want a good book, i can recommend the excellent jQuery in Action - yes, it's targeted at jQuery users, but the concepts apply regardless of your choice in libraries.
Motivation, sorry can't help there.
Syntax is learned by rote. The rules are simple, and reasonably consistent, so in truth syntax isn't that hard.
What you conflate with syntax are likely the other aspects like what properties are available on what objects, what functions to call, what does your framework provide. That, again, is basically rote memorization.
Many frameworks add a little bit of syntax through clever use of the JavaScript syntax, and you'll need to learn those as well.
But when it all comes down to it, the only way to learn this stuff is to use it.
You can't read about it, you have to do it.
Find an issue that you want to work on, a feature for your site or whatever, and attack that.
If you find a tutorial or whatever on line that does what you want, TYPE IN THE CODE, don't cut and paste it. As you type it in, question every symbol or character, try to understand why you're typing what you are typing.
Make an effort to change things, even if it's just variable names, because then you get a better idea of what things are being used for, and how they're referenced. It also lets you focus on a small part of the larger program.
If you're changing the "window1" variable to "myWindow", then at least you can look at the code as "blah blah blah window1 blah blah window1" without having to understand all of it.
Start small, don't worry about "doing it right", etc. so much as just being successful. If the way it's done doesn't bother you, then you're good. If you look at it and go "That's not quite right" because you learned something later after you started, then go back and clean it up.
At this stage, function is greater than form. Much of the form simply comes from experience.
Depends on what you want to do. Are you a successful web designer who's considering getting into the development side? Forge ahead, but tread cautiously. JavaScript can be easy to start with, but it can get ugly very quickly. And it's very different from any server-side language (including Java). Some of your JavaScript skills will translate to other languages, (conditional and control-flow operators, for example). But some things are unique to JavaScript and will require some relearning if you move to another language.
Also, some things in JavaScript won't completely make sense unless you've done object-oriented development; even though JavaScript is "prototype-based" rather than strictly object-oriented, without the OO concepts to relate to, the prototyping system may be difficult to understand. The typing system also may not make much sense if you don't have a lot of experience with different typing systems (static vs. dynamic, explicit vs. implicit).
Use a good framework like jQuery or YUI, but be sure to understand what's going on behind the scenes. Shog9's suggestion to use FireBug is a good one, too. It will show you what's going on (without having to do a lot of alert() statements in your code).
Your HTML DOM and CSS experience will help some, but only in the sense of understanding what the JavaScript is trying to do. Having written HTML and CSS by hand won't help you learn to write JavaScript; HTML and CSS are document markup languages, not imperative programming languages.
So go for it, but don't expect it to be easy. You may make a lot of quick progress, only to find that you're not as far along as you think, and that things don't work the way the appear to. But with enough effort and research you'll probably get there.
I think learning Javascript is a great idea if you are all ready doing HTML and CSS. Javascript is a cool, but quirky language. Most people that use don't really know how to write good JS code. I highly recommend watching Douglas Crockford video, see http://video.yahoo.com/watch/111593
They will give the real scoop on Javascript.
I've recommended JavaScript: The Good Parts before (and can't recommend it highly enough), but if you're new to programming I suggest starting with Head First JavaScript.
(source: oreilly.com)
I think you've got an abundance of great answers and resources already, but I'd like to chime in, too, since I've seen a couple of jQuery recommendations:
I love jQuery, too, and use it nearly daily. That said, for a beginner, I would recommend that you be comfortable with javascript proper first before diving into jQuery. Being comfortable with the syntax, variables, scope, and at least some DOM concepts will greatly improve your understanding of how to do what you want with jQuery. If you try to speed too quickly past the fundamentals, you'll definitely get stuck on some common misunderstanding that jQuery won't be able to help you with.
http://codeavengers.com level 1 JavaScript is great for the complete beginner. I created the courses and have had lots of great feedback from beginners who have found my course a fun and effective way to learn JavaScript.

Is there a resource to help convert Prototype JavaScript to jQuery?

I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio.
I understand that we can use the jQuery.noConflict to run it alongside Prototype, but we would like to avoid having users need to download both libraries to use our website.
So, is there a good resource that can help us move old scripts from Prototype to jQuery?
I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed.
While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over all your scripts is going to be many many hours of work. The cost of your users downloading an extra 30kb of scripts is going to be roughly 0.3 seconds. Perhaps try to slowly phase out Prototype and only refactor your existing pages when a) you have to, or b) if you've got nothing better to do.
Falkayn,
There is no automated process available for conversion of JavaScipt code written against one JS library to another one. Moreover there cannot be one. Different libraries implement different proramming models as well as they arrange their APIs in different manner.
So, before you have found a solution to your problem now ask yourself a question: Am I going to convert my jQuery code once another even "cooler" "X-type" JavaScript library became available?
If your answer is no, take your time and convert the code manually no mater how long will it take. In case you answer "yes" don't convert the code at all.
So it goes.
Thanks guys for your input. I was looking for more of a syntax comparison than anything automated, but nickf makes a good point in that the real cost need not be too great. We only used Prototype on a few pages that really needed a high level of interactivity, so as long as mind out Ps and Qs it should not hurt to use jQuery everywhere else.

Categories

Resources