Closing a Class

Hi All,

I have below code :

    Private Function Check_Data_Ok() As Boolean

        If Me.txtNoTransaksi.Text.Trim = "" Then
            MsgBox("Nomor Transaksi Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtNoTransaksi.Focus()

            Return False
        End If

        If Me.txtCatatan.Text.Trim = "" Then
            MsgBox("Catatan Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtCatatan.Focus()
            Return False
        End If

        Dim clsPublicStoredProcedure As New clsPublicStoredProcedure

        Try

            If Not clsPublicStoredProcedure.Is_Print_Transaction_Exist(Me.txtNoTransaksi.Text.Trim, "") Then
                MsgBox("Nomor Transaksi Tidak Ditemukan ...!", MsgBoxStyle.Information, Me.Text)
                Return False
            End If

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, Me.Text)
        End Try

        clsPublicStoredProcedure = Nothing

        Return True

    End Function

How to always set  clsPublicStoredProcedure   = Nothing what ever the scenario ? Because there is return code there.

Thank you.
LVL 1
emi_sastraAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
May be you can put it in Finally block which (I believe) is guaranteed to execute every time.

Furthermore, not sure why do you want to explicitly do it as all local variables are automatically garbage collected once they are out of scope.

Unless you have some real special case for this class which needs to be explicitly taken care of, which you haven't mentioned.

Any normal / usual class, I haven't particularly been worried about disposing.
0
ste5anSenior DeveloperCommented:
In addition to Nitin's post: You should rely on garbage collection.

Thus to your question: You only need to explicitly set an object reference to nothing, if your code stays for long time in the same scope. In your case this is not necessary, cause you're exiting your function Check_Data_Ok() immediately after using clsPublicStoredProcedure.Is_Print_Transaction_Exist(). Thus it is automatically marked as unused.

Big exception is when using external resources. Then your class should implement the IDisposable pattern (remember, all classes implementing it should be used by using the using clause) or have an explicit Dispose() call in the correct scope.

p.s. clean code principles say that  a function should have only one point of return. Thus I would write the function as follows:

Private Function Check_Data_Ok() As Boolean

    Try
        If Me.txtNoTransaksi.Text.Trim = "" Then
            MsgBox("Nomor Transaksi Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtNoTransaksi.Focus()
            Return False
        ElseIf Me.txtCatatan.Text.Trim = "" Then
            MsgBox("Catatan Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtCatatan.Focus()
            Return False
        Else
            Dim clsPublicStoredProcedure As New clsPublicStoredProcedure
            If Not clsPublicStoredProcedure.Is_Print_Transaction_Exist(Me.txtNoTransaksi.Text.Trim, "") Then
                MsgBox("Nomor Transaksi Tidak Ditemukan ...!", MsgBoxStyle.Information, Me.Text)
                Return False
            Else
                Return True
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.Information, Me.Text)
    End Try

Open in new window

Or using a real single point of return:

Private Function Check_Data_Ok() As Boolean

    Dim Result As Boolean = True
    Try
        If Me.txtNoTransaksi.Text.Trim = "" Then
            MsgBox("Nomor Transaksi Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtNoTransaksi.Focus()
            Result = False
        ElseIf Me.txtCatatan.Text.Trim = "" Then
            MsgBox("Catatan Harus Diisi ...!", MsgBoxStyle.Information, Me.Text)
            txtCatatan.Focus()
            Result = False
        Else
            Dim clsPublicStoredProcedure As New clsPublicStoredProcedure
            If Not clsPublicStoredProcedure.Is_Print_Transaction_Exist(Me.txtNoTransaksi.Text.Trim, "") Then
                MsgBox("Nomor Transaksi Tidak Ditemukan ...!", MsgBoxStyle.Information, Me.Text)
                Result = False
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.Information, Me.Text)
    End Try

    Return Result

End Function

Open in new window


p.s. when the general usage pattern of your class clsPublicStoredProcedure is as shown in your sample, then you should consider making it a shared function in your class.
0
emi_sastraAuthor Commented:
Hi Nitin,

- May be you can put it in Finally block which (I believe) is guaranteed to execute every time.

   Try

            If Not clsPublicStoredProcedure.Is_Print_Transaction_Exist(Me.txtNoTransaksi.Text.Trim, "") Then
                MsgBox("Nomor Transaksi Tidak Ditemukan ...!", MsgBoxStyle.Information, Me.Text)
                Return False  <------
            End If

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, Me.Text)

        Finally
             clsPublicStoredProcedure = Nothing
        End Try

At return false, it also execute the Finally ?

Thank you.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Nitin SontakkeDeveloperCommented:
The following would probably clear all your doubts. And it does confirms what I was saying....

https://www.dotnetperls.com/finally
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
Yes finally always runs no matter the exit point; e.g. -
Module Module1
	Sub Main()
		Console.WriteLine($"{TestAdd(2, 3, False)}")
		Console.WriteLine($"{TestAdd(2, 3, True)}")
		Console.ReadLine()
	End Sub

	Function TestAdd(lhs As Integer, rhs As Integer, isException As Boolean) As Integer
		Try
			If (isException) Then
				Throw New Exception()
			Else
				Return lhs + rhs
			End If
		Catch ex As Exception
			Return lhs + rhs + 10
		Finally
			Console.Write($"Addition completed; {lhs} + {rhs} {If(isException, "+ 10 = ", "= ")}")
		End Try
	End Function
End Module

Open in new window

Produces the following output -Capture.PNG-saige-
0
emi_sastraAuthor Commented:
Hi All,

Thank you very much for your help.
0
Nitin SontakkeDeveloperCommented:
So, finally, you are convinced!
0
emi_sastraAuthor Commented:
Yes. Thank you.
0
Nitin SontakkeDeveloperCommented:
Not sure if you got it, but my comment was intended to be a pun.
0
emi_sastraAuthor Commented:
- Not sure if you got it, but my comment was intended to be a pun.
I am sorry for late provide points.

Thank you.
0
ste5anSenior DeveloperCommented:
And just for clarity:
Using finally in your function to set clsPublicStoredProcedure = Nothing is not necessary, cause you are immediately leaving the function. Thus clsPublicStoredProcedure is marked as unused automatically. And there is no difference in how the instances is handled by GC in both cases.
0
Nitin SontakkeDeveloperCommented:
@ste5an,

That's precisely what I tried to convey in my very first comment:

Furthermore, not sure why do you want to explicitly do it as all local variables are automatically garbage collected once they are out of scope.
0
emi_sastraAuthor Commented:
Hi All,

I think I should use Public shared.
It is more simple to code.

Is it right ?

Thank you.
0
ste5anSenior DeveloperCommented:
I think I should use Public shared. It is more simple to code. Is it right ?
Given your small code sample, yes, then it is (maybe) lesser code and is simpler to consume. And the consuming part was your question. Thus make it a shared function as I already recommended.
0
emi_sastraAuthor Commented:
Yes. I do understand now.

Thank you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.