Pages

Friday 4 January 2013

Bad Programming Practices: Never write your application business logic in eventhandlers

Bad Programming Practices: Never write your application business logic in eventhandlers

Writing your application business logic in eventhandlers is a bad programming practice. By doing this, you are mixing your design and logic and making your application more prone to disasters. No doubt your functionality will work fine, but when your senior sits to do your code review, s/he will reject your code. I am trying to explain it by simple delphi example. I will be using 2 methods to implement same functionality.

Method 1:

In the following delphi XE2 example, application logic is written on the click event of OK button. It means when from user interface, user clicks the OK button the application logic will run.

procedure Form1.btnOKClick(Sender: TObject);
begin
  //my application business logic goes here
end;

This application logic can be run by clicking on OK button or just by calling the event handler in your delphi program like following:

btnOK.click; or
btnOKClick(Self.btnOK);

Method 2:

In following delphi XE2 example, same thing is done but in different way. Application logic is written in some delphi function "ApplicationLogic" and is called from the event handler (click of OK button).

procedure TForm1.ApplicationLogic;
begin
 //my application business logic goes here
end;

procedure TForm1.btnOKClick(Sender: TObject);
begin
 ApplicationLogic;
end;

Method 2 is better approach as it encapsulate your actual business logic. by using this approach, you can separate your design logic from application logic and your code will be neat and clear and easy to understand. Your code will be self documented.

Also, directly calling event handlers from program (as in method 1) is quite complex which degrades the performance when your application will grow large.

You can make your code reusable by putting your application logic in some library and then calling the methods of that library from event handlers as well as from other places. Even you can use same methods in some different application by just including that library which contains all your application logic functions. 

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.