473,770 Members | 2,065 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
15 2970

"CR" <cr***@hotmail. com> wrote in message
news:1a******** *************** ***@posting.goo gle.com...

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.


Yes, it was discouraged in VB6 because VB6 didn't actually create the
instance at that location. It deferred creation until you actually *used*
the class, which bloated your code with extra null checks.
However, this is no longer the case in VB.NET. The compiler does pretty much
what it looks like it should be doing now.

-Rob Teixeira [MVP]
Nov 20 '05 #11
CR
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message news:<Om******* *******@TK2MSFT NGP11.phx.gbl>. ..
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".


I hate to argue with someone who is helping me but I can't help it :).
When I first started working as a programmer (15 years ago), I was all
about subroutining the hell out of everything. I had been taught that
if it was more than a page it should be a function. The problem I
found with too many subs is the maintenance. The biggest problem is
you have to pass all your vars from sub to sub. It gets ugly if you
start using subs inside of subs. I was at my first job for 11 years
and 50% of what I did was maintain old code. Whenever I came across
stuff with a bunch of subs I got depressed! It's so hard to debug.
There are many cases that really need to be subbed but I would never
write a sub to fill in a listbox.

I have a question about the DataSource. I've never used it in the
earlier versions because I didn't think it was flexible. What if I
wanted to hyphenate every other entry in a listbox (for whatever
reason)?

For example how would I do this with the DataSource?

lngCount = 0
For Each dr In ds.Tables(0).Ro ws
strTemp = dr.Item("Field1 ")
if (lngCount Mod 2 = 0) then
strTemp = Left(strTemp,2) & "-" & Mid(strTemp,3)
listbox.Items.A dd(strTemp)
else
listbox.Items.A dd(strTemp)
endif
lngCount = lngCount+1
Next

Thanks!

Chuck.
Nov 20 '05 #12
> middle of code instead of at the top. What is the advantage of this?
It seems like it makes it hard to reuse variables.


a) More readable as the declaration of the variable occurs next to where
it's first used so you don't have to scroll up to the top.
b) You can initialise and declare at the same time in VB.NET so why not
always declare where variable first used
c) Faster typing as you don't have to move up to the top, enter declaration
and move back down :-)

Rob
Nov 20 '05 #13
CR,
I hate to argue with someone who is helping me but I can't help it :). Is this an argument, a debate or a discussion. I figure its a discussion!

Also I have images of the "exact" programs that you are referring to!!

I've actually seen both! Poorly written code that uses a lot of subroutines
and poorly written code that does not use any subroutines. Just goes to show
Poor code is Poor code, despite the paradigm one chooses to use! :-) Of
course what you or I consider poor code may be the rest of the teams gold
code...

I do find that if you start really doing OOP smaller light weight objects
with smaller subroutines are far more flexible then a single monolithic
Module with a single monolithic sub-routine (yes an extreme, but I've seen
major programs written in a monolithic manner). Which is why I find
Refactoring
http://www.refactoring.com so useful. IMHO it helps to get the "right size"
of subroutine & object, especially after the subroutine/object is finished
and you need to come in later & modify it...
I have a question about the DataSource. I've never used it in the
earlier versions because I didn't think it was flexible. What do you mean "earlier versions"? DataSource is new with VB.NET 2002, it
is a extremely simple & flexible way of populating "list" controls.
What if I
wanted to hyphenate every other entry in a listbox (for whatever
reason)? Realistically often you do you need that? It seems more the exception then
the norm...
For example how would I do this with the DataSource?
I would populate the DataTable or "domain" collection with hyphenated rows,
especially if the "list" is used in more then one place. Otherwise I would
consider simply using a DataReader and building the list similar to your
code.

The point Cor & I are attempting to make about the DataSource, is we would
NOT populate a DataTable (DataSet) simply to iterate over it to populate
Items collection, if I populated the DataSet I would use the DataSource, if
I needed to populate just the ITems collection (for hyphenation for example)
I would use a DataReader... (sample of DataReader given in early post). As
the DataSource property can be used in the designer and produces very
compact code.

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 news:<Om******* *******@TK2MSFT NGP11.phx.gbl>. ..
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".


I hate to argue with someone who is helping me but I can't help it :).
When I first started working as a programmer (15 years ago), I was all
about subroutining the hell out of everything. I had been taught that
if it was more than a page it should be a function. The problem I
found with too many subs is the maintenance. The biggest problem is
you have to pass all your vars from sub to sub. It gets ugly if you
start using subs inside of subs. I was at my first job for 11 years
and 50% of what I did was maintain old code. Whenever I came across
stuff with a bunch of subs I got depressed! It's so hard to debug.
There are many cases that really need to be subbed but I would never
write a sub to fill in a listbox.

I have a question about the DataSource. I've never used it in the
earlier versions because I didn't think it was flexible. What if I
wanted to hyphenate every other entry in a listbox (for whatever
reason)?

For example how would I do this with the DataSource?

lngCount = 0
For Each dr In ds.Tables(0).Ro ws
strTemp = dr.Item("Field1 ")
if (lngCount Mod 2 = 0) then
strTemp = Left(strTemp,2) & "-" & Mid(strTemp,3)
listbox.Items.A dd(strTemp)
else
listbox.Items.A dd(strTemp)
endif
lngCount = lngCount+1
Next

Thanks!

Chuck.


Nov 20 '05 #14
CR
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message news:<u$******* *******@TK2MSFT NGP11.phx.gbl>. ..
CR,
I hate to argue with someone who is helping me but I can't help it :). Is this an argument, a debate or a discussion. I figure its a discussion!

Also I have images of the "exact" programs that you are referring to!!

