Showing posts with label OO. Show all posts
Showing posts with label OO. Show all posts

Saturday, July 7, 2012

Smalltalk inspired extensions for c#

Having developed in Smalltalk for about 3 years in the early '90's, I still regard the language fondly and am always slightly saddened that it never achieved mainstream adoption.Without Smalltalk, I don't believe I would have so 'easily' became moderately proficient in object oriented thought - note, not analysis or design, but literally thinking 'as an object'. Anthropomorphising is still something I engage in.

Philosophy aside, I amused myself by considering the behaviour of the Smalltalk boolean object a few weeks ago after a brief period of development in Squeak (see also below). You 'talk' to the boolean, and can effectively ask it to do something if it is true or false.

A simple example below, that writes a message to the Transcript window depending on the outcome of the test (which returns a boolean):

 a > b  
 ifTrue:[ Transcript show: 'greater' ]  
 ifFalse:[ Transcript show: 'less or equal' ]  

So, being perverse, what could I do to mimic this behaviour in c#, so I might be able to say:

 (a > b)  
   .IfTrue(() => Console.Write("greater"))  
   .IfFalse(() => Console.Write("less or equal"));  

It's obvious really - use an extension method on the System.Boolean type. This is shown below:

 public static class BoolExtension {  
          public static bool IfTrue(this bool val, Action action) {  
              if (val) action();  
              return val;  
          }  
          public static bool IfFalse(this bool val, Action action) {  
              if (!val) action();  
              return val;  
          }  
      }  

Please don't misinterpret - I'm not espousing this as a necessarily good idea, more demonstrating that extension methods allow one to 'fake' the presence of interesting constructs present in other languages.

From the squeak website:
Welcome to the World of Squeak!Squeak is a modern, open source, full-featured implementation of the powerful Smalltalk programming language and environment. Squeak is highly-portable - even its virtual machine is written entirely in Smalltalk making it easy to debug, analyze, and change. Squeak is the vehicle for a wide range of projects from multimedia applications, educational platforms to commercial web application development.

Tuesday, November 15, 2011

Sencha Touch: Workflow framework published


I've been working on a workflow framework for Sencha Touch, after repeatedly being in the position of wanting to compose tasks in an intelligible, maintainable and flexible manner. It employs some simple OO abstractions, a nod towards separation of concerns, and the handy inbuilt event framework of Sencha. It also utilises JSinq, which I find a rather handy little library - although it is relatively easy to convert to not use it in case of concerns over download/package size.
The project is published on codeplex: http://mobileflow.codeplex.com/
Project overview (excerpt)
A workflow framework for Sencha Touch mobile apps including automatic component management. The intent is to start 'small', with a basic workflow engine, and build to include hydration/dehydration of workflow instances (using the memento pattern and local storage for example) and a visual designer and DSL style code generation.
Currently uses Sencha Touch 1.1, but will upgrade to 2.0 when out of the preview stage.

Saturday, June 4, 2011

Self constructing 'Null' objects with Unity

This post follows on from the musings on proxies and Null objects. As I opined, auto constructing implementations of the Null object pattern should be possible via a proxy approach - hence here, I show one way of doing such, using the Unity framework as a base.

The essence of the implementation is: when creating an object that needs auto construction services (that is, when a property is referenced and it is both a reference object and null - create a stand-in), wrap it in a unity interceptor, and associate with the wrapper (in my case) an 'object creation provider' object - that is responsible for providing (literally) the object creation service.

Here is the almost complete implementation, followed by an exposition on the salient points.

