473,761 Members | 8,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Declaring variables in the middle of your code.

CR
I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.

Here is how all the examples I've seen so far create an OleDbCommand
Object:

Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

I had to figure out that it was the same as this:

Dim cmd as new OleDbCommand
cmd.CommandText = "SELECT * FROM Table1"
cmd.Connection = cnn

I know it takes 3 lines but at least I know how to reuse it later. How
to you reuse the variable in the first example? I know you could do
this:

'first use
Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

'second use
cmd.CommandText = "SELECT * FROM Table2"
cmd.Connection = cnn2

But that seems inconsistent, plus I have to figure out which
properties were which in the declaration (CommandText and Connection).

I know I'm being picky but this is bugging me! I'm old school. Or
maybe just old!

Chuck.
Nov 20 '05 #1
15 2968
It doesn't matter where you declare your local variables inside your
procedures. The compiler/runtime will set a variable declaration block for
each procedure, and this happens before any code actually runs (because in
..NET, the stack is carefully managed, and always fixed for any given member
call). This adds a level of security and is one of the things that helps
prevent buffer overruns.

However, from your example, it seems you are more interested with
Constructors. Constructors are special procedures that build class instances
(when you call New). They weren't available as such in VB4/5/6, but are
..NET. They help keep the code more compact, among other things. In certain
cases, they prevent class instances from being in an incomplete or invalid
state because the object must be initialized to correct values as soon as it
is created. Every class can define as many constructure procedures as
necessary, each with different parameters. You can only use the old style
instanciation if the class provides a constructor with no parameters (which
most do). Sometimes (but not always), using the constructor can be a tad bit
faster in execution speed than calling the individual properties. This is
not guaranteed.
Other than the cases where no Parameterless (Default) Constructor exists,
whether you use optional constructors vs. specifying one property at a time,
is basically a matter of choice.
I'm sure some people will call it old-school though :-)

-Rob Teixeira [MVP]

"CR" <cr***@hotmail. com> wrote in message
news:1a******** *************** ***@posting.goo gle.com...
I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.

Here is how all the examples I've seen so far create an OleDbCommand
Object:

Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

I had to figure out that it was the same as this:

Dim cmd as new OleDbCommand
cmd.CommandText = "SELECT * FROM Table1"
cmd.Connection = cnn

I know it takes 3 lines but at least I know how to reuse it later. How
to you reuse the variable in the first example? I know you could do
this:

'first use
Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

'second use
cmd.CommandText = "SELECT * FROM Table2"
cmd.Connection = cnn2

But that seems inconsistent, plus I have to figure out which
properties were which in the declaration (CommandText and Connection).

I know I'm being picky but this is bugging me! I'm old school. Or
maybe just old!

Chuck.

Nov 20 '05 #2
CR,
I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this? I find having declaration of the variable is by the code that uses it,
making it easier to see what the declaration is. Also as your example shows
it allows you to initialize the variable when you declare it.

Sometimes you can actually scope the variable to the specific statement, for
example:

' VS.NET 2003 syntax
For Each index As Integer = 0 to 9
' do something with index
Next

The 'index' variable is only valid within the For statement.
It seems like it makes it hard to reuse variables. Reusing variables is not always a good idea!

If you set a variable at the top of your function, then use it at the bottom
of your function, then later decide to "reuse" it in the middle of your
function. Hopefully you find the problem right away, rather then 6 months
later, when a problem occurs...
But that seems inconsistent, plus I have to figure out which
properties were which in the declaration (CommandText and Connection). I find your example a good example of why NOT to reuse a variable, not where
reusing it is a good idea.

I would actually define cmdTable1, cmdTable2 variables which effectively
eliminates your problem of "which properties were in the declaration"). As
you know what is in which variable, and you don't need to worry about when
is this variable this & when is it that. Further I would consider having two
routines, SelectTable1 & SelectTable2 that created & executed the
commands...

Note when I do want to reuse the variable (name) I normally do:
Dim cmd as OleDbCommand 'first use cmd = New OleDbCommand("S elect * FROM Table1",cnn)
'second use cmd = New OleDbCommand("S ELECT * FROM Table2", cnn2)

