Saturday, June 4, 2011

What Can We Learn From Python And JavaScript While Programming in C#

What can we learn from

Python and JavaScript

while programming in C# 4.0?


Who I am?

First Name: Frederic
Last Name:  Torres
Web Site:
State:      Massachusett

  • I have been writing code since MS-DOS 2.0 on different continents.
  • I write code in C# by day and in Python or JavaScript by night.

What about you ?

Alt text

Why am I here?

Dynamic Languages - Python, Ruby, JavaScript.

    - Source Code Length

    - Readability

Python and Ruby

  • The Pythonic way (Python Secret Weblog)
  • Ruby is designed to make programmers happy

Peter Norvig from Google wrote a spell checker in 21 lines in Python How to Write a Spelling Corrector

import re, collections

def words(text): return re.findall('[a-z]+', text.lower()) 

def train(features):
    model = collections.defaultdict(lambda: 1)
    for f in features:
        model[f] += 1
    return model

NWORDS = train(words(file('big.txt').read()))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

def known_edits2(word):
    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
    return max(candidates, key=NWORDS.get)

  • Is there anything we can learn from programming Python and JavaScript and apply it in C#?

    • This is the question I have been thinking about.
    • And it is not just me!

A different way to code in C#

  • Is there a different way to write code in C# in the air?
  • 3 Samples

  • ASP.NET MVC Syntax (Microsoft Product)

   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } 

  • Massive and Dapper : 2 small ORMs

    • Written in less than 400 lines of code each
    • Written by Rob Conery and Sam Saffron (from Stack Overflow)
    • Have been talked about on the hanselminutes podcast.

// Massive Syntax
var table = new Products();
table.Update( new { ProductName = "Chicken Fingers" } , 12);

var resultSet1 = persons.All(columns: "*", where: "ID >= @0", args: 1);
foreach(var p in resultSet1)
    Console.WriteLine(String.Format("ID:{0}, Name:{1}, {2}", p.ID, p.LastName, p.FirstName));                


  • The Dapper library and reflection.

  • Web Matrix (Microsoft Product)

How did I got involve in this

  • The more experienced with Dynamic Languages, the more you will miss their syntaxes working in C#.
  • Is there anything that we can do with?

    • Reflection
    • Generics
    • Anonymous types
    • Extension method
    • Lambda expression/statment
    • The keyword params
    • The keyword dynamic and the class DynamicObject


  • http://www.DynamicSugar.Net

    • A library providing methods and classes inspired by the dynamic languages Python and JavaScript
    • To write shorter and more readable source code in C# 4.0
    • On
    • On

It's all about Syntactic sugar.

Let's Start...

What can we learn about formatting string from JavaScript?

In C#

var firstName = "Fred";

Console.WriteLine(String.Format("Hello {0}",firstName));

In JavaScript

In JavaScript you may find this, which is not standard, but generally implemented via extension methods.

var firstName = "Fred";

print(String.format("Hello {0}",firstName));

print("Hello {0}".format(firstName));

print("Hello {firstName}".format( { firstName:"Fred" } ));

- Demo

What can we learn about formatting string from Python?

class Person(object):

  def __init__(self, name, age):
    self.Name = name
    self.Age  = age

  def Format(self, myFormat):
      return myFormat.format(**self.__dict__)


p = Person("Fred", 45)
print p.Format("Name={Name}, Age={Age}")

- Demo

Object Literals [ ]

Python's List

i = 3

if i in [1,3,5]:
    print "in the list"

JavaScript's Array

This code is not standard JavaScript. The method Contains() and In() are
defined before this code as extension methods.

var i = 3;

    console.log("in the list")

    console.log("in the list")

- Demo

What about a function returning multiple values?

What Python's syntax can say about that?

def ComputeValues(value):
    return True, 2.0*value, "Hello"

ok, amount, message = ComputeValues(2)

print ok:{0}, amount:{1}, message:{2}".format(ok, amount, message)

More about this

def ComputeValues(value):
    return True, 2.0*value, "Hello"

ok, amount, message = ComputeValues(2)

print "ok:%s, amount:%s, message:%s" % (ok, amount, message)

values = ComputeValues(2)

print "ok:%s, amount:%s, message:%s" % (values[0], values[1], values[2])

What JavaScript's syntax can say about that?

function ComputeValues(value) {

    return { ok:true, amount:2.0*value, message:"Hello" };

var r = ComputeValues(2);

print("ok:"             + r.ok);
print("amount:"         + r.amount);
print("message:"        + r.message);

- Demo

Object Literals { }

  • Passing a populated dictionary to a function very common in Dynamic Languages.
  • In Python and Ruby, there is a dedicated syntax just to do that.

This allow to pass an unlimited number of argument in very clear way, by defining the name and the value of each argument.

  • JavaScript - an Ajax call with jQuery.

        type    : "POST",
        url     : "some.php",
        data    : "name=John&location=Boston",
        success : function(msg){ alert( "Data Saved: " + msg ); }

  • Python

def MyFunction(**context):

    if context["debug"]:
        print "Debug on"

    if "America" in context["continent"]:
        print context["continent"]

MyFunction( debug=True,  continent="North America" )
MyFunction( debug=True,  continent="South America" )
MyFunction( debug=False, continent="Europe"        )

With C# 4.0

  • Named parameters allow a similar syntax,
  • The number of arguments is limited and have to be predefined.

void MyFunction(bool debug, string continent){
  // code

MyFunction(false, "Europe");

MyFunction(debug:false, continent:"Europe");

- Demo