I've actually seen both! Poorly written code that uses a lot of subroutines
and poorly written code that does not use any subroutines. Just goes to show
Poor code is Poor code, despite the paradigm one chooses to use! :-) Of
course what you or I consider poor code may be the rest of the teams gold
code...


Now that I think about it I use Fill_ListBox subroutines constantly
(oops!). Usually when there's a situation when I want to fill the
ListBox during the Form_Load event and later when the user clicks on a
button. Forget about what I said about never using it. I think the
most important reason to make a sub is for it to be reusable. If
you're just doing it to make your routine shorter, that's a bad
reason.
I have a question about the DataSource. I've never used it in the
earlier versions because I didn't think it was flexible.

What do you mean "earlier versions"? DataSource is new with VB.NET 2002, it
is a extremely simple & flexible way of populating "list" controls.


Didn't they have something called a DataControl in VB6? I just assumed
that was the same type of thing.
What if I
wanted to hyphenate every other entry in a listbox (for whatever
reason)?

Realistically often you do you need that? It seems more the exception then
the norm...


I think it's fairly common for me to modify the data somewhat before I
display in a listbox. The hyphenated example was a bit extreme, but
the idea is that I don't always display data straight out of the
database. I'll have to give the DataSource a try, however. I didn't
know you could use it with straight code, I can't stand using wizards.
The point Cor & I are attempting to make about the DataSource, is we would
NOT populate a DataTable (DataSet) simply to iterate over it to populate
Items collection, if I populated the DataSet I would use the DataSource, if
I needed to populate just the ITems collection (for hyphenation for example)
I would use a DataReader... (sample of DataReader given in early post). As
the DataSource property can be used in the designer and produces very
compact code.


My goal is to be able to use the same method, even if it's
inefficient. For example when filling a listbox I don't want to fill
it using the DataSource one time and then ListBox.Items.A dd another
time. Same thing with the Datareader vs the DataSet. I'd prefer to use
the DataSet all the time, even if it would be more efficient to use
the DataReader. My programs are fast enough that I don't worry about
speed, I just want them to be easy to maintain.

Thanks!

Chuck.
Nov 20 '05 #15
CR
Didn't they have something called a DataControl in VB6? I just assumed
that was the same type of thing. Same type of thing, IMHO significantly better implementation! (I've seen
others say the same thing).
I think it's fairly common for me to modify the data somewhat before I
display in a listbox. The hyphenated example was a bit extreme, but
the idea is that I don't always display data straight out of the
database. I'll have to give the DataSource a try, however. I didn't
know you could use it with straight code, I can't stand using wizards. Remember you can put "computed" columns in a DataTable, so you can message
the data to a certain degree without an "exterior" loop.
My goal is to be able to use the same method, even if it's
inefficient. For example when filling a listbox I don't want to fill
it using the DataSource one time and then ListBox.Items.A dd another Understood, on a project by project basis I do that.

If you don't have it and I have not mentioned it, you may want to consider
getting David Sceppa's book "Microsoft ADO.NET - Core Reference" from MS
Press it is a very good tutorial (on a number of topics we touched on in
this thread) as well as a good desk reference once your using ADO.NET.

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

news:<u$******* *******@TK2MSFT NGP11.phx.gbl>. ..
CR,
I hate to argue with someone who is helping me but I can't help it :).

Is this an argument, a debate or a discussion. I figure its a discussion!

Also I have images of the "exact" programs that you are referring to!!

I've actually seen both! Poorly written code that uses a lot of subroutines and poorly written code that does not use any subroutines. Just goes to show Poor code is Poor code, despite the paradigm one chooses to use! :-) Of
course what you or I consider poor code may be the rest of the teams gold code...


Now that I think about it I use Fill_ListBox subroutines constantly
(oops!). Usually when there's a situation when I want to fill the
ListBox during the Form_Load event and later when the user clicks on a
button. Forget about what I said about never using it. I think the
most important reason to make a sub is for it to be reusable. If
you're just doing it to make your routine shorter, that's a bad
reason.
I have a question about the DataSource. I've never used it in the
earlier versions because I didn't think it was flexible.

What do you mean "earlier versions"? DataSource is new with VB.NET 2002, it
is a extremely simple & flexible way of populating "list" controls.


Didn't they have something called a DataControl in VB6? I just assumed
that was the same type of thing.
What if I
wanted to hyphenate every other entry in a listbox (for whatever
reason)?

Realistically often you do you need that? It seems more the exception then the norm...


I think it's fairly common for me to modify the data somewhat before I
display in a listbox. The hyphenated example was a bit extreme, but
the idea is that I don't always display data straight out of the
database. I'll have to give the DataSource a try, however. I didn't
know you could use it with straight code, I can't stand using wizards.
The point Cor & I are attempting to make about the DataSource, is we would NOT populate a DataTable (DataSet) simply to iterate over it to populate
Items collection, if I populated the DataSet I would use the DataSource, if I needed to populate just the ITems collection (for hyphenation for example) I would use a DataReader... (sample of DataReader given in early post). As the DataSource property can be used in the designer and produces very
compact code.


My goal is to be able to use the same method, even if it's
inefficient. For example when filling a listbox I don't want to fill
it using the DataSource one time and then ListBox.Items.A dd another
time. Same thing with the Datareader vs the DataSet. I'd prefer to use
the DataSet all the time, even if it would be more efficient to use
the DataReader. My programs are fast enough that I don't worry about
speed, I just want them to be easy to maintain.

Thanks!

Chuck.

Nov 20 '05 #16

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

Similar topics

2
4917
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
1595
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
2267
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
2113
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
9591
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
10228
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10057
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
10002
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
8883
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
7415
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
6676
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
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3970
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

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.