Coding Practices and list of Frequent Errors
We have recently concluded a project and project closure meeting is conducted in order to ascertains the views/experience of stake holders especially developers. The project was about customizing ArcMap with set of new commands and tools using Microsoft .NET Technology. The project was developed by the team of junior programmers (first time coders) lead by a senior developer.
I would like to come out with the list of frequent errors committed by programmers, missing validations and performance improvement ways. I have briefly discussed here. You can take this as a check list before start coding. There is no particular order followed in this list.
1. System.NullReferenceException – “Object reference not set to an instance of an object.”
This is the most frequently committed error by every developer. I would rate this error as an top rated one. You see people asking about this everywhere; about why are they getting this error. This error primarily occurred when coders are not seriously looking at the Objects created for the class. Below are a few common causes for this
Cause: You are trying to use a reference variable whose value is Nothing/Null.
• When the value is Nothing/null for the reference variable that means it is not actually holding a reference to an instance of any object.
• You either never assigned something to the variable, never created an instance of the value assigned to the variable
• You set the variable equal to Nothing/null manually, or you called a function that set the variable to Nothing/null for you.
I wish to highlight that there is a difference between C#. NET and VB.NET. In certain instances VB.NET code will compile whereas the C# even not allow do this. This is for generic cases for example accessing string.
C#.NET won’t compile
if (a.Length == 0)
VB.NET will compile
Dim a As String
If a.Length = 0 Then
But, there will be case in ArcObjects like this.
pMxDoc = m_MxDoc
pMap = pMxDoc.FocusMap
pFeatureLayer = pMap.Layer(0)
Dim Test As String = pFeatureLayer.Name
pFeatureClass = pFeatureLayer.FeatureClass
pFeatureCursor = pFeatureClass.Search(Nothing, False)
pFeature = pFeatureCursor.NextFeature //Culprit is here
We have written code and tested several times works well. But, when Layer (0) doesn’t have any features its throws an ugly error. We may test the code several times with the contents while there were no features and trying the get the Feature object it explodes. This is one such sample.
There are ‘n’ numbers of ways to cause this error in ArcObjects. I always suggest to check whether object is not ‘Nothing’ or object reference is properly set. Give higher importance when dealing with objects particularly while using COM objects.
2. ‘Maximum open cursors exceeded’ or ‘Layer in Use- Maximum number of streams exceeded’
This is also another frequent error which developer does. The maximum cursors will be opened while loop through recordset.
Where: Looping through a recordset using IFeatureCursor may cause the above error:
Garbage collection takes care of releasing resources in managed code. This process is non-deterministic and will release resources at some undetermined time. In most cases this approach works fine, however in this situation it is necessary to mark the COM object as eligible for garbage collection so the resources will be released in a timely manner. i.e. Explicit release of COM Objects when once usage is completed.
3. Opening and Closing Database Connection using predefined Methods.
It is best practice to open and close database connection using separate common methods by passing its parameters. We have to use this method whenever we need to open/close DB connection. It is also advisable that we need to close the DB connection on ‘Finally’ block; this prevents keeping the connection open when error has occurred in method.
// Open Connection
// Do Something…..
Catch (Exception ex)
//Show Error Messages
//Release unwanted Objects
//Close DB connection
//Close DB Connection here as well…
4. Checking ArcObjects License using AoInitialize object
It is very important to check license availability of the application developed. Especially while using ESRI products understanding License Concepts is bit tough if you are novice. It is worth to give a reading on EDN about license on ESRI products.
Whenever we develop a project first and foremost requirement gathered is product/license used at client side. We have to ascertain the Product used along with Service Packs. As developer we may develop with product used at our organization. This brings greater conflict if you mismatched. Its strongly recommend you to use same product license and service similar to client environment. This will reduce major pain during deployment.
Here are other frequent errors which should be taken care of
5. Use of Feature Class names for all validation; avoid using layer name which may change at any course of time
6. Whenever updating (inserting) data in database in bulk use IFeatureBuffer/IRowBuffer interface for better performance.
7. Always use Try/Catch Block in each and every subroutine/method. This is MUST for any disciplined programmer. Otherwise it would be of hell later when you encounter errors at final stage.
8. IndexOutofRange/ ArrayBound Exception/Over Flow erros/InvalidCast Exception are few common errors can be avoided easily by taking little care while coding. Read OMD for better usage. Especially while using C#.NET casting objects is very vital. There is a performance difference between two ways of casting.
a. pFeatLayer = (IFeatureLayer)pLayer;
a. pFeatLayer = pLayer as IFeatureLayer ;
9. Use of proper collections plays huge role in performance e.g. ArrayList in place of HashTable . The hashtable is used to retrieve value using Key/Value pair whereas Arraylist to use to store the content that cannot be accessed at random. Usage of collection should be judicious. Note, key has to be unique while storing in hash tables otherwise throws an error. Determining which variable to store as key and which as value is paramount importance while retrieving. We often mismatch and take a long detour.
10. Providing proper Error Messages.
User doesn’t want detailed error message or stack trace, providing meaning full error message is very important. I suggest using resource files for doing this job. The usage of constants and providing simple, meaningful message makes application user friendly.
11. Use of proper Enumeration while using Collections- Enumeration, Dictionary etc
12. File Not Found/Read-Write Error.
Sometimes we need to write data in text/excel file, we must check whether file exists or not at the specified path and then proceed further. At times file which we are about to write will be opened by others or shared, we have to handle such situations. Use of System.IO.Exception solves the issue. Here is an sample code in VB.NET
pStreamWr= New StreamWriter(strFoldPath + “\” + abc + “.csv”)
blnOpen = False
Catch ex As IOException
MessageBox.Show(abc + “.csv file is already in use. Please close the file and click Ok.”)
blnOpen = True
Catch ex As UnauthorizedAccessException
MessageBox.Show(abc + “.csv file property is Read-only. Please change the file property and click Ok.”)
blnOpen = True
13. Usage of Constants throughout the project helps managing application easier. For example Message Box title /Form Title have to constant through out the application, hence usage of application level constant will solve the issue. Using resource file will be handy and easier.
14. Editing Concepts:
When to use pooled vs. non-pooled objects in case of Web Application is another question which we come across often. General practice is if your edits are quick, and you do not need to have un-do / re-do type capabilities, you apply them against a pooled object.For example – if you just need to insert a point into a layer – collect the x, y and attribute information via your web front end, and then create the feature in one transaction. This will work with a pooled object just fine.
If you want to have a longer running edit session, where the save is not automatically committed back to the database, use a non-pooled object.
15. Avoid simple errors like – allowing users to type in Dropdown list, this is prevented setting appropriate property in the control; Form will be opened multiple times on clicking command has been avoided by setting as Modal.
These are some of the points which has brought out at this instance. Many of developers may use better coding practice to avoid these sorts of error, but these points will be useful for many who just begin coding. As I said in top of this post these are used as check list to avoid frequent errors. If this post helps please drop your comments/Suggestion, you may suggest few more points to this one.