Notice I am reinitializing the variable itself as to avoid reusing the
object, which can cause problems.

Another trend I hope you are noticing is to have smaller more dedicated
functions, rather then larger more general functions.

Martin Fowler's book "Refactorin g - Improving the Design of Existing Code"
by Addision Wesley http://www.refactoring.com, offers a number of 'smells'
in code and how to correct them. I don't see where he explicitly suggests to
put the declaration by the use, however it does appear that it is an
implicit practice. Also he promotes the smaller dedicated functions/object
over the larger more general function/object practice of coding.

Hope this helps
Jay

"CR" <cr***@hotmail. com> wrote in message
news:1a******** *************** ***@posting.goo gle.com... I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.

Here is how all the examples I've seen so far create an OleDbCommand
Object:

Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

I had to figure out that it was the same as this:

Dim cmd as new OleDbCommand
cmd.CommandText = "SELECT * FROM Table1"
cmd.Connection = cnn

I know it takes 3 lines but at least I know how to reuse it later. How
to you reuse the variable in the first example? I know you could do
this:

'first use
Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

'second use
cmd.CommandText = "SELECT * FROM Table2"
cmd.Connection = cnn2

But that seems inconsistent, plus I have to figure out which
properties were which in the declaration (CommandText and Connection).

I know I'm being picky but this is bugging me! I'm old school. Or
maybe just old!

Chuck.

Nov 20 '05 #3
Cor
Hi CR,

A old style answer,
I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.
What is 100bytes in a computer from today.
The benefit is that your variables are always new and you do not have to
test if you can use them at that moment.
'first use
Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)

'second use
cmd.CommandText = "SELECT * FROM Table2"
cmd.Connection = cnn2

In this way you can use your command a lot of times.
By instance when you are building a new table in the database

I think old school however probably young enough to change. Otherwise it
would not botter you anymore.

With VB.net you can do things as effective as you want, depending on things
as; is it often running, is it a one time program, is it etc etc.

I hope this gives an idea?

Cor
Nov 20 '05 #4
CR
"Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message news:<uW******* ******@TK2MSFTN GP11.phx.gbl>.. .

However, from your example, it seems you are more interested with
Constructors. Constructors are special procedures that build class instances
(when you call New). They weren't available as such in VB4/5/6, but are
.NET. They help keep the code more compact, among other things. In certain
cases, they prevent class instances from being in an incomplete or invalid
state because the object must be initialized to correct values as soon as it
is created. Every class can define as many constructure procedures as
necessary, each with different parameters. You can only use the old style
instanciation if the class provides a constructor with no parameters (which
most do). Sometimes (but not always), using the constructor can be a tad bit
faster in execution speed than calling the individual properties. This is
not guaranteed.
Other than the cases where no Parameterless (Default) Constructor exists,
whether you use optional constructors vs. specifying one property at a time,
is basically a matter of choice.
I'm sure some people will call it old-school though :-)


I guess I'll have to break down and do it the new way (declaring in
the middle). It does make the code more compact and I hate having to
research every example I see in a book to make it fit my old style.

Thanks!

Chuck.
Nov 20 '05 #5
cr***@hotmail.c om (CR) wrote in message
I've noticed that the trend these days is to declare variables in the
middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.


Chuck,

In addition to the other things mentioned, it makes code easier to
read. As I get older I discover that six months later I can't
remember what I did without reading through the code to see where it
goes. This is where not haveing to scroll up and down to get the whole
picture is a big help(this stuff was a lot easier at 30 and even 40,
OK). This is also one of the reasons I enjoy .NET so much, the code
is very compact and easy to read.

Charlie
Nov 20 '05 #6
CR
cw*****@tstar.n et (Charlie Smith) wrote in message

Chuck,

In addition to the other things mentioned, it makes code easier to
read. As I get older I discover that six months later I can't
remember what I did without reading through the code to see where it
goes. This is where not haveing to scroll up and down to get the whole
picture is a big help(this stuff was a lot easier at 30 and even 40,
OK). This is also one of the reasons I enjoy .NET so much, the code
is very compact and easy to read.

