?
Solved

How do I handle a function method that could return null in vb.net?

Posted on 2011-10-21
18
Medium Priority
?
317 Views
Last Modified: 2012-05-12
I'm sure I have read this somewhere, but how is the best way to handle this situation?

Let's say I have a function that returns a DataTable.  The result of this function is based on if there are files in a certain location or not. If there are no files, then the function would either return null, or I should not call the function at all.  So it seems like I should create a method that checks for files that is called first then based on those results, calls another method that returns the DataTable if it's there.  The thing is, it would be nice to just call one method to get it all done. What happens if there is a null though? Do I just check for a null, or just pass a DataTable object with nothing in it, and check that it's empty?
Public Function NewFiles() As Boolean
          ' Check to see if log file date stamp is earlier than last write time in repository folder
          ' also checks to see if log exists
          ' the log file logs when files have been checked
          ' since this file is updated every time files are processed one can compare this file
          ' date to the file dates in the repository to know if a file is dropepd or not
          ' since the repository is read only all files remain in the repository even after
          ' they are dropped
          NewFiles = False
          m_checkLogResult = CheckLog(m_carrierName, m_logFileSpec, m_repoPath)
          Select Case m_checkLogResult
               Case CheckLogResult.LogFileDoesNotExist
                    MessageBox.Show("Log file does not exist.")
                    Exit Function
               Case CheckLogResult.NoNewFiles
                    Return False
               Case CheckLogResult.NewFilesExist
                    Return True
          End Select
     End Function

Open in new window

Public Function GetFileList() As DataTable

' What if this returns a void DataTable?

 End Function

Open in new window

0
Comment
Question by:harmono
  • 8
  • 4
  • 3
  • +1
18 Comments
 
LVL 1

Author Comment

by:harmono
ID: 37009404
I'm thinking MyFunction() As Object will allow me to return either a Boolean, or a DataTable, and return False if there is nothing to return. That way if someone uses my function they will see that it returns an object and have to know how to respond to what object. Does this make sense?
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1000 total points
ID: 37009436
You could return Object, but you (and others behind you) would have to know the semantics of returning Object. That is, whether or not the function is returning a Boolean or a DataTable. In my opinion, it's just as easy to test for Nothing on the return value. But let me ask this:  why not return an empty DataTable if there are no records? Wouldn't that be a more intuitive way--for both you and your code--to know that there were no files found?
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37009493
let the function return an object and in the calling function try and run your code as normal (i.e as if the returned object is a datatable) encapsulated in a try ... Catch. that way you know if it throws an error then the result was a null / nothing and you can doany cleanup in the finally part
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37009517
Use a try/catch to catch a known condition? That's sloppy programming.
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37009542
returning an empty datatable can be contrued as a waste of resources too, sloppy programming in your language if you like. Short of my suggestion, I'd get the type of the returned object and execute  a select statement for the two known results., but I did not hear you suggest that .....
0
 
LVL 40
ID: 37010169
kaufmed is right, when you can use a better method than a Try...Catch, do it. A Try Catch is for an exception, not an expected situation.

nepaluz is right, returning an empty datable is a waste a ressource.

The solution is simply to return Nothing.

Public Function GetFileList() As DataTable
    If <This returns a void DataTable> Then Return Nothing
End Function

Open in new window


When you call the function, simply handle it with something similar to the following:

Dim table As DataTable
table = GetFileList()
If table Is Nothing Then
    'Nothing in the table
    MessageBox.Show("Sorry, nothing in the Table")
Else
    'work with table
End If

Open in new window


No empty table. No Try...Catch. The table variable has simply not been instanciated.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37011088
The solution is simply to return Nothing.
I beg to differ. That is not a solution...  it is a preference. And it is a preference that MS itself advocates against:  http://blogs.msdn.com/b/ericlippert/archive/2009/05/14/null-is-not-empty.aspx
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37011117
That is not a solution...
That is not the solution...
0
 
LVL 40
ID: 37011163
@kaufmed

Yes, somebody at Microsoft (it's a blog, so it is not an official recommendation) advocates against it, but for a unique value from a database, and for a String. Not for the table itself. A table cannot be Empty of Null in the sense that is described in the blog. Empty applies only to string. A Null in that discussion is a Null field. It does not have the same meaning as Nothing or (the C# null). A Nullable variable is used with value objects, because there is no way to determine if they have been initialized or not. It is useless with a reference object such as a DataTable.

There are a ton of methods in the framework that return Nothing instead of throwing an exception under circumstances where the object cannot be created. If Microsoft did not advocate it, they would not use it.

Letting the system trigger an Exception requires it to create the Exception object, build up the StackTrace, and get extra information for many Exceptions. If you can do otherwise, you save resources.

Returning a Table with no rows is also a very good way to lose resources for nothing, because you are creating a useless object that will have to be destroyed by the GC without having ever being used.

Returning Nothing has absolutely no impact.

So I do not thing that this is a preference.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37011187
@JamesBurger
Yes, somebody at Microsoft...
Yes, because I quoted some random guy at the MS help desk. From his S.O. profile:

Eric Lippert is a principal developer on the Microsoft Visual C# compiler team.

What would he possibly know, right? And before you go off on some "But he's a C# developer" tangent, let's remember that we are talking about .NET here. The concepts would still apply.

This is a matter of over analyzing for performance reasons. So what if there is another object for the GC to collect? That's its job. Code should be clear in its intention. I agree with the post that I referenced in that returning Nothing implies from the function, "I did not know how to create a DataTable for your request. This could imply some exceptional situation occurred within the function. Returning an empty DataTable indicates, "I did not find any records for your request."

Returning Nothing throughout your code means you now have to also include checks for Nothing throughout your code. More code to maintain. If you are writing all of the code, meaning you control the all aspects of it, then returning an empty DataTable means you can know that you will never encounter a NullReferenceException if you simply use the returned object--without having to explicitly check for Nothing. If you return an empty DataTable and subsequently use it in a foreach to inspect its row count, runtime of your is unaffected--there is nothing to process.

The reason I discounted the try/catch method is because throwing that out implies that any time you want to check some condition, using a try/catch is preferred. I think we all agree this is not the best practice. Suggesting this method gives a false impression to new developers.

So I do not thing that this is a preference.
Then you must not understand what it means when you are given two choices and you can select one over the other  ; )

@harmono

As you can see in this post alone, the choice is hotly debated. It is a matter of preference. Make your code understandable. You, or others behind you, will have to maintain the code at some point. You should be able to quickly determine the meaning of your code if you have to look it over at some point. Making decisions early in the development process based on performance alone is a sure way to guarantee that you will be un-performance-enhancing your code at some later date. Focus on learning the Framework and as you gain more experience, you will begin to know where you can safely enhance performance. I am speaking from experience here.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37011192
I forgot to add that when the code is not under your control, meaning you are using some external library, then checking for Nothing or catching exceptions makes sense.
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37011227
splitting hairs done, the function should return an object of nothing or datatable, depending ... (was it a dataset?)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37011238
You should give me unrestricted access to your bank account.

See, I can make unqualified statements too!
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 37011275
what, with all the 250 quid still in it?
0
 
LVL 1

Author Comment

by:harmono
ID: 37011780
My particular project is small, so probably returning nothing would be the least verbose solution, but I was asking this from a best practices standpoint, i probably should mention that in many cases no data would be found. I think an 80 20 rule can apply, so in some cases returning an empty database seems right. In my case, probably returning nothing will work. I was not sure that would work.
0
 
LVL 40
ID: 37012080
@kaufmed

If you return an empty DataTable, you have to check everywhere if it contains data. Checking everywhere for Nothing is not more trouble. Not counting the fact that usually, specially if there is nothing to return, the process is stopped in some way because there is nothing to do. So I do not believe that you would have to checks throughout your code.

I stick to the opinion than returning Nothing is better than instantiating an object that won't be used. There might be other situations that would be better with another solution, but not this one.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37012290
If you return an empty DataTable, you have to check everywhere if it contains data.
Really? So you're saying this:

DataTable d = SomeFunctionThatReturnsADataTable();

if (d != null)
{
    foreach (DataRow row in d.Rows)
    {
        // Do someting with row
    }
}

Open in new window


is better than this:

DataTable d = SomeFunctionThatReturnsADataTable();

foreach (DataRow row in d.Rows)
{
    // Do someting with row
}

Open in new window


Call me crazy, but I think the last one checks that data exists. Am I missing something?

For giggles, let's stick with your option of returning null. Do tell:  how does harmono know that the return of null was because his function found no files or that his function encountered an error, and could not determine if there were files?
0
 
LVL 1

Author Closing Comment

by:harmono
ID: 37021629
Returning a DataTable with no records is the most sensible way of doing this, although it may take up more resources than returning Nothing, it follows the concept of encapsulation best, because a DataTable is expected, and the person using the method should expect the possibiltiy of no records returned.
In my particular example, it seemed at first to be strange to intentionally return a DataTable when it's known that sometimes there will be no new files, however, a single type return is more appropriate. Another method that checks to see if there are files and returns either a count, or a boolean true, could be used in order to preserve resources. One could also use overloading on the same method calling the method with an optional boolean flag to return either a boolean, or a datatable.  MyMethod( ByVal CheckForFiles As Boolean) As Boolean.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question