Declaring variables in the middle of your code.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • CR

    Declaring variables in the middle of your code.

    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.
  • Rob Teixeira [MVP]

    #2
    Re: Declaring variables in the middle of your code.

    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" <cr113@hotmail. com> wrote in message
    news:1ab0ed1b.0 401120928.3f621 4e7@posting.goo gle.com...[color=blue]
    > 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.[/color]


    Comment

    • Jay B. Harlow [MVP - Outlook]

      #3
      Re: Declaring variables in the middle of your code.

      CR,[color=blue]
      > 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?[/color]
      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.
      [color=blue]
      > It seems like it makes it hard to reuse variables.[/color]
      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...
      [color=blue]
      > But that seems inconsistent, plus I have to figure out which
      > properties were which in the declaration (CommandText and Connection).[/color]
      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:
      [color=blue]
      > Dim cmd as OleDbCommand[/color]
      [color=blue]
      > 'first use[/color]
      cmd = New OleDbCommand("S elect * FROM Table1",cnn)[color=blue]
      >
      > 'second use[/color]
      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" <cr113@hotmail. com> wrote in message
      news:1ab0ed1b.0 401120928.3f621 4e7@posting.goo gle.com...[color=blue]
      > 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.[/color]


      Comment

      • Cor

        #4
        Re: Declaring variables in the middle of your code.

        Hi CR,

        A old style answer,
        [color=blue]
        > 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.[/color]

        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.[color=blue]
        >
        > 'first use
        > Dim cmd as new OleDbCommand("S elect * FROM Table1",cnn)
        >
        > 'second use
        > cmd.CommandText = "SELECT * FROM Table2"
        > cmd.Connection = cnn2
        >[/color]
        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


        Comment

        • CR

          #5
          Re: Declaring variables in the middle of your code.

          "Rob Teixeira [MVP]" <RobTeixeira@@m sn.com> wrote in message news:<uWuqAjT2D HA.308@TK2MSFTN GP11.phx.gbl>.. .

          [color=blue]
          > 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 :-)[/color]

          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.

          Comment

          • Charlie Smith

            #6
            Re: Declaring variables in the middle of your code.

            cr113@hotmail.c om (CR) wrote in message[color=blue]
            > 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.[/color]

            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

            Comment

            • CR

              #7
              Re: Declaring variables in the middle of your code.

              cwsmith@tstar.n et (Charlie Smith) wrote in message[color=blue]
              >
              > 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[/color]

              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!

              Comment

              • CR

                #8
                Re: Declaring variables in the middle of your code.

                "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message
                [color=blue]
                > 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...[/color]

                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

                Comment

                • Cor

                  #9
                  Re: Declaring variables in the middle of your code.

                  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


                  Comment

                  • Jay B. Harlow [MVP - Outlook]

                    #10
                    Re: Declaring variables in the middle of your code.

                    CR,[color=blue]
                    > Which method is more "by the book" in your opinion?[/color]
                    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


                    [color=blue]
                    > 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:[/color]
                    Yes, it was discouraged in VB6, however in .NET it is explicit instantiation
                    so there is no problem!

                    Hope this helps
                    Jay

                    "CR" <cr113@hotmail. com> wrote in message
                    news:1ab0ed1b.0 401130921.716fc 8da@posting.goo gle.com...[color=blue]
                    > "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message
                    >[color=green]
                    > > I would actually define cmdTable1, cmdTable2 variables which effectively
                    > > eliminates your problem of "which properties were in the declaration").[/color][/color]
                    As[color=blue][color=green]
                    > > you know what is in which variable, and you don't need to worry about[/color][/color]
                    when[color=blue][color=green]
                    > > is this variable this & when is it that. Further I would consider having[/color][/color]
                    two[color=blue][color=green]
                    > > routines, SelectTable1 & SelectTable2 that created & executed the
                    > > commands...[/color]
                    >
                    > 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[/color]
                    System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data[color=blue]
                    > 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[/color]
                    System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data[color=blue]
                    > 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[/color]


                    Comment

                    • Rob Teixeira [MVP]

                      #11
                      Re: Declaring variables in the middle of your code.


                      "CR" <cr113@hotmail. com> wrote in message
                      news:1ab0ed1b.0 401130921.716fc 8da@posting.goo gle.com...[color=blue]
                      >
                      > 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.[/color]

                      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]


                      Comment

                      • CR

                        #12
                        Re: Declaring variables in the middle of your code.

                        "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message news:<OmUk3wj2D HA.1264@TK2MSFT NGP11.phx.gbl>. ..
                        [color=blue]
                        > 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".[/color]

                        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.

                        Comment

                        • Rob Nicholson

                          #13
                          Re: Declaring variables in the middle of your code.

                          > middle of code instead of at the top. What is the advantage of this?[color=blue]
                          > It seems like it makes it hard to reuse variables.[/color]

                          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


                          Comment

                          • Jay B. Harlow [MVP - Outlook]

                            #14
                            Re: Declaring variables in the middle of your code.

                            CR,[color=blue]
                            > I hate to argue with someone who is helping me but I can't help it :).[/color]
                            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...
                            [color=blue]
                            > I have a question about the DataSource. I've never used it in the
                            > earlier versions because I didn't think it was flexible.[/color]
                            What do you mean "earlier versions"? DataSource is new with VB.NET 2002, it
                            is a extremely simple & flexible way of populating "list" controls.
                            [color=blue]
                            > What if I
                            > wanted to hyphenate every other entry in a listbox (for whatever
                            > reason)?[/color]
                            Realistically often you do you need that? It seems more the exception then
                            the norm...
                            [color=blue]
                            > For example how would I do this with the DataSource?[/color]

                            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" <cr113@hotmail. com> wrote in message
                            news:1ab0ed1b.0 401140714.42d50 1cc@posting.goo gle.com...[color=blue]
                            > "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message[/color]
                            news:<OmUk3wj2D HA.1264@TK2MSFT NGP11.phx.gbl>. ..[color=blue]
                            >[color=green]
                            > > 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[/color][/color]
                            what[color=blue][color=green]
                            > > I do).
                            > >
                            > > I would move the code to create & populate into its own subroutine. If I[/color][/color]
                            was[color=blue][color=green]
                            > > using the DataSet & DataSource I would look a single DataSet object with
                            > > multiple DataTables (not shown). If I could not use the DataSource as[/color][/color]
                            Cor[color=blue][color=green]
                            > > pointed out I would use a DataReader rather then creating a DataSet &
                            > > "throwing it away".[/color]
                            >
                            > 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.[/color]



                            Comment

                            • CR

                              #15
                              Re: Declaring variables in the middle of your code.

                              "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message news:<u$rFIzx2D HA.1392@TK2MSFT NGP11.phx.gbl>. ..[color=blue]
                              > CR,[color=green]
                              > > I hate to argue with someone who is helping me but I can't help it :).[/color]
                              > 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...[/color]

                              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.
                              [color=blue][color=green]
                              > > I have a question about the DataSource. I've never used it in the
                              > > earlier versions because I didn't think it was flexible.[/color]
                              > What do you mean "earlier versions"? DataSource is new with VB.NET 2002, it
                              > is a extremely simple & flexible way of populating "list" controls.[/color]

                              Didn't they have something called a DataControl in VB6? I just assumed
                              that was the same type of thing.
                              [color=blue][color=green]
                              > > What if I
                              > > wanted to hyphenate every other entry in a listbox (for whatever
                              > > reason)?[/color]
                              > Realistically often you do you need that? It seems more the exception then
                              > the norm...[/color]

                              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.
                              [color=blue]
                              > 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.[/color]

                              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.

                              Comment

                              Working...