Charlie


OK, I'm convinced! Now I'm wondering if I should go all the way with
this and declare all the variables in the middle as needed. What is
considered proper programming style?

Thanks!
Nov 20 '05 #7
CR
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
I would actually define cmdTable1, cmdTable2 variables which effectively
eliminates your problem of "which properties were in the declaration"). As
you know what is in which variable, and you don't need to worry about when
is this variable this & when is it that. Further I would consider having two
routines, SelectTable1 & SelectTable2 that created & executed the
commands...


OK here's 2 examples of filling ListBox1 and ListBox2 with 2 different
SQL statements.

This is putting all the declares at the top:

Dim cnn As System.Data.Ole Db.OleDbConnect ion
Dim cmd As System.Data.Ole Db.OleDbCommand
Dim da As System.Data.Ole Db.OleDbDataAda pter
Dim ds As System.Data.Dat aSet
Dim dr As System.Data.Dat aRow

'open connection
cnn = New System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
Source=c:\test. mdb;")
cnn.Open()

'fill DataSet1
cmd = New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1", cnn)
da = New System.Data.Ole Db.OleDbDataAda pter(cmd)
ds = New System.Data.Dat aSet
da.Fill(ds)

'fill ListBox1
For Each dr In ds.Tables(0).Ro ws
ListBox1.Items. Add(dr.Item("Fi eld1"))
Next

'fill DataSet2
cmd = New System.Data.Ole Db.OleDbCommand ("Select * FROM Table2", cnn)

'fill ListBox2
For Each dr In ds.Tables(0).Ro ws
ListBox2.Items. Add(dr.Item("Fi eld1"))
Next

'close connection
cnn.Close()

This is using declares in the middle:

'open connection
Dim cnn As New System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
Source=c:\test. mdb;")
cnn.Open()

'fill DataSet1
Dim cmd1 As New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1",
cnn)
Dim da1 As New System.Data.Ole Db.OleDbDataAda pter(cmd1)
Dim ds1 As New System.Data.Dat aSet
da1.Fill(ds1)

'fill ListBox1
Dim dr1 As System.Data.Dat aRow
For Each dr1 In ds1.Tables(0).R ows
ListBox1.Items. Add(dr1.Item("F ield1"))
Next

'fill DataSet2
Dim cmd2 As New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1",
cnn)
Dim da2 As New System.Data.Ole Db.OleDbDataAda pter(cmd2)
Dim ds2 As New System.Data.Dat aSet
da2.Fill(ds2)

'fill ListBox2
Dim dr2 As System.Data.Dat aRow
For Each dr2 In ds2.Tables(0).R ows
ListBox2.Items. Add(dr2.Item("F ield1"))
Next

'close connection
cnn.Close()

Which method is more "by the book" in your opinion?

Thanks! You guys have really helped.

Chuck.

P.S. Something just occured to me. Wasn't implicit instantiation (my
2nd example) discouraged in VB6? It seems I remember that anytime
"weirdness" started happening the first recommendation was to
explicitly instantiate your objects. For example:

do this:

dim rst as recordset
set rst = new recordset

instead of this:

dim rst as new recordset
Nov 20 '05 #8
Cor
Hi CR

The simplest way
\\\
dim cnn as new OleDB.OledbConn ection("Provide r=Microsoft.Jet .OLEDB.4.0;Data
Source=c:\test. mdb;")
dim ds as new dataset
dim da as new oledb.oledbdata adapter("Select * FROM Table1", cnn)
da.fill(ds)
cnn.close
listbox1.dataso urce=ds.tables( 0)
listbox1.displa ymember="Field1 "
///

:-)

Cor
Nov 20 '05 #9
CR,
Which method is more "by the book" in your opinion? Both! :-)

It seems to me you have an awful lot of duplicate code in both examples!
Which is a HUGE smell in Refactoring! (http://www.refactoring.com)

In addition to Cor's suggestion of using DataSource (which is normally what
I do).

