KoffeeKoder


  • One thing that I have frequently witnessed in the Ruby Language is the use of very small methods. Most of the methods/functions I have seen in Ruby are only couple of lines long. This is a very good programming practice and we can learn to write smaller methods in .NET.

    First here is the Ruby method Strip which is used to remove leading and trailing white spaces:


    static VALUE
    rb_str_strip(str)
        VALUE str;
    {
        str = rb_str_dup(str);
        rb_str_strip_bang(str);
        return str;
    }


    Now, let's move to .NET. Here is one very simple example which uses the bank transfer feature:


    [TestFixture]
        public class when_customer_transfer_balance_from_wamu_account_to_boa_account
        {            

            [Test]
            public void should_deduct_balance_from_wamu_account_and_deposit_balanace_to_boa_account()
            {
                Account wamu = new Account();
                wamu.Balance = 100;

                Account boa = new Account();
                boa.Balance = 0;

                wamu.Transfer(20).To(boa);

                Assert.AreEqual(80, wamu.Balance);
                Assert.AreEqual(20, boa.Balance);
            }
        }


    And here is the code for the Account class:


    public class Account
        {
            private double _balance;
            private double _amount;

            public double Balance
            {
                get { return _balance; }
                set { _balance = value; }
            }

            public double Amount
            {
                get { return _amount; }
                set { _amount = value; }
            }

            public Account Withdraw(double amount)
            {
                _balance -= amount;
                return this;
            }

            public Account Transfer(double amount)
            {
                _amount = amount;
                return this;
            }

            public Account Deposit(double amount)
            {
                _balance+= amount;
                return this;
            }

            public void To(Account account)
            {
                account.Deposit(_amount);
                this.Withdraw(_amount);
            }

        }


    Of course, the above code just moves the amount from one memory object to another but we can always plug in our own data access layer. The point I want to make is the simplicity and clarity of the code. Also, take a look at the above methods and see how simple they look.