Pythonista: Applying Python idiom to C# with attribute-builder pattern
Recently I’ve been looking into the way Google AppEngine lets you define properties from a “property class” and noticed a semi-metaprogramming pattern:
class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True)
Note how author, content and date looks like a normal variable with a class instance being assigned.
And recently I have been Diving into Python and was reading up on class instantiation and so I immediaty thought of this:
def buildAdder(num): def myAdder(x): return num + x return myAdder
This function lets me easily create functions (closures?) on-the-fly ala meta-programming, so I can create a class like this:
class MyClass: add1 = buildAdder(1) add2 = buildAdder(2) add3 = buildAdder(3)
And sure enoughs, MyClass now has 3 methods for adding 1, 2 and 3 respectively:
k = MyClass() print k.add1(9) # prints 10 print k.add2(8) # prints 10 print k.add3(7) # prints 10
And I suddenly realize that This pattern can easily be mimicked in C#!
Because in C# 3.5 we now have lambda functions and closures, this pattern can be repeated almost exactly the same way in C# by utilizing public Func fields:
class MyClass { public Func<int, int> Add1 = buildAdder(1); public Func<int, int> Add2 = buildAdder(2); public Func<int, int> Add3 = buildAdder(3); static Func<int, int> buildAdder(int number) { return x => x + number; } }
And then I can invoke the functions on MyClass just the same way:
var t = new MyClass(); Console.WriteLine(t.Add1(9)); // prints 10 Console.WriteLine(t.Add2(8)); // prints 10 Console.WriteLine(t.Add3(7)); // prints 10
C# is awesome!
However, classes in C# are immutable so they are not easily plugged-in and plugged-out like those in Python. It might take a lot more work to translate Django/AppEngine-style property builder pattern to C#.
There are also some performance implications to be concerned, but in some slow-start-doesn’t-matter scenarios this might prove to be useful.
Categories: Tutorials
Tags: appengine, c#, function-builder, meta-programming, python
Comments: 3 Comments.
[...] This is a follow up to last post on attribute-builder pattern. [...]
Without the use of ‘Func’, I can define a delegate to accomplish the same thing too, right?
And without C#, is this the same thing as defining interfaces and use anonymous class to implement them in Java ? (http://stackoverflow.com/questions/443708/callback-functions-in-java/443741#443741)
I still can’t understand this Python’s beauty
Same… but its more elegant in Python less so in C# less so using delegate and even less so in Java.