Friday, 12 April 2013

Planning Humanity's Future

Stack Exchange Q&A site proposal: Humanity's Future

A new Q&A website called Humanity's Future has been proposed on the much famed StackExchange collection of websites. It's currently in the definition stage, which means more questions need to be asked. The website focuses on the state of the world and the challenges we are leaving to our children. Planning the future of humanity's technological, political and spiritual direction. It currently requires more followers, especially experts. Please show your support and follow this link.

http://area51.stackexchange.com/proposals/53713/humanitys-future

You may find the answers to be about whether the questions are good, which might seem strange. It's because the site is in the proposal definition stage, and isn't actually live yet.

Saturday, 6 April 2013

Javascript Folding Pattern

There are many patterns for arranging code in Javascript, such as the Module Pattern, the Revealing Module Pattern and the Prototype Pattern. Most programmers adopt their own style based on these. After creating a project with a fairly large and interconnected Javascript code base, I slowly derived this pattern.

The Folding Pattern is acutely aware that Javascript is a functional/imperative object-oriented language, which employs object prototypes rather than classes. It allows for the concept of private members, which is practically a requirement for large projects (to combat accidental mangling of an object, by other coders or even yourself). By sticking to the rigorous formatting you can create very large objects which are easy to maintain and navigate. (Especially if you use a development environment which has code folding.)

Here are two templates (copy them and alter as required) of how to use the Folding Pattern, one of a singleton object and the other a type object:

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Folding Pattern - templates
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(function (global) {
   "use strict";

   // Create a name-space in the global space.
   var foldingPattern = global.foldingPattern = global.foldingPattern || {};

   //====================================
   // The template for making a singleton.
   //====================================
   foldingPattern.singletonTemplate = (function () {
       var N = {}, // Enclosed (private) members are here.
           X = {}; // Exposed (public) members are here.

       (function ENCLOSED_FIELDS() {
           N.myField = 0;
       }());

       (function ENCLOSED_METHODS() {
           N.myMethod = function () {
               N.myField++;
           };
       }());

       (function EXPOSED_PROPERTIES() {
           Object.defineProperty(X, 'myProperty', {
               get: function () {
                   return N.myField;
               }
           });
       }());

       (function EXPOSED_METHODS() {
           X.myMethod = N.myMethod;
       }());

       // Return the exposed object instance.
       return X;
   }());
   //====================================


   //====================================
   // The template for making a type.
   //====================================
   // This function is used to segregate the components of the type.
   (function () {
       // Here is the constructor section.
       var thisType = foldingPattern.TypeTemplate = function () {
           var N = {}, // Enclosed (private) members are here.
               X = this; // Exposed (public) members are here.

           (function ENCLOSED_FIELDS() {
               N.myField1 = 0;
           }());

           (function EXPOSED_FIELDS() {
               X.myField2 = 0;
           }());

           // The properties below have access to the enclosed fields.
           // Careful with functions exposed within the closure of the
// constructor, each new instance will have it's own copy.
           (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
               Object.defineProperty(X, 'myProperty1', {
                   get: function () {
                       return N.myField1;
                   },
                   set: function (value) {
                       N.myField1 = value;
                   }
               });
           }());
       };

       // Here is the prototype section.
       (function PROTOTYPE() {
           var P = thisType.prototype;

           (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
               Object.defineProperty(P, 'myProperty2', {
                   get: function () {
                       return this.myField2;
                   }
               });
           }());

           (function EXPOSED_METHODS() {
               P.myMethod = function () {
                   return this.myProperty1 + this.myField2;
               };
           }());
       }());
   }());
   //====================================

}(this));
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Here are two examples of using the templates:


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Folding Pattern - examples
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(function (global) {
   "use strict";

   var foldingPattern = global.foldingPattern = global.foldingPattern || {};

   //====================================
   // An example of making a singleton.
   //====================================
   foldingPattern.singletonExample = (function () {
       var N = {}, // Enclosed (private) members are here.
           X = {}; // Exposed (public) members are here.

       (function ENCLOSED_FIELDS() {
           N.toggle = false;
           N.text = '';
           N.count = 0;
           N.numbers = [1, 2, 3];
       }());

       (function ENCLOSED_METHODS() {
           // An enclosed instance method.
           N.tweak = function () {
               N.toggle = !N.toggle;
               if (N.toggle) {
                   X.count++;
               }
               N.incrementNumbersByCount();
               N.text = 'tweaked';
           };

           // An enclosed instance method that references exposed members.
           N.incrementNumbersByCount = function () {
               var i;
               for (i = 0; i < X.numbers.length; i++) {
                   X.numbers[i] += X.count;
               }
           };
       }());

       (function EXPOSED_PROPERTIES() {
           Object.defineProperty(X, 'numberCount', {
               get: function () {
                   return this.numbers.length;
               }
           });

           Object.defineProperty(X, 'count', {
               get: function () {
                   return N.count;
               }
           });

           Object.defineProperty(X, 'numbers', {
               get: function () {
                   return N.numbers;
               }
           });
       }());

       (function EXPOSED_METHODS() {
           // Expose an enclosed function.
           X.tweak = N.tweak;
       }());

       // Return the exposed object instance.
       return X;
   }());
   //====================================


   //====================================
   // An example of making a type.
   //====================================
   // This function is used to segregate the components of the type.
   (function () {
       // Here is the constructor section.
       var thisType = foldingPattern.TypeExample = function () {
           var N = {}, // Enclosed (private) members are here.
               X = this; // Exposed (public) members are here.

           (function ENCLOSED_FIELDS() {
               N.toggle = false;
               N.text = '';
           }());

           (function EXPOSED_FIELDS() {
               X.count = 0;
               X.numbers = [1, 2, 3];
           }());

           // The properties below have access to the enclosed fields.
           // Careful with functions exposed within the closure of the
// constructor, each new instance will have it's own copy.
           (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
               Object.defineProperty(X, 'toggle', {
                   get: function () {
                       var before = N.toggle;
                       N.toggle = !N.toggle;
                       return before;
                   }
               });

               Object.defineProperty(X, 'text', {
                   get: function () {
                       return N.text;
                   },
                   set: function (value) {
                       N.text = value;
                   }
               });
           }());
       };

       // Here is the prototype section.
       (function PROTOTYPE() {
           var P = thisType.prototype;

           (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
               Object.defineProperty(P, 'numberLength', {
                   get: function () {
                       return this.numbers.length;
                   }
               });
           }());

           (function EXPOSED_METHODS() {
               P.incrementNumbersByCount = function () {
                   var i;
                   for (i = 0; i < this.numbers.length; i++) {
                       this.numbers[i] += this.count;
                   }
               };
               P.tweak = function () {
                   if (this.toggle) {
                       this.count++;
                   }
                   this.text = 'tweaked';
               };
           }());
       }());

   }());
   //====================================

}(this));
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code is completely free to use by anybody. It is held under the Do What You Want To Public License: http://tinyurl.com/DWYWTPL

Monday, 18 March 2013

Fickle - variables with attached events (in Java)

In programming a personal project I came across the requirement to have collections of objects that all have access to the same value. Another related requirement was that if the value changed then those other classes may have to reconfigure themselves (a knock-on effect due to that original value changing). The obvious answer was to employ an event driven design.
I created a class to handle these requirements in a generic way. I thought of this new "value class" as containing a capricious value, and so called it Fickle, which is a parameterized class. It is not synchronised, so beware when multithreading.

Here is the code:
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;

public class Fickle<T>
{
    private T _value;
    private final Set<OnChangeListener<T>> _listeners;

    public Fickle(final T value)
    {
        _value = value;
        _listeners = Collections.newSetFromMap(
         new WeakHashMap<OnChangeListener<T>, Boolean>());
    }

    public void addOnChangeListener(final OnChangeListener<T> listener)
    {
        _listeners.add(listener);
    }

    public void setValue(final T newValue)
    {
        _value = newValue;
        for (OnChangeListener<T> l : _listeners)
            if (l != null)
                l.onChangeEvent(newValue);
    }

    public T getValue()
    {
        return _value;
    }

    public interface OnChangeListener<T>
    {
        void onChangeEvent(T newValue);
    }
}
As you can see I have used a Set made from a WeakHashMap to store the event listeners. This is to ensure that Fickle objects don't create memory leaks. As the reference to the listener is weak, when a listener object is no longer in use anywhere else in the code then it will automatically be removed from the set. This is a very cool Java feature. However, what this means is that you must have a strong (normal) reference to the listener object, otherwise it will be deleted.

Here is an example of how to use the Fickle class:
class MrsClass
{
    private float _doubleVal;

    public MrsClass(final Fickle<Float> capVal)
    {
        // Initialize the member variable.
        setVal(capVal.getValue());

        // Handle the on change event.
        capVal.addOnChangeListener(new Fickle.OnChangeListener<Float>()
            {
                public void onChangeEvent(Float newValue)
                {
                    setVal(newValue);
                }
            });
    }
    
    private void setVal(float val)
    {
        _doubleVal = val * 2.0f;
    }

    public float getDoubleVal()
    {
        return _doubleVal;
    }
}

class MrMain
{
    public static void main(String[] args)
    {
        Fickle<Float> val;
        val = new Fickle<Float>(1.0f);

        MrsClass mrs = new MrsClass(val);
        float doubled = mrs.getDoubleVal(); // should equal 2.0f

        val.setValue(3.5f);
        doubled = mrs.getDoubleVal(); // should equal 7.0f

        // By dereferencing the MrsClass object the
        // listener will be automatically removed from
        // the listener Set by the WeakHashMap class.
        mrs = null;
    }
}
This code is completely free to use by anybody. It is held under the Do What You Want To Public License: http://tinyurl.com/DWYWTPL