Readable, lean and mean codes are necessary

Hi guys!

I know most of you are using VS 2005 (or even VS 2008) and creating best applications. VS 2005 is fun to use and harness, but it has many good best practices in its own code generators. Take for example, the Windows Forms code generator.

 

vs2005_formdesigner

 

It's quite neat, isn't it? Yes, VS 2005 has done this for us. Even since VS 2002, the first VS .NET release.

This idea promotes cleaner and readable code. I bet many of you write code like this:

 

    public partial class FrmUser : csMaintenanceForm
    {

        /// <summary>
        /// Default constructor
        /// </summary>
        public FrmUser()
        {
            this.bizUser = new csUserBusiness();
            this.RegisterPrimaryBizObj(this.bizUser);

            InitializeComponent();
            this.bizUser.LoadAllData();

        }

        protected csUserBusiness bizUser;

        private void SleepForAWhile(int msec)
        {
            System.Threading.Thread.Sleep(msec);
        }
    }

Why don't you reorganize it into this:

 

    public partial class FrmUser : csMaintenanceForm
    {

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public FrmUser()
        {
            this.bizUser = new csUserBusiness();
            this.RegisterPrimaryBizObj(this.bizUser);

            InitializeComponent();
            this.bizUser.LoadAllData();

        }

        #endregion

        protected csUserBusiness bizUser;

        #region Methods

        private void SleepForAWhile(int msec)
        {
            System.Threading.Thread.Sleep(msec);
        }

        #endregion

    }
And make it look like this (after being collapsed by "Ctrl+M,CTRL+O")

vs2005_codereorganized

 

For complex code, I use this arrangement (from first to last):

  • Constructors
  • Properties
  • Methods

Why? These are my reasons/rationales:

  • I put constructors first, since it’s cleaner to know class constructors first and it’s called first time when an object is instantiated.
  • Properties come before methods, because we then want to know what are the object’s attributes are.
    And then what the object do (the object’s operations in OOP terms), and this can mean methods and event handlers.
  • Then, all of the implementation from interfaces is grouped last. This idea comes from VS itself, since VS 2003.

Those rationales come from this simple sequence of job interview questions:

“Hey, I just get to know you. How do I call you? (Constructors) What are your traits and biodata? (Properties) What can you do? (Methods and interfaces implementations)”

Voila! It’s quite simple, in my opinion.

Comments are welcome! :)

 

Eriawan

Share this post: | | | |

Comments

No Comments