I would move the code to create & populate into its own subroutine. If I was
using the DataSet & DataSource I would look a single DataSet object with
multiple DataTables (not shown). If I could not use the DataSource as Cor
pointed out I would use a DataReader rather then creating a DataSet &
"throwing it away".

'open connection
Dim cnn As New
System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
Source=c:\test. mdb;")
cnn.Open()

FillListBox(Lis tBox1, "Field1", "Select Field1 From Table1", cnn)
FillListBox(Lis tBox2, "Field1", "Select FIeld1 From Table2", cnn)

'close connection
cnn.Close()
' Use a DataSet
Private Shared Sub FillListBoxViaD ataSet(ByVal listbox As ListBox, ByVal
columnName As String, ByVal cmtText As String, ByVal cnn As
OleDb.OleDbConn ection)
'fill DataSet
Dim cmd As New System.Data.Ole Db.OleDbCommand (cmtText, cnn)
Dim da As New System.Data.Ole Db.OleDbDataAda pter(cmd)
Dim ds As New System.Data.Dat aSet
da.Fill(ds)

'fill ListBox
Dim dr As System.Data.Dat aRow
For Each dr In ds.Tables(0).Ro ws
listbox.Items.A dd(dr.Item(colu mnName))
Next
End Sub

' Use a DataReader
Private Shared Sub FillListBox(ByV al listbox As ListBox, ByVal
columnName As String, ByVal cmdText As String, ByVal cnn As
OleDb.OleDbConn ection)
Dim cmd As New System.Data.Ole Db.OleDbCommand (cmdText, cnn)
Dim dr As OleDb.OleDbData Reader = cmd.ExecuteRead er()
Do While dr.Read()
listbox.Items.A dd(dr.Item(colu mnName))
Loop
End Sub
P.S. Something just occured to me. Wasn't implicit instantiation (my
2nd example) discouraged in VB6? It seems I remember that anytime
"weirdness" started happening the first recommendation was to
explicitly instantiate your objects. For example: Yes, it was discouraged in VB6, however in .NET it is explicit instantiation
so there is no problem!

Hope this helps
Jay

"CR" <cr***@hotmail. com> wrote in message
news:1a******** *************** ***@posting.goo gle.com... "Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
I would actually define cmdTable1, cmdTable2 variables which effectively
eliminates your problem of "which properties were in the declaration"). As you know what is in which variable, and you don't need to worry about when is this variable this & when is it that. Further I would consider having two routines, SelectTable1 & SelectTable2 that created & executed the
commands...
OK here's 2 examples of filling ListBox1 and ListBox2 with 2 different
SQL statements.

This is putting all the declares at the top:

Dim cnn As System.Data.Ole Db.OleDbConnect ion
Dim cmd As System.Data.Ole Db.OleDbCommand
Dim da As System.Data.Ole Db.OleDbDataAda pter
Dim ds As System.Data.Dat aSet
Dim dr As System.Data.Dat aRow

'open connection
cnn = New

System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data Source=c:\test. mdb;")
cnn.Open()

'fill DataSet1
cmd = New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1", cnn)
da = New System.Data.Ole Db.OleDbDataAda pter(cmd)
ds = New System.Data.Dat aSet
da.Fill(ds)

'fill ListBox1
For Each dr In ds.Tables(0).Ro ws
ListBox1.Items. Add(dr.Item("Fi eld1"))
Next

'fill DataSet2
cmd = New System.Data.Ole Db.OleDbCommand ("Select * FROM Table2", cnn)

'fill ListBox2
For Each dr In ds.Tables(0).Ro ws
ListBox2.Items. Add(dr.Item("Fi eld1"))
Next

'close connection
cnn.Close()

This is using declares in the middle:

'open connection
Dim cnn As New System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data Source=c:\test. mdb;")
cnn.Open()

'fill DataSet1
Dim cmd1 As New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1",
cnn)
Dim da1 As New System.Data.Ole Db.OleDbDataAda pter(cmd1)
Dim ds1 As New System.Data.Dat aSet
da1.Fill(ds1)

'fill ListBox1
Dim dr1 As System.Data.Dat aRow
For Each dr1 In ds1.Tables(0).R ows
ListBox1.Items. Add(dr1.Item("F ield1"))
Next

'fill DataSet2
Dim cmd2 As New System.Data.Ole Db.OleDbCommand ("Select * FROM Table1",
cnn)
Dim da2 As New System.Data.Ole Db.OleDbDataAda pter(cmd2)
Dim ds2 As New System.Data.Dat aSet
da2.Fill(ds2)

'fill ListBox2
Dim dr2 As System.Data.Dat aRow
For Each dr2 In ds2.Tables(0).R ows
ListBox2.Items. Add(dr2.Item("F ield1"))
Next

'close connection
cnn.Close()

Which method is more "by the book" in your opinion?

Thanks! You guys have really helped.

Chuck.

P.S. Something just occured to me. Wasn't implicit instantiation (my
2nd example) discouraged in VB6? It seems I remember that anytime
"weirdness" started happening the first recommendation was to
explicitly instantiate your objects. For example:

do this:

dim rst as recordset
set rst = new recordset

instead of this:

dim rst as new recordset

Nov 20 '05 #10

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

Similar topics

2
4916
by: Hal Vaughan | last post by:
First, I am aware of both SwingUtilities.invokeLater(), and of using Thread to create a new thread.  These are part of the problem. I want to have something running in the background, while the GUI is updating.  I've done that before without a problem, however, now, I need to pass variables to the separate Thread or Runnable that I'm using.  I'm using something like this: //Other code setting things up and updating GUI //Variables...
2
2141
by: Oliver Corona | last post by:
I am wondering if anyone has any insights on the performance benefit (or detriment) of declaring local variables instead of referencing members. Is allocating memory for a new variable more efficient than repeatedly referencing the member in a loop? Maybe using a string isn't the best example, but hopefully you get the idea! * example (referencing member):
6
1593
by: Joe | last post by:
Is it generally considered "better" (i.e. clearer) to declare all variables at the start of a function or as you need them within it? Joe
1
2433
by: ColinWard | last post by:
Hi guys. I have a question about declaring variables. I do a lot of re-querying of controls in my database and I use the Set statement with a variable set to the name of the control to tell the program which control to requery. This makes it easy to requery controls on a different form. However, up until today, I was dimming a new local variable for each control I wanted to deal with ( E.G. Dim cbxctl as control) and then setting that...
3
2266
by: jbeteta | last post by:
Hello, I have a problem declaring variables. I need to create an object oRpte as ReportClass on WebForm1.aspx and be able to use its value on WebForm2.aspx. For declaring the property oRpte() on WebForm1.aspx, I use "Public Property" and I declare variable _oRpte as Friend Shared. That's my problem. If I don't declare _oRpte as Friend Shared, I can't use WebForm1.oRpte() on other webpage. If I declare _oRpte as Friend Shared, I can use...
8
7519
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine, like this: for(var i=0; i<list; i++) { var name = list; }
6
2986
by: =?Utf-8?B?QUw=?= | last post by:
Hi I usually stick to the convention of not declaring variables in my bodies of "loops" (including foreach) ie int x; for (int i = 0; i < 10; i++) {
9
2112
by: Robbie Hatley | last post by:
Greetings, group. I just found a weird problem in a program where a variable declared in a {block} after a "case" keyword was being treated as having value 0 even though its actual value should have been something else. An extremely stripped-down version: int Function (int something) { switch(something) { case WHATEVER:
5
2378
by: quirk | last post by:
I am trying to write a script where a page is populated with some maths questions, user answers them (it's timed but I've left this bit out), gets results on same page and ajax takes their score, sends it to php script which updates sql. Make sense so far?!! The problem I have is getting their score out of javascript and into ajax and therefore into the sql record table. I have no problem sending php variables to ajax, just the javascript...
0
9376
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
9988
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...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
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...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.