1:    
2:    
3:   public class AutoConstructingObjectProxy : BaseInterceptionBehavior {  
4:    
5:    private const string GetPropertyPrefix = "get_";  
6:    private static readonly Dictionary<Type, Func<object>> mHandlers =   
7:     new Dictionary<Type, Func<object>> {   
8:      { typeof(string), () => String.Empty }   
9:     };  
10:    
11:    public AutoConstructingObjectProxy(IObjectCreationProvider objectBuilder)  
12:     : base(PromiscuousPolicy) {  
13:     ObjectBuilder = objectBuilder;  
14:    }  
15:    
16:    protected override IMethodReturn ProcessInvocation(IMethodInvocation input, Func<IMethodReturn> processNext) {  
17:     IMethodReturn result = processNext();  
18:    
19:     if (result.ReturnValue == null) {  
20:      PropertyInfo info = GetProperty(input);  
21:      if (info != null) {  
22:       object constructedObject =   
23:        PrimitiveDefault(info) ??   
24:        (ConstructableProperty(info) ?   
25:         ObjectBuilder.CreateObjectFromType(info.PropertyType, true) : null);  
26:       if (constructedObject != null) {  
27:        // If, for some reason, the property is not mutable,   
28:        // then this will be an inefficient mechanism  
29:        if (info.CanWrite)  
30:         info.SetValue(input.Target, constructedObject, null);  
31:        result.ReturnValue = constructedObject;  
32:       }  
33:      }  
34:     }  
35:     return result;  
36:    }  
37:    
38:    private object PrimitiveDefault(PropertyInfo info) {  
39:     return mHandlers.ContainsKey(info.PropertyType) ? mHandlers[info.PropertyType] : null;  
40:    }  
41:    
42:    private PropertyInfo GetProperty(IMethodInvocation input) {  
43:     return !input.MethodBase.Name.StartsWith(GetPropertyPrefix) ?  
44:       null :   
45:       input.Target.GetType().GetProperty(input.MethodBase.Name.Replace(GetPropertyPrefix, String.Empty));  
46:    }  
47:    
48:    private bool ConstructableProperty(PropertyInfo info) {  
49:     return ObjectBuilder.ControlsNamespace(info.PropertyType.Namespace);  
50:    }  
51:    
52:    private IObjectCreationProvider ObjectBuilder { get; set; }  
53:    
54:   }  
55:  }  
56:    

So, of course the class declaration itself:

  • Line 5: defines the standard prefix for a property 'getter' (used in reflection later)
  • Lines 6-9: Define some handlers for objects that can't just be 'new'd' and are not constructed automagically
  • Lines 11-14: This interceptor type is constructed with an implementation of the interface IObjectCreationProvider - an object building factory if you will, that knows how to locate types to construct and then create them on demand. As part of construction, an object is passed to the base class constructor that controls how properties are to be intercepted - in this case promiscously; that is, all properties are candidates for inspection


1:    
2:    
3:   public class AutoConstructingObjectProxy : BaseInterceptionBehavior {  
4:    
5:    private const string GetPropertyPrefix = "get_";  
6:    private static readonly Dictionary<Type, Func<object>> mHandlers =   
7:     new Dictionary<Type, Func<object>> {   
8:      { typeof(string), () => String.Empty }   
9:     };  
10:    
11:    public AutoConstructingObjectProxy(IObjectCreationProvider objectBuilder)  
12:     : base(PromiscuousPolicy) {  
13:     ObjectBuilder = objectBuilder;  
14:    }  
15:       

Here's the key part.

  • Line 16: This is an override of a base class method that itself implements the Unity Invoke method (base class created by Sam Stephens, as part of our project when we refactored the previous policy injection application block implementation. And Sam, who coined the memorable phrase "social oddity" to describe my interaction with humans!) 
  • Line 17 - execute the invocation to it's result yielding conclusion
  • Line 19 - see if the return value is actually null
  • Line 20 - Call a private method that uses reflection to get a PropertyInfo object for the currently intercepted method, if one exists
  • Lines 22-25 - Declare and construct an object. If the 'standard' handlers don't provide a value (use of the coalescing operator of c#), see if the property info has a return type  such that the object creation provider can theoretically construct the object. If it can, ask the provider to create an object, and (using the true parameter) request that the returned object is itself wrapped in an auto constructing object proxy. This is obviously most important - if we auto construct a stand-in object, we need that object to also auto construct parts of itself that might be null.
  • Lines 26-30 - so, if we have an object reference now, and the property itself is writeable, insert this object into the current object (the target of the interception). Also, and again important, set the return value of the invocation to the object we constructed. There is a performance implication if the property that was located is not writeable - we'll keep creating objects every time such a property is referenced.

     
16:    protected override IMethodReturn ProcessInvocation(IMethodInvocation input, Func<IMethodReturn> processNext) {  
17:     IMethodReturn result = processNext();  
18:    
19:     if (result.ReturnValue == null) {  
20:      PropertyInfo info = GetProperty(input);  
21:      if (info != null) {  
22:       object constructedObject =   
23:        PrimitiveDefault(info) ??   
24:        (ConstructableProperty(info) ?   
25:         ObjectBuilder.CreateObjectFromType(info.PropertyType, true) : null);  
26:       if (constructedObject != null) {  
27:        // If, for some reason, the property is not mutable,   
28:        // then this will be an inefficient mechanism  
29:        if (info.CanWrite)  
30:         info.SetValue(input.Target, constructedObject, null);  
31:        result.ReturnValue = constructedObject;  
32:       }  
33:      }  
34:     }  
35:     return result;  
36:    }  

The rest of the implementation is simple 'helper' methods. And it works - but with Unity, as usual, with some implications in terms of performance.

Of course, there are limitations. In particular, if a wrapped object has a property that can't be auto constructed, and is a reference type other than string - nothing will happen if that property is null. Now, for certain types, it will be relatively trivial to construct them, again, using reflection. So, if we had:

public List<IDomainObject> Associates { get; private set; }

Then, sure, we can construct an empty list easily enough. However, if we had instead:

public IEnumerable<IDomainObject> Associates { get; private set; }

This is rather more problematic. It's certainly quite easy to select any sub type of IEnumerable<T> and instantiate that - but if client objects ill advisedly have expectations of the concrete type of 'Associates' (say, for the sake of argument, it is an array and not a List<T> instance), it's going to be eminently breakable. Of course, we'd argue that expectations of the concrete type are improper on the part of a consumer; and, if you want an array, why not just use the construct: 'Associates.ToArray()'?

In terms of 'breakability', the OO purist side of me says 'tough' - but the real world is anything but pure or simple (or even predictable).

Saturday, May 28, 2011

RavenDB: Conflict resolution when loading documents

The fun with RavenDB continues - if that sounds sarcastic, it's not meant to be - I'm rather fond of Raven, it certainly performs well, and I still find myself waxing lyrical about the LINQ provider - it's really very nice indeed.

One thing I did have to do though was work out how to deal with conflicts, especially in the face of a replication setup. It's not that difficult to do, but I thought I'd share (I like my presumption that anyone is actually going to read this!).

I have a wrapper class around Raven (I get bored typing RavenDB, so Raven it is), that provides some useful behaviour around core Raven features. One such wrapper feature is the 'recoverable' load - simply put, when a document is loaded from Raven and a conflict is detected, an attempt will be made to resolve the conflict.

The base implementation is as below - we use a Func<> to load an object, and if a Raven conflict exception occurs, we attempt to resolve the conflict, and return an object.

1:  public T RecoverableLoad<T>(string id, Func<RavenSessionWrapper, string, T> loader) where T : RavenBase {  
2:    DBC.AssertNotNull(loader, "Cannot exeucte a recoverable load with a null loader");  
3:    T result;  
4:    try {  
5:      LogFacade.LogInfo(this, string.Format("Recoverable load attempt for {0}", id));  
6:      result = loader(this, id);  
7:    }  
8:    catch (ConflictException ex) {  
9:      result = ResolveConflict(ex, id, loader);  
10:      DBC.AssertNotNull(result, "Null document even after conflict resolution tried");  
11:    }  
12:    return result;  
13:  }  
14:  private T ResolveConflict<T>(ConflictException ex, string id, Func<RavenSessionWrapper, string, T> loader) {  
15:    return ResolveConflict(ex.ConflictedVersionIds, id, loader);  
16:  }  

Lines 14-16 are just a convenience method to extract conflict ids from the actual conflict exception.

The actual conflict resolution behaviour is shown next:

1:  private T ResolveConflict<T>(IEnumerable<string> conflictIDs, string id, Func<RavenSessionWrapper, string, T> loader) {  
2:    LogFacade.LogWarning(this,   
3:     string.Format("Forced to resolve conflict for {0}. Conflict IDs:{1}{2}", id, Environment.NewLine, string.Join(Environment.NewLine, conflictIDs.ToArray())));  
4:    List<JsonDocument> conflicts =   
5:     conflictIDs.Select(s => RavenStore.DatabaseCommands.Get(s)).ToList();  
6:    Func<JsonDocument, DateTime> f = d =>  
7:     d.DataAsJson[TimestampProperty] == null ?   
8:      DateTime.MinValue :   
9:      JsonConvert.DeserializeObject<DateTime>(d.DataAsJson[TimestampProperty].ToString());  
10:    JsonDocument choice =   
11:       conflicts.Aggregate((curMax, x) => curMax == null || f(x) > f(curMax) ? x : curMax);  
12:    RavenStore.DatabaseCommands.Put(id, null, choice.DataAsJson, choice.Metadata);  
13:    LogFacade.LogWarning(this, string.Format("Resolved conflict for {0}, Marker: {1}", id, f(choice)));  
14:    return loader(this, id);  
15:  }  

So, what do we actually do:

  • Get a list of JSON documents that correspond to the conflict ids, using the base Raven'Get'  database command  (lines 4-5)
  • Define a Func<> that gets a timestamp property from the raw JSON document or provides a substitute value if non existent (lines 6-9)
  • Find the JSON document with the latest timestamp, via a peculiar use of the Aggregate LINQ method (lines 10-11)
  • Write the document back to Raven as definitive (line 12)
  • Now, load the document (line 14)
Sure, it is not that pretty, and it could do with some optimisation, but it works. The only implementation issue is really that a specific property is expected to exist in the JSON document. However, in my scenario, I have complete control over the construction of Raven documents, so there was no real need to make it more general.

Lazy loading: Generic Proxy and Null Object patterns

Most developers will be familiar with the concept of lazy loading, and in particular the use of proxies to support this. I have a simple implementation of the Proxy pattern in the code base I work most with, using a basic generic interface approach.

Firs then, the state proxy interfaces, with a single method to retrieve state on demand and three flavours - one to three generic types.

1:  #region State proxy interface  
2:    
3:  public interface IStateProxy<R> {  
4:    R ObtainState();  
5:  }  
6:    
7:  public interface IStateProxy<R, S> {  
8:    R ObtainState(S arg0);  
9:  }  
10:    
11:  public interface IStateProxy<R, S, T> {  
12:    R ObtainState(S arg0, T arg1);  
13:  }  
14:    
15:  #endregion  

It's expected that concrete implementations of these interfaces are created at some time and injected into the object that desires to use their services. One such example is shown below - the two type variant, returning one type and accepting a different type as an argument.

1:  #region State proxy  
2:  [Serializable]  
3:  internal class HomeLoanStateProxy :   
4:      IStateProxy<ILoanOffsetInstrument, IHomeLoan> {  
5:    public ILoanOffsetInstrument ObtainState(IHomeLoan loan) {  
6:      ILoanOffsetInstrument result;  
7:      try {  
8:        result = AgentFactory.Instance.CreateMappedAgent<AccountsAgent>().DeriveLoanInstrument(loan);  
9:      }  
10:      catch (Exception ex) {  
11:        LogFacade.LogError(this, string.Format("Failed to gather loan instrument information for {0}", loan.Number), ex);  
12:        result = LoanOffsetInstrument.Empty();  
13:      }  
14:      return result;  
15:    }  
16:  }  
17:  #endregion  

The example proxy takes a Null Object pattern approach to exceptions during processing, and aggressively so. If, for some reason, the proxy fails during execution, a log event is generated, and the return object is set to an instance of a LoanOffsetInstrument that has benign content. This way, the proxy dependent can always rely on a non null result.

Then of course, the proxy consumer/dependent itself.

1:  public override ILoanOffsetInstrument OffsetInstrument {  
2:    get {  
3:      if (mInstrument.IsEmpty() && StateProxy != null)  
4:        mInstrument = StateProxy.ObtainState(this);  
5:      return mInstrument;  
6:    }   
7:    protected set {  
8:      mInstrument = value;  
9:    }  
10:  }  

While writing this, it occurred to me that:
  • It bears some similarities to the Lazy<T> previous post, in terms of intent
  • A proxy might be better implemented with a proper dynamic proxy approach - something like Castle Dynamic Proxy for example
  • The proxy implementation should take care of the state it serves up; there is little need for it to be stored as part of the dependent object (this should have been quite obvious to me - the proxy is even marked serializable, as at some point in it's life it is sent out of process along with its container)
  • The proxy should be more aware of its 'exception state' - that is, it should know if it has failed before and needs to try and retrieve state again; it should also know when to give up - that is, not keep pathologically attempting to retrieve an object if the retrieval keeps failing 
  • The dependent implementation could be made simpler on the back of this, with no need to have a property setter, and no local state being held:
1:  public override ILoanOffsetInstrument OffsetInstrument {  
2:    get {  
3:      return StateProxy == null ? null : StateProxy.ObtainState(this);    
4:    }     
5:  }  

That's almost right, but it does not honour the Null Object pattern intent of the state proxy, so we'd probably have to return an "Empty" object. But this is just doodling :-)

Saturday, May 21, 2011

Singleton using Lazy<T>

Singleton is a common (and sometimes controversial) pattern. A few weekends ago, during the creation of a particularly hot chilli jam (recipe here, but quintuple the amount of chilli at least), I thought that perhaps the new .NET 4.0 class Lazy<T> would be a pleasing way of implementing a singleton.

Some judicious googling later - not a new idea at all. The only slightly unpleasant aspect to using Lazy<T> is that in 'naked' use, it expects a public default constructor - which of course is an excellent way to defeat a singleton implementation! But there are overloads that allow one to specify a Func<T> to create an instance, and even better, thread safety options can also be specified.

Another overload would therefore be useful - the ability to specify binding flags perhaps, to indicate to Lazy<T> that it should look for a private constructor. A little clumsy I suppose, since it would then be required to use reflection, but that is not so expensive a proposition these days.

MSDN documentation.

Wednesday, April 20, 2011

Reification of policy abstractions

I've been considering recently how I use 'policies as objects' in an implementation. I'm not quite sure where I got the notion from that this was good practice, but it does seem to work acceptably and allows for a degree of 'pluggability' - maybe it's just a take on the GOF Strategy idea. There is certainly some anthropomorphic  appeal; you may have had recourse to use a phrase like 'it is our policy to...' in relation to an action that was necessary based on certain conditions. A necessary action based on conditions, is classifiable (with a degree of artistic license!) as behaviour based on state. And with a Booch mindset in place, therefore has a direct relationship to object oriented practice.

So the interface definition below is a simple example I have to hand. An instance of a DCS provider manager (it does not matter awfully what that means) has an injected reference to an implementer of IDCSProviderManagerPolicy. At certain strategic points in it's behaviour, it can ask the policy for 'advice' on what to do when certain conditions are encountered. In the case of this example, whether recovery is possible when an error is encountered, and if there is a 'provider switch' available when an operation fails. All in all, a very simple abstraction indeed. My current project has two policy implementations; a 'fail always' policy, and an 'alternate providers once only' policy. Each is used for particular scenarios.

   /// <summary>  
   /// A reification of policy  
   /// </summary>  
   public interface IDCSProviderManagerPolicy {  
     /// <summary>  
     /// Returns true if the implementer adjudges it   
     /// possible that recovery may be attempted  
     /// </summary>  
     bool MayAttemptRecovery { get; }  
     /// <summary>  
     /// Invoked when a DCS provider operation fails  
     /// </summary>  
     IDCSProvider OperationFailed(IDCSProviderManager manager);  
   }  

Saturday, December 11, 2010

Ternary associations

I'm often surprised by how many designers/developers are unfamiliar with the notion of a ternary association. To me, they represent a natural decomposition of a relationship between two objects. There is a certain symmetry that is pleasant both intellectually and aesthetically, additionally appealing to the (I seem to remember) Wirfs-Brock notion of distributed intelligence in object systems being a goal worthy of achieving (for a variety of reasons).

In the finance industry, these relationship types fairly seem to assail you from all sides. Take the canonical interpretation of a funds transfer (c.f. payment). At its simplest level, this is a process - the act of moving funds from a source account (source) to a target account (sink). But on further inspection it becomes obvious that the nature of the process itself holds state and behaviour that is not peculiar to either of the parties in the transaction, and thus lends itself to ternary association modelling. Trivially, you might model simple properties (such as a boolean property representing 'intra bank' transfers; if the putative transfer is valid and so on) in this process class; and also behaviour (whether this process is potentially a fradulent/risk attracting one).

The typical UML like representation of a ternary association is as below:

Here, of course, the Payment abstraction represents the ternary association, aggregating behaviour such as that already mentioned. Representation of a ternary in 'concrete' coding terms is usually straightforward. Almost never is a bi-directional association the mechanism to employ; almost always, a completely separate object is required, and in this case it would not be remiss to have the Payment type reference both Source and Sink directly. In fact, one would expect an instance of Payment to be the object that was dealt with directly. Such payments could be created directly or via a factory of some sort.

But is that really a ternary association, or just a simple pair of associations between one object and two other dependents. Why is it not just a whole/part example? If you refer to a payment as a process, why make the distinction at all, as the source and sink objects would surely just be participants in the process itself?

In this case, I think the reference to a ternary is valid; the payment does in fact expose behaviour and derived state that is attributable to the relationships between two discrete objects. And I don't believe that the cardinality of the relationships between the two 'simple' objects has to be many to many for this modelling technique to make sense.