Model View Controller Rewrite (JavaScript)
I think it's worthwhile rewriting large amounts of code if it adds significant advantage such as cleaner and more maintainable codebase. I have taken some screenshots along the way to document how I do a rewrite.
The contextIn 2006, when I started Todoist, MochiKit was one of the better JavaScript libraries. Today MochiKit is largely forgotten and the state of the art JavaScript libraries are backbone.js, spine.js or ember.js. All of these newer libraries use the Model-View-Controller (MVC) pattern, a pattern I have written about in the past: Model View Controller rewrite in JavaScript/CoffeeScriptI will now show a series of screenshots of what the problem is and how I find a solution that makes the code simpler and more maintainable. Each project in Todoist has a counter that shows how many tasks the project holds. In the old codebase there's one creator and 7 (yes 7!) update functions:
I could rewrite this to use fewer update functions or even just one, but I could also go an extra mile to ensure that such blunders do not happen in the future. The better way to do this is to use the MVC pattern: the basic idea is that we create a counter that autoupdates itself each time the model changes. I looked at how modern libraries handled this (I was largely inspired by backbone.js ) and I began scribbling down how an API could look like:
I did not want to use backbone.js directly as I don't like the way routes work or that it's dependent on underscore (adding backbone.js and underscore would result in 2000 lines of extra code). I also think I can learn more by implementing stuff myself and I can do a customized solution that works well with my existing code. After this step I began to implement a test to see if my API made sense:
I tried to use the new code for the counter (I had two solutions, either binding it to a project object or using ProjectsModel). I tried to use them both throughout some code to see how they would behave in different contexts:
Then I set these solutions against each other - - reflecting on pros and cons of each solution:
The solution I ended up with was following:
Would love to hear about how you attack a rewrite. Happy hacking!
Code
·
Code improvement
·
Design
·
JavaScript
·
Todoist
•
27. Jan
|
|