473,804 Members | 3,548 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Should I Use "Dim ___ As New ___"?

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
Mar 15 '06
17 1585
"Tim Baur" <tr**********@A RDyahoo.com> wrote in message
news:Xn******** *************** ***********@207 .46.248.16...
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 InterestingModu le(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_a ctivity(param1)
End Sub

' Would BE REPLACED BY

Sub InterestingModu le(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.Cr eateFudgeType()
fubar.perform_a ctivity(param1)
End Sub

The change is subtle but VERY important. By having a seperate method
(CreateFudgeTyp e) 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/..._Factories.pdf
-- Perspectives of Use vs. Creation in Object Oriented Design, Netobjectives
e-zine,
http://www.netobjectives.com/ezines/...InOODesign.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/....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.
--
Mar 15 '06 #11
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
"jvb" <go*****@gmail. com> wrote in message
news:11******** *************@p 10g2000cwp.goog legroups.com...
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.

Mar 16 '06 #12

Tim Baur wrote:
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.

--
Larry Lard
Replies to group please

Mar 16 '06 #13
"Nick Malik [Microsoft]" <ni*******@hotm ail.nospam.com> wrote in
news:pL******** ************@co mcast.com:
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.
Mar 16 '06 #14
"Larry Lard" <la*******@hotm ail.com> wrote in news:1142504076 .123444.95700
@j33g2000cwa.go oglegroups.com:
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.
Mar 16 '06 #15
> 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 InterestingModu le(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_a ctivity(param1)
End Sub
' Would BE REPLACED BY

Sub InterestingModu le(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.Cr eateFudgeType()
fubar.perform_a ctivity(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.Net
Mar 16 '06 #16
>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/de...el.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/archi...11/241027.aspx

So lets not forget the fine YAGNI and KISS principles.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 16 '06 #17
"Mattias Sjögren" <ma************ ********@mvps.o rg> wrote in message
news:OF******** ******@TK2MSFTN GP11.phx.gbl...
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/de...el.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/archi...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.
--
Mar 17 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
21557
by: Monte | last post by:
It compiles fine in one of my ms2002 databases, but on another db (I inherited from somebody else), I get this compile error: "User-defined type not defined" Is something turned off in this second db or something? Thanks much
3
17002
by: Bart Lateur | last post by:
For some reason, "Database" isn't recognised by Access as a built-in/predefined type, in Access' own VBA. Whenever I try to compile a line like Dim db as Database I get the complaint that that user defined type ("database") isn't defined. This happens both in Access 97 (on Win98) and in Access 2000 (on XP). I seem to recall this used to work on Access 2. For the rest, Access works normally.
2
1897
by: Peter Ignarson | last post by:
Hi, simple question Is there a syntax (other than the one below that is invalid) that will let me declare and initialize two variables at the same time (using VS 2003, 1.1) ? Thank you Pete Dim a,b As Integer = 6 'Syntax error, invalid
4
5542
by: Vincent Finn | last post by:
Hi, in some code I have there is a variable declared as Dim as String what is the for in this case? I thought it was an array at first but as far as I can tell the variable is just a string
3
1023
by: Tony Bansten | last post by:
Occasionally I saw VBS script where local variables were declared on top with a statement like DIM myvar However most of my own vbs script run without such declaration. When do I need them and when not? Tony
11
4244
by: Anil Gupte/iCinema.com | last post by:
When I use this Dim instance As New Timer I get the error: Error 1 Overload resolution failed because no accessible 'New' accepts this number of arguments. Yet, in the help section for Timer (in VB 2005) this is exactly the syntax shown. I also tried:
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10326
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10317
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9143
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.