Refactor code from presentation to business layer

Way too often the presentation layer contains business logic.  When I recognise this and need to refactor my working order is like this:

myButton_OnClick(... {
    ...do some business logic with control values 
    ...and object variables as input and object
}

I only want very little stuff in the very click event handler.  The less the click event knows about other controls, or the form, the easier it is to change or even remove it.

myButton_OnClick(... {
   DoThis()
}

That was an uninteresting refactoring. Not something worth blogging about. So I make it static, recompile and get rid of the references to object variables.

myButton_OnClick(... {
   DoThis(txtUsername.Text, txtSalary.Text, ddlCompany.Value) 
}

private static void DoThis(string  username, int salary, Company company ){
   ... do business stuff
}

Now I just move the method to the business layer and dig out the remaining bugs (the Company enum was maybe declared in the presentation layer).

myButton_OnClick(... {
   DoThis(txtUsername.Text, txtSalary.Text, ddlCompany.Value) 
}

private static void DoThis(string  username, int salary, Company company ){
   string username = txtUsername.Text
   int salary = txtSalary.Text
   Company company = ddlCompany.Value
   var bl = new BusinessLayer.User()
   bl.DoThis(username, salary, company) 
}

There is nothing magic with this working order.  It is just a way to refactor step by step to avoid to much non-compiling code at once.

Tags:

Leave a Reply