Sunday, 7 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 lot of interconnected Javascript, I slowly derived this pattern.

The Folding Pattern is aware that Javascript is a functional/imperative object-oriented language that employs object prototypes rather than classes. It allows for the concept of private members, which is of importance in large projects (to combat accidental mangling of an object). By sticking to the rigorous formatting you can create very large objects which are easy to maintain and navigate. (Especially if you use an IDE which allows for folding of statement blocks.)

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

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 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));
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


To use the templates just take a copy of one and rearrange it to suit. 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.text = 'untweaked';
           N.count = 0;
           N.nums = [1, 2, 3];
       }());

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

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

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

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

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

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

   (function () {
// Here is how to use that singleton.

 var mySingRef = foldingPattern.singletonExample;
mySingRef.tweak();
mySingRef.tweakStatus = 'dunno';
   }());
   //====================================


   //====================================
   // 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 () {
                       N.toggle = !N.toggle;
                       return N.toggle;
                   }
               });

               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';
               };
           }());
       }());
   }());

   (function () {
// Here is how make an instance of that type.
    var myInst = new foldingPattern.TypeExample();
myInst.text = 'toggle: ' + myInst.toggle;
    myInst.tweak();
   }());
   //====================================

}(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


[Edit]
Regarding the comment below, to explain further, the main reason for the self-executing functions (in upper-case) is because many text editors allow for "code folding". So for a large object definition, the methods can be folded up into a single line. Somewhat like this:

   // 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() {...

           +(function EXPOSED_FIELDS() {...

           // 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() {...

       };

       // Here is the prototype section.
       (function PROTOTYPE() {

           var P = thisType.prototype;

           +(function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {...

           +(function EXPOSED_METHODS() {...
       }());
   }());

This makes it easier to see the file in a kind of "overview mode", where moving between sections is made easier and more manageable.

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;
    }
}
So this is effectively an encapsulation of the Observer pattern.

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, 26 November 2012

Java Lazy Evaluation

Lazy evaluation. This is where a piece of code is written which evaluates a value (usually requiring a relatively large amount of processing), but the code isn't executed until the moment it is needed (if ever).

For example, class A calls a method in class B. It passes some values (which take a long time to compute). If the values are passed lazily then class B can decide when and if to compute them. It is up to class A to implement the code for how to evaluate the value. So maybe there are 3 lazy values passed and class B decides it doesn't need to use value 1 but it does use values 2 and 3 (perhaps invoking each evaluation in separate threads, to maximise performance). The code to evaluate value 1 is never called, the code to evaluate values 2 and 3 will be called once and only once. Subsequent retrievals of a lazily evaluated value will return a cached copy of the value (unless the lazy evaluator is reset... see the code below).

Here is the class:

public abstract class Lazy<T>
{
  private boolean _evaluated = false;
  private T _value = null;

  public final T get()
  {
    if (!_evaluated)
    {
      _value = evaluate();
      _evaluated = true;
    }

    return _value;
  }

  public void reset()
  {
    _evaluated = false;
    _value = null;
  }

  protected abstract T evaluate();
}

... and here is how to use it:

  // Setup.
  final float height = 7.0f;

  // Create the lazy.
  Lazy<Float> halfHeight = new Lazy<Float>()
  {
    public Float evaluate()
    {
      return height / 2;
    }
  };

  // Get it's value.
  halfHeight.get();

And that's all you need. 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

Thursday, 11 October 2012

Half-sort



Half-sort is a sorting algorithm. A copy of it can be found here:
https://www.box.com/s/p0pn15736599bv8rb8rx

It has the following features:

  • It is an in-place sort. (No extra data space needed.)
  • It works by "divide and conquer" recursion. (It is quite like Quick-sort and Merge-sort.)
  • It is not stable. (i.e. It does NOT keep the original order of identically valued items in the list.)


Here is some pseudo-code that explains how the Half-sort algorithm works:

  1. Calculate M to be a value that is half way between the smallest item and the biggest item in the collection. You may have to scan the entire collection to find this value, but it may already be known or can be easily calculated.
  2. L begins by pointing to the start of the collection and moves forwards until an item bigger than M has been found.
  3. R begins by pointing to the end of the collection and moves backwards until an item smaller than M is found.
  4. Swap the items at L and R.
  5. Carry on doing this until L and R meet in the middle. This would be the mean average middle, not the middle index position.
  6. Now repeat these steps on each side of collection, until it is fully sorted.



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

Wednesday, 22 August 2012

Landscape Chess

I had a weekend of chess. Saturday, a couple of friends came over and we played some games. Next day my sister's family came, my nephew wanted to play chess too. So we had a few games.

Then our young daughter wanted to play and we had a good mess around, laughing our heads off as we came up with crazy ideas for new rules and ways that the pieces can move. Then out of the chaos some order arose and we found a fun new way to play chess.

Originally it had another name, but after doing some research we found another chess variant had that name. So to make this variant unique we decided on naming it Landscape Chess. At first we were somewhat disheartened to find somebody had already created a chess variant using a diagonal board, although we initially guessed someone probably would have. However, the other variants all seemed to muddy the beauty of chess. We think this variant complements chess, and even more so it actually brings something new to explore.

How to play Landscape Chess

Setting up

The chess board is turned diagonally, so that a black corner faces each player. The pieces are arranged as shown in the pictures (K is king and N is knight).




Movement

The pieces actually move in the same way as regular chess... except for the pawn, which moves pretty much in the usual manner, only diagonally.







Rules

There is no castling in Landscape Chess. When pawns get to either edge of the other side of the board they can be promoted to any other piece. The goal of the game hasn't changed from regular chess: you must try to get the opponent's king into check mate. 

Landscape Chess has one new rule not found in regular chess: any bishop on a white square can be moved to an adjacent black square, possibly taking an opponent piece in the process. The reason for this new rule is that all bishops begin on white squares at the beginning of the game. This new rule adds much to the strategy and actually makes the bishop a very formidable piece, if used wisely.