Should I Use "Dim ___ As New ___"?

  • Thread starter Thread starter Tim Baur
  • Start date Start date
T

Tim Baur

Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?


TIA
~Tim
 
There is a bit more flexibility in declaring first and instantiating second
that *may* be usefull in certain scenarios. Other than this, it doesn't
matter.
 
Using New is required except when using shared members of the class.
The new keyword creates a reference to the object that you are using.
 
Tim Baur said:
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general
question about variable declaration. In VB, I've always tried to
avoid using the "As New" construct when declaring a variable
preferring instead to instantiate in the class' or form's initialize
event or as needed. Using "As New" created unnecessary overhead and
resulted in a loss of control over my object's life cycle.

Is this advisable practice in .Net?

The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this does
not exist anymore. Now it means that the object is created as soon as the
variable is created. So, if you write

dim bla as new form

in a procedure, it is exactly the same as writing

dim bla as form
bla = new form


If you declare it at class level, it is exactly the same as writing

dim bla as form
'...
sub New()
bla = new form
end sub


See also:
http://msdn.microsoft.com/library/en-us/vbcn7/html/vaconObjectCreation.asp


Though, it is sometimes not advisable, but this is personal taste. I always
assume that the order of declaration doesn't matter. This is not true
anymore if the declaration contains a New statement. Example:

dim con as new oledbconnection(...)
dim cmd as new oledbcommand(con)

You see that the app will fail if you change the order because the 2nd
statement depends on the 1st one.



Armin
 
The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this
does not exist anymore. Now it means that the object is created as
soon as the ...


Thank you all for the input. Thanks for the thourough analysis, Armin.
This is good news -- I had hoped VB.Net would handle it this way.
 
Tim,

Dim ds as new Dataset
For each whatever
ds = new Dataset
'The first instanced object will only be cleaned up unused by the GC

Therefore you can do better
Dim ds as Dataset
For each whatever
ds = new dataset

Although when I don't need the dataset outside the loop I prefer even

For each whatever
dim ds as new Dataset

I hope this gives some ideas

Cor
 
For each whatever
dim ds as new Dataset

In this example, ds scopes the loop and drops the reference on completion?
Nice, very C-ish.

This brings up a new question, if I followed the example above, wouldn't a
thousand whatevers result in ds being created a thousand times? A thousand
sets of variables on the stack, memory reservations, methods registered,
constructors running, etc.

If I instantiate ds outside the loop and reuse the reference, haven't I
saved effort?
 
Tim Baur said:
I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

There is no difference between 'As New X()' and 'As X = New X()' in VB.NET
any more. Personally I prefer 'As New' because it makes code more compact.
 
Tim Baur said:
The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this
does
not exist anymore. Now it means that the object is created as soon as
the
variable is created. So, if you write
dim bla as new form

Not only that, but in VB6 if you re-referenced a variable which was previously
set to nothing, you would re-instantiate it. This was the main reason to
avoid the Dim x as New foo in VB 6. You no longer need to worry about that.

Jim Wooley
 
Tim,
This brings up a new question, if I followed the example above, wouldn't a
thousand whatevers result in ds being created a thousand times? A
thousand
sets of variables on the stack, memory reservations, methods registered,
constructors running, etc.

If I instantiate ds outside the loop and reuse the reference, haven't I
saved effort?

That was why I showed it, in all those except the first will the same amount
of ds be instanced. In the first sample is that plus 1. However why bother
you are using managed code that is especially for this.

Cor
 
Tim Baur said:
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?


TIA
~Tim

The other responses have covered the language-specific concerns and the
difference in language behavior for VB.Net. Part of the reason that you
were following the 'best practice' that you were... was because of a gotcha
in VB that has been addressed in VB.Net.

However, there is also a design question here. Just because we have solved
the language 'gotcha,' this does not mean we should lose sight of a core
'best practice' for OOP: You should seperate creation from use.

The concept goes to the heart of design patterns. You have patterns for
creation that allow entire structures of objects to be created, allowing
configuration files to fundamentally alter the behavior of the system
without the app developer being required, at every step, to check the config
file. Seperately, you have structural and behavioral patterns that are used
to model the seperation of concerns. The goal here is to minimize code
churn when a design change is necessitated by changing requirements.

By seperating creation from use, we can leverage all three pattern classes.

What this looks like in code is another thing altogether. Code that looks
like this:

Sub InterestingModule(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_activity(param1)
End Sub

' Would BE REPLACED BY

Sub InterestingModule(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.CreateFudgeType()
fubar.perform_activity(param1)
End Sub

The change is subtle but VERY important. By having a seperate method
(CreateFudgeType) that creates the 'fudge' object, we can isolate the logic
for creation patterns. This allows an object that is decended from the
fudge type to be returned, instead of the parent object itself. This allows
the fudge type to be an interface only (not possible in the first code
snippet... entirely possible in the second).

This type of factory pattern does not work when you say
Dim fubar as new fudge
because the module with that line is coupled to the concrete 'fudge' class.
This is a form of tight coupling that can be easily avoided.

So, just because we 'can' say Dim fubar as new fudge, that doesn't mean we
'should.' It's bad practice.

This concept has been written about extensively. If you'd like to dig up
some of the opinions of the well known thinkers, try:
-- Java's New Considered Harmful, DDJ 04/2002,
http://www.ddj.com/documents/s=7027/ddj0204a/0204a.htm
-- Lessons from OODesign: Factories, Design Patterns Explained (Chapter 20),
http://www.netobjectives.com/ezines/ez0406NetObj_LessonsFromDesignPatterns_Factories.pdf
-- Perspectives of Use vs. Creation in Object Oriented Design, Netobjectives
e-zine,
http://www.netobjectives.com/ezines/ez0405NetObj_PerspectivesOfUseVsCreationInOODesign.pdf

You can also find notes on the creation patterns by looking up things like
'abstract factory pattern' and 'factory method pattern'.


--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://www.netobjectives.com/ezines...InOODesign.pdfhttp://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
 
I don't think that's what the question was about. The question was whether
to write this:

Dim x As Object
x = New Object

....or, write this...

Dim x As New Object


-Scott
 
Tim said:
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?

The thread has shown you that Dim X As New Thing is OK in VB.NET; one
thing to consider, though, is that if you are still using VB6 on a
day-to-day basis, it's worth explicitly NOT using this syntax even in
VB.NET, lest you inadvertently use it in VB6.
 
This type of factory pattern does not work when you say
Dim fubar as new fudge
because the module with that line is coupled to the concrete 'fudge'
class. This is a form of tight coupling that can be easily avoided.

So, just because we 'can' say Dim fubar as new fudge, that doesn't
mean we 'should.' It's bad practice.
...

I have always been in the habit of writing a data class that handles
information flow and using a LoadData method on the object in question.
The caller would look to the data class as a source, and send the
information to the Object. It's a step up from calling each property
individually, but it calls upon the developer to know to use LoadData to
give the instance an identity.

I've used my share of third party libraries that were developed like this.
They can be a challenge to implement if you aren't privy to the internal
code. It also leads to buggy situations in which the class might be
employed before being properly initialized with values.

Thank you for sharing your thoughts, Nick, and for the excellent links. I
will have to try your approach in my current project.
 
The thread has shown you that Dim X As New Thing is OK in VB.NET; one
thing to consider, though, is that if you are still using VB6 on a
day-to-day basis, it's worth explicitly NOT using this syntax even in
VB.NET, lest you inadvertently use it in VB6.

I think that this is what I will probably do, Larry. Besides, the fact
that an object is Nothing is informative. It's like the database concept
of Null.
 
By seperating creation from use, we can leverage all three pattern
classes.

What this looks like in code is another thing altogether. Code that
looks like this:

Sub InterestingModule(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_activity(param1)
End Sub
' Would BE REPLACED BY

Sub InterestingModule(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.CreateFudgeType()
fubar.perform_activity(param1)
End Sub

I'm glad MSFT is acknowledging the factory patterns finally. It would be
nice to remove the requirement for a parameterless default constructor on
the business classes for UI binding purposes. Is this something we could
look for in the future?

Jim Wooley
http://www.devauthority.com/blogs/jwooley
MCSD.Ne
 
So, just because we 'can' say Dim fubar as new fudge, that doesn't mean we
'should.' It's bad practice.

I wouldn't go as far as saying that it's bad practice. Using the
factory pattern makes sense sometimes but using it too much has it's
own set of problems. Just look at how messy some frameworks
(especially in the Java world) are to use because of overuse of
factories. Reminds me of this post

http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

Even the .NET design guidelines recommend using public constructors
over factories unless you have a good reason not to.

http://blogs.msdn.com/kcwalina/archive/2004/10/11/241027.aspx

So lets not forget the fine YAGNI and KISS principles.


Mattias
 
Mattias Sjögren said:
I wouldn't go as far as saying that it's bad practice. Using the
factory pattern makes sense sometimes but using it too much has it's
own set of problems. Just look at how messy some frameworks
(especially in the Java world) are to use because of overuse of
factories. Reminds me of this post

http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

Even the .NET design guidelines recommend using public constructors
over factories unless you have a good reason not to.

http://blogs.msdn.com/kcwalina/archive/2004/10/11/241027.aspx

So lets not forget the fine YAGNI and KISS principles.

That's something about a forum with a bunch of smart folks... never be too
general!

How about this: Seperating creation from use is good practice.

On the other hand, if you are still learning OO design, it is better, in my
opinion, to err with too many factories than too few.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
 
Back
Top