mardi 24 février 2015

Using a callback to force commit after changes to object

I'm writing a javascript module to manage a group of objects/entities and requires users to commit changes after performing certain update-like methods on an object.


One way of doing this would be to have a certain commit() method, like this:



// myApp.js
module.modifyMethodOne(object);
module.modifyMethodTwo(object);
module.commit(object);


However, I see two problems with this approach:



  1. A user has to never forget to call commit

  2. The module needs to do all sorts of checks to see if an object has been modified / if changes have been committed. This makes the code more complex and adds slight overhead. As this may be happening a few hundred times per second I try to keep overhead to a minimum wherever I can in this module.


Even when this approach doesn't seem too bad, I came up with something like this proposed solution:



// myApp.js
module.updateObject(object, function(UpdateHelper) {
UpdateHelper.modifyMethodOne(object);
UpdateHelper.modifyMethodTwo(object);
});

// module.js
module = {
this.commit = function() { // commit changes }

this.UpdateHelper = {
this.modifyMethodOne = function(object) { // do stuff }
this.modifyMethodTwo = function(object) { // do stuff }
}

this.updateObject = function(object, callback) {
callback(this.UpdateHelper);
this.commit();
}
}


Here, module.updateObject would just run the callback first and, when that is done, automatically call commit. All methods that would change an object in a way that would require a commit are moved into an UpdateHelper within the module. This way a user can never access them outside of module.updateObject, thus:



  1. Forcing commit after running modifying methods.

  2. Removing all references to whether an object is currently modified or not. All modifying happens in clear blocks of code.


My questions are:



  1. Is there something clearly wrong with this approach I am missing? What would be the disadvantages?

  2. How do I find out more about this approach? Is there a name for this? Where has it been used before?


P.S.: Mods, could someone perhaps rephrase my question? I feel like my question is constructive but I have trouble phrasing it properly (partly because I am missing the correct lingo to do this, hence why I am asking a question I can't google).


Edit:


To clarify I updated the code samples with another method so it is clear how the interface would look like in case of multiple changes to an object and I added the internals of the module to clarify what is going on in the proposed solution.


I would like to emphasize that the question is about the second solution I proposed.


What are the design pitfalls with this implementation? How is this pattern called?


Aucun commentaire:

Enregistrer un commentaire