Why learn new programming languages

37
WHY LEARN NEW PROGRAMMING LANGUAGES? What I’ve learned from Ruby and Scheme that applies to my daily work in C# and JavaScript Trondheim XP Meetup Jonas Follesø, Scientist/Manager BEKK Trondheim 08/02/2012

description

A presentation sharing my pe

Transcript of Why learn new programming languages

Page 1: Why learn new programming languages

WHY LEARN NEW PROGRAMMING

LANGUAGES?

What I’ve learned from Ruby and Scheme that applies to my daily work in C# and

JavaScript

Trondheim XP Meetup

Jonas Follesø, Scientist/Manager BEKK Trondheim

08/02/2012

Page 2: Why learn new programming languages
Page 3: Why learn new programming languages

3

Page 4: Why learn new programming languages

4PERSONAL HISTORY OF PROGRAMMING LANGUAGES

QBasic(1996)

Turbo Pascal(1998)

Delphi(1999)

VBScript(2001)

C#(2002)

JavaScript(2003)

Java(2004)

Python(2005)

Scheme(2006)

Ruby(2010)

Page 5: Why learn new programming languages

5PERSONAL HISTORY OF PROGRAMMING LANGUAGES

QBasic(1996)

Turbo Pascal(1998)

Delphi(1999)

VBScript(2001)

C#(2002)

JavaScript(2003)

Java(2004)

Python(2005)

Scheme(2006)

Ruby(2010)

Page 6: Why learn new programming languages

6HIGHER ORDER FUNCTIONS

Formulating Abstractions with Higher-Order

Functions

Page 7: Why learn new programming languages

7ABSTRACTIONS THROUGH FUNCTIONS

(* 3 3 3) ; outputs 27

(define (cube x)   (* x x x))  (cube 3) ; outputs 27

Page 8: Why learn new programming languages

8ABSTRACTIONS THROUGH FUNCTIONS

(define (sum-int a b)  (if (> a b)      0      (+ a (sum-int (+ a 1) b))))

(define (sum-cubes a b)  (if (> a b)      0      (+ (cube a) (sum-cubes (+ a 1) b))))

Page 9: Why learn new programming languages

9ABSTRACTIONS THROUGH FUNCTIONS

(define (sum-int a b)  (if (> a b)      0      (+ a (sum-int (+ a 1) b))))

(define (sum-cubes a b)  (if (> a b)      0      (+ (cube a) (sum-cubes (+ a 1) b))))

Page 10: Why learn new programming languages

10ABSTRACTIONS THROUGH FUNCTIONS

(define (<name> a b)  (if (> a b)      0      (+ <term> (<name> (<next> a) b))))

Page 11: Why learn new programming languages

11ABSTRACTIONS THROUGH FUNCTIONS

(define (sum term a next b)  (if (> a b)      0      (+ (term a) (sum term (next a) next b))))

(define (inc n) (+ n 1))(define (identity n) n)

(define (sum-int a b) (sum identity a inc b))(define (sum-cubes a b) (sum cube a inc b))

(sum-int 0 10) ; outputs 55(sum-cubes 0 10) ; outputs 3025

Page 12: Why learn new programming languages

12ABSTRACTIONS THROUGH FUNCTIONS

(define (sum term a next b)  (if (> a b)      0      (+ (term a) (sum term (next a) next b))))

(define (inc n) (+ n 1))(define (identity n) n)

(define (sum-int a b) (sum identity a inc b))(define (sum-cubes a b) (sum cube a inc b))

(sum-int 0 10) ; outputs 55(sum-cubes 0 10) ; outputs 3025

Page 13: Why learn new programming languages

13ABSTRACTIONS THROUGH FUNCTIONS - JAVASCRIPT

$("li").click(function() {    $(this).css({'color':'yellow'});});

$("li").filter(function(index) {    return index % 3 == 2;}).css({'color':'red'});

$.get("/some-content", function(data) {    // update page with data...});

Page 14: Why learn new programming languages

14ABSTRACTIONS THROUGH FUNCTIONS – C#

SumEvenCubes(1, 10); // outputs 1800

public int SumEvenCubes() {    var num = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    return num .Where(IsEven) .Select(Cube) .Aggregate(Sum);}

public bool IsEven(int n) { return n % 2 == 0; }public int Cube(int n) { return n*n*n; }public int Sum(int a, int b) { return a + b; }

Page 15: Why learn new programming languages

15OBJECTS FROM CLOSURES

You don’t need classes to create objects

Page 16: Why learn new programming languages

16OBJECTS FROM CLOSURES IN SCHEME (define (make-account balance)

  (define (withdraw amount)    (if (>= balance amount)        (set! balance (- balance amount))        "Insufficient funds"))    (define (deposit amount)    (set! balance (+ balance amount))    balance)    (define (dispatch m . args)    (case m      ((withdraw) (apply withdraw args))      ((deposit) (apply deposit args))))    dispatch)

(define account1 (make-account 100))(account1 'withdraw 50)(account1 'deposit 25) ; outputs 75

Page 17: Why learn new programming languages

17OBJECTS FROM CLOSURES IN JAVASCRIPTvar make_account = function (balance) {    var withdraw = function (amount) {        if (balance >= amount) balance -= amount;        else throw "Insufficient funds";         return balance;    };     var deposit = function (amount) {        balance += amount;        return balance;    };     return {        withdraw: withdraw,        deposit: deposit    };};

var account1 = make_account(100);account1.withdraw(50);account1.deposit(25); // outputs 75

Page 18: Why learn new programming languages

18READABILITY

Extreme emphasis on expressiveness

Page 19: Why learn new programming languages

19READABILITY

“[…] we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves…”

Page 20: Why learn new programming languages

20EXAMPLES OF RUBY IDIOMS

abort unless str.include? "OK"

x = x * 2 until x > 100

3.times { puts "olleh" }

10.days_ago2.minutes + 30.seconds

1.upto(100) do |i|  puts iend

Page 21: Why learn new programming languages

21EXAMPLE OF RSPEC TEST

describe Bowling do    it "should score 0 for gutter game" do        bowling = Bowling.new        20.times { bowling.hit(0) }        bowling.score.should == 0    endend

Page 22: Why learn new programming languages

22C# UNIT TEST INFLUENCED BY RSPEC

public class Bowling_specs {    public void Should_score_0_for_gutter_game() {        var bowling = new Bowling();        20.Times(() => bowling.Hit(0));        bowling.Score.Should().Be(0);    }}

public static class IntExtensions {    public static void Times(this int times, Action action) {        for (int i = 0; i <= times; ++i)            action();    }}

Page 23: Why learn new programming languages

23C# FLUENT ASSERTIONS

string actual = "ABCDEFGHI";

actual.Should().StartWith("AB") .And.EndWith("HI") .And.Contain("EF") .And.HaveLength(9);

IEnumerable collection = new[] { 1, 2, 3 };collection.Should().HaveCount(4, "we put three items in collection"))collection.Should().Contain(i => i > 0);

Page 24: Why learn new programming languages

24READABILITY

Internal DSLs andFluent Interfaces

Page 25: Why learn new programming languages

25RUBY DSL EXAMPLES - MARKABY

Page 26: Why learn new programming languages

26RUBY DSL EXAMPLES – ENUMERABLE PROXY API

Page 27: Why learn new programming languages

27C# LINQ EXAMPLEstatic void Main(string[] args){ var people = new[] { new Person { Age=28, Name = "Jonas Follesø"}, new Person { Age=25, Name = "Per Persen"}, new Person { Age=55, Name = "Ole Hansen"}, new Person { Age=40, Name = "Arne Asbjørnsen"}, };

var old = from p in people where p.Age > 25 orderby p.Name ascending select p;

foreach(var p in old) Console.WriteLine(p.Name);}

---Arne AsbjørnsenJonas FollesøOle Hansen

Page 28: Why learn new programming languages

28C# STORYQ EXAMPLE[Test]public void Gutter_game(){ new Story("Score calculation") .InOrderTo("Know my performance") .AsA("Player") .IWant("The system to calculate my total score") .WithScenario("Gutter game") .Given(ANewBowlingGame) .When(AllOfMyBallsAreLandingInTheGutter) .Then(MyTotalScoreShouldBe, 0) .WithScenario("All strikes") .Given(ANewBowlingGame) .When(AllOfMyBallsAreStrikes) .Then(MyTotalScoreShouldBe, 300) .ExecuteWithReport(MethodBase.GetCurrentMethod()); }

Page 29: Why learn new programming languages

29C# OBJECT BUILDER PATTERN[Test]public void Should_generate_shipping_statement_for_order(){ Order order = Build

.AnOrder() .ForCustomer(Build.ACustomer()) .WithLine("Some product", quantity: 1) .WithLine("Some other product", quantity: 2);

var orderProcessing = new OrderProcessing(); orderProcessing.ProcessOrder(order);}

Page 30: Why learn new programming languages

30MONKEY PATCHING

Runtime generation of codeand behaviour

Page 31: Why learn new programming languages

31RUBY ACTIVE RECORD AND METHOD MISSING

Page 32: Why learn new programming languages

32C# DYNAMIC AND EXPANDO OBJECTstatic void Main(string[] args){ dynamic person = new ExpandoObject(); person.Name = "Jonas Follesø"; person.Age = 28;

Console.WriteLine("{0} ({1})", person.Name, person.Age);}

Jonas Follesø (28)

Page 33: Why learn new programming languages

33C# MONKEY PATCHINGpublic class DynamicRequest : DynamicObject{ public override bool TryGetMember(GetMemberBinder binder, out object result) { string key = binder.Name; result = HttpContext.Current.Request[key] ?? ""; return true; }}

@using MvcApplication1.Controllers@{ Page.Request = new DynamicRequest();}

<h4>Hello @Page.Request.Name</h4><h4>Hello @HttpContext.Current.Request["Name"]</h4>

Page 34: Why learn new programming languages

34C# MICRO ORMS

• Afrer C# 4.0 with support for dynamic typing a whole new category of micro ORMs has emerged:

• Massive

• Simple.Data

• Peta Pico

• Dapper

Page 35: Why learn new programming languages

35C# MICRO ORMS

IEnumerable<User> u = db.Users.FindAllByName("Bob").Cast<User>();

db.Users.FindByNameAndPassword(name, password)// SELECT * FROM Users WHERE Name = @p1 and Password = @p2

db.Users.FindAllByJoinDate("2010-01-01".to("2010-12-31"))// SELECT * FROM [Users] WHERE [Users].[JoinDate] <= @p1

Page 36: Why learn new programming languages

36SAPIR–WHORF HYPOTHESIS

The principle of linguistic relativity holds that the structure of a language affects the ways in which its speakers are able to conceptualize their world, i.e. their world view.

http://en.wikipedia.org/wiki/Linguistic_relativity

Page 37: Why learn new programming languages

TAKK FOR MEG

Jonas Follesø

37