Rules to Better Code (legacy) - 3 Rules
Ensure the reliability of your legacy code with these essential rules that focus on proper event handling and interoperability. This set of guidelines will help you maintain and improve the functionality of older codebases effectively.
Sometimes the button's event handler hook-up could be lost by accident, but there will be no warning or error reported when you compile your applications.
this.button1 = new System.Windows.Forms.Button(); this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.button1.Location = new System.Drawing.Point(419, 115); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 60; this.button1.UseVisualStyleBackColor = true;
Bad Example - the event handler hook-up is lost, so there will be no response after you click the button
this.btnResetAll = new System.Windows.Forms.Button(); this.btnResetAll.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnResetAll.Location = new System.Drawing.Point(417, 410); this.btnResetAll.Name = "btnResetAll"; this.btnResetAll.Size = new System.Drawing.Size(75, 23); this.btnResetAll.TabIndex = 54; this.btnResetAll.Text = "Reset &All"; this.btnResetAll.UseVisualStyleBackColor = true; this.btnResetAll.Click += new System.EventHandler(this.btnResetAll_Click);
Good Example : keep the event handler hook-up together with the initialization of the button
VB.NET includes the
CreateObject()
Method for creating the COM object. This is an old relationship between VB and COM.Sub CreateADODBConnection() Dim adoApp As Object adoApp = CreateObject("ADODB.Connection") End Sub
Figure: Bad code - Uses a VB technique
CreateObject()
for creating a COM objectUsing the CreateObject() method affects the performance of your application. The variable adoApp is of type Object and this results in "late binding"
which might lead to so much uncertainty. It is more efficient to use the interoperability features of .NET, which allows you to work with existingunmanaged code (code running outside the CLR) in COM components as well as Microsoft Win32 DLLs. The interoperability feature uses run-timecallable wrappers for handling all interaction between the .NET client code (managed code) and the COM component (unmanaged code).
To add references to COM objects:
- On the Project menu, select Add Reference and then click the COM tab.
-
Select the component you want to use from the list of COM objects.
- To access to the interoperability assembly in your application, add an Imports statement to the top of the class or module in which you will use the COM object.
You can also create interoperability assemblies using the Tlbimp command line utility.
We have a program called SSW Code Auditor to check for this rule.
This is often a bad practice if you already are ending Sub you don't need another line.
Sub MySub ... End Sub Exit sub
Figure: Bad example
Sub MySub ... End sub
Figure: Good example