r/visualbasic • • Aug 07 '15

Writing clean code - simplify your code.

6 Upvotes

I was handed an application recently from a developer who is leaving the company and it contained many oracle functions like the following;

Protected Sub SaveAdjustment_Names(ByVal sadjnameid As String, ByVal sADj_Name As String, ByVal sComments As String, ByVal sEntered_BY As String, ByVal sADJ_STATUS As String, ByVal sACTION As String)
    'TODO:   refactor this
    Try
        Dim sconstr As New AppFunctions
        Dim oracon As New OracleConnection(sconstr.sConstring)
        Dim cmdOra As New OracleCommand
        cmdOra.CommandType = CommandType.StoredProcedure
        cmdOra.CommandText = "WAP.AP_ADJUST_NAME_CHANGE"  '
        cmdOra.Connection = oracon
        Dim pavtid As New OracleParameter
        pavtid.OracleDbType = OracleDbType.Varchar2
        pavtid.ParameterName = "SADJNAMEID"
        pavtid.Direction = ParameterDirection.Input
        pavtid.Value = Trim(sadjnameid)

        Dim pavtType As New OracleParameter
        pavtType.OracleDbType = OracleDbType.Varchar2
        pavtType.ParameterName = "SADJ_NAME"
        pavtType.Direction = ParameterDirection.Input
        pavtType.Value = Trim(sADj_Name)

        Dim pavtCode As New OracleParameter
        pavtCode.OracleDbType = OracleDbType.Varchar2
        pavtCode.ParameterName = "SCOMMENTS"
        pavtCode.Direction = ParameterDirection.Input
        pavtCode.Value = Trim(sComments)

        Dim pavtSecCode As New OracleParameter
        pavtSecCode.OracleDbType = OracleDbType.Varchar2
        pavtSecCode.ParameterName = "SENTERED_BY"
        pavtSecCode.Direction = ParameterDirection.Input
        pavtSecCode.Value = sEntered_BY 'Trim(Me.T_avtcode.Text.ToString)

        Dim pavtDesc As New OracleParameter
        pavtDesc.OracleDbType = OracleDbType.Varchar2
        pavtDesc.ParameterName = "SADJ_STATUS"
        pavtDesc.Direction = ParameterDirection.Input
        pavtDesc.Value = Trim(sADJ_STATUS)

        Dim pAction As New OracleParameter
        pAction.OracleDbType = OracleDbType.Varchar2
        pAction.ParameterName = "SACTION"
        pAction.Direction = ParameterDirection.Input
        pAction.Value = Trim(sACTION)

        cmdOra.Parameters.Add(pavtid)
        cmdOra.Parameters.Add(pavtType)
        cmdOra.Parameters.Add(pavtCode)
        cmdOra.Parameters.Add(pavtSecCode)
        cmdOra.Parameters.Add(pavtDesc)
        cmdOra.Parameters.Add(pAction)

        cmdOra.Connection.Open()
        cmdOra.ExecuteNonQuery()
        cmdOra.Connection.Close()
    Catch ex As Exception
        Session("Error") = ex
        Response.Redirect("ErrorInfo.aspx")
    End Try

End Sub

There is nothing wrong with this code. It works and is easy to understand.

When using clean code principals we can reduce this to something easier to understand. The first thing I noticed when I looked at this function was that there were 6 identical chunks of code that created an oracle parameter. The rule of thumb for clean code is

"If a block of code appears more than once, break it out to a function"

Following this rule I created this function.

Public Function CreateOracleParameter(paramName As String) As OracleParameter
    Dim opParm As New OracleParameter
    opParm.OracleDbType = OracleDbType.NVarchar2
    opParm.ParameterName = Trim(paramName.ToUpper)
    opParm.Direction = ParameterDirection.Input
    opParm.Value = Trim(paramName)
    Return opParm
End Function

Which changed the intial function to;

Protected Sub SaveAdjustment_Names(ByVal sadjnameid As String, ByVal sADj_Name As String, ByVal sComments As String, ByVal sEntered_BY As String, ByVal sADJ_STATUS As String, ByVal sACTION As String)

    Try
        Dim sconstr As New AppFunctions
        Dim oracon As New OracleConnection(sconstr.getConnectionString)

        Dim cmdOra As New OracleCommand
        cmdOra.CommandType = CommandType.StoredProcedure
        cmdOra.CommandText = "WAP.AP_ADJUST_NAME_CHANGE"  '
        cmdOra.Connection = oracon

        cmdOra.Parameters.Add(CreateOracleParameter(sadjnameid))
        cmdOra.Parameters.Add(CreateOracleParameter(sADj_Name))
        cmdOra.Parameters.Add(CreateOracleParameter(sComments))
        cmdOra.Parameters.Add(CreateOracleParameter(sEntered_BY))
        cmdOra.Parameters.Add(CreateOracleParameter(sADJ_STATUS))
        cmdOra.Parameters.Add(CreateOracleParameter(sACTION))

        cmdOra.Connection.Open()
        cmdOra.ExecuteNonQuery()
        cmdOra.Connection.Close()

    Catch ex As Exception
        Session("Error") = ex
        Response.Redirect("ErrorInfo.aspx")
    End Try

End Sub

As you can see much easier to read and thus easier to maintain and trace issues. In this specific case I was able to refactor 168 calls for parameters and reduced the code base by over 20 percent.

Remember there is no wrong way to program, only better ways.

Improve your craft one method at a time.

B


r/visualbasic • • May 26 '15

Sort [VB.NET] Failed implementation of quicksort

6 Upvotes

Hey guys, can someone tell me why my quicksort doesn't work? It's an implementation of the pseudocode found at wiki and, as far as I can figure out, everything seems to be correct. I even followed it on paper and, as far as I can see, the logic is right: but the results I end up getting are far from sorted.

http://pastebin.com/766uDJGK

Appreciate any help!


r/visualbasic • • Feb 17 '15

Attaching to and automating an existing IE instance is a pain. I wrote some functions to make it less of a pain.

Thumbnail
github.com
6 Upvotes

r/visualbasic • • Nov 03 '14

Is Visual Basic something a total beginner can learn?

6 Upvotes

Hi all. My husband, who is not a programmer but has some programming experience, is thinking about learning Visual Basic because of a potential new job opportunity. I am an absolute beginner when it comes to programming but I thought it might be more fun to learn together. Is this a good idea? Are there any tutorials you would recommend? Thank you!


r/visualbasic • • May 17 '14

How to create a Sudoku Solver, using Visual Basic 2010 Express part one

Thumbnail
youtube.com
6 Upvotes

r/visualbasic • • Mar 07 '14

For your pleasure: A generic XML serializer + deserializer

6 Upvotes

I see a lot of posts where people are trying to save/load classes to disk, with varying results. I tend to recommend looking at the XMLSerializer documentation, but they're limited in that they only work for one specific class. Coding the same thing over and over again is always stupid, so a long time ago I made a serializer/deserializer that works with anything you give it! Huzzah!

Load/Deserialize:

Public Function Load(Of T)(path As String, classToLoad As T) As T
    ' I had a specific reason for doing this, but i don't remember why. maybe it
    ' was related to not being able to call GetType() on a null object? oh well..    
    Dim tp = If(classToLoad Is Nothing, GetType(T), classToLoad.GetType())
    Dim stream As StreamReader
    Try
        Dim reader = New XmlSerializer(tp)
        stream = New StreamReader(path)
        classToLoad = CType(reader.Deserialize(stream), T)
    Catch ex As Exception
        ' write a message to the console, pop up a message box, whatever 
        classToLoad = Nothing
    Finally
        If stream IsNot Nothing Then
            stream.Close()
        End If
    End Try
    Return classToLoad
End Function

Save/Serialize:

Public Sub Save(Of T)(path As String, classToSave As T)
    Dim writer As New StreamWriter(path)
    Try
        Dim ser As New XmlSerializer(classToSave.GetType())
        ser.Serialize(writer, classToSave)
    Catch ex As Exception
        ' do the needful
    Finally
        If writer IsNot Nothing Then
            writer.Close()
        End If
    End Try
End Sub

Edit: Yes, I do know that the Try...Catch blocks are functionally equivalent to Using..., I just like the ability to inform the user of why it failed


r/visualbasic • • Apr 12 '13

I found a bug in VB: math class

Thumbnail
imgur.com
6 Upvotes

r/visualbasic • • Apr 03 '13

Classic Visual Basic’s end marked a key change in software development

Thumbnail
codeproject.com
6 Upvotes

r/visualbasic • • Feb 09 '13

Hidden Features of VB.Net -- Something for Everyone

Thumbnail
stackoverflow.com
6 Upvotes

r/visualbasic • • May 23 '12

Stubborn StreamReader

6 Upvotes

Hey guys,

I've got a bit of trouble here, this component of my code writes an integer to a text file on close and then writes it to an integer when the form loads.

The problem I'm having is that the "Process cannot access the file because it is being used by another process" error.

Now I've put it down to my load streamreader, even though I've included the streamreader.close() line it doesn't actually process this line. It only reads the line before it and proceeds to open the form.

Here's my code:


Private Sub Main_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    Dim sw_QuoteNo As StreamWriter
    Dim sFileName As String
    Dim iRecords As Integer

    iRecords = lbxQuoteNumber.Items.Count
    sFileName = Application.StartupPath & "\QuoteEnd.txt"
    sw_QuoteNo = New StreamWriter(sFileName, True)

    If File.Exists(sFileName) Then
        sw_QuoteNo.WriteLine(iQuoteEnd)
    Else
        MsgBox("The file was not found.")
    End If

    sw_QuoteNo.Close()

End Sub

Private Sub frmQuoteSystem_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim sr_QuoteNumber As StreamReader
    Dim sFileName As String
    Dim sLine As String

    sFileName = Application.StartupPath & "\QuoteEnd.txt"
    sr_QuoteNumber = New StreamReader(sFileName, True)

    iQuoteEnd = sr_QuoteNumber.ReadLine

    sr_QuoteNumber.Close()
End Sub


Obviously, one is the form load sub and the other is the closing sub.

Some clarity would be much appreciated, I've been working on this for far too long to no avail.

(I do have other streamreader/writers but they're triggered with a button)


r/visualbasic • • Feb 13 '12

Hidden Features of VB.NET

Thumbnail
stackoverflow.com
6 Upvotes

r/visualbasic • • Dec 18 '11

Welcome to the new r/VisualBasic!

6 Upvotes

I recently took over /r/visualbasic and /r/vbnet (though I figured that they could both be combined into one community since /r/vbnet was created as a result of a failed submission and had no submissions itself) and I'm hoping we can "revive" this reddit and have it expand into a more active/larger community than what it is now.

What I've done so far

  • added a header image

  • a bit of a theme (the navigation bar at the top of the reddit uses the same colour style as tabs in VB.NET's IDE) - I was working on a "full" reddit theme but the link colours clashed with the darker blue background so I've settled for just a coloured background (same as the VB.NET IDE's selected tabs) but I might try the "full" theme again later.

  • minor tweaks

  • rewrote the sidebar*

Regarding the sidebar

I'm not sure what to put in the sidebar - rules? If rules, what should be allowed and what shouldn't?

I'd appreciate any suggestions or feedback you have so that we can make this community better.

-Ordona


r/visualbasic • • Jul 28 '26

How do you approach debugging an old codebase that has little or no documentation?

5 Upvotes

r/visualbasic • • Nov 18 '25

VB.NET Help Need someone to help me create an "Active Desktop" like a webpage. (Partically it is related to Visual basic)

Thumbnail reddit.com
5 Upvotes

r/visualbasic • • Aug 25 '25

Discord server for VB (.Net and COM)

Thumbnail discord.gg
5 Upvotes

r/visualbasic • • May 01 '25

VB Neural Net Library ca. 1992?

5 Upvotes

Around 1992-93 I was just getting into VB programming and on a visit home to see my parents I saw my dad was using a neural net library for Visual Basic. It was very rudimentary but could be trained to do simple pattern recognition. For example, one could train it to recognize smiley and frowny faces by drawing them in a box with the mouse and then labeling them happy or sad. After enough training data, the library could recognize a newly drawn face.

The library wasn’t limited to that - it would work on a wide variety of data. I don’t remember a lot but do remember the documentation talked the normal neural net talk: input/hidden/output layers, back-propagation, biases, weights, etc.

Does anyone remember such a library? The Googles and even perplexity aren’t finding anything.

I’m not sure but the publisher could have been in Florida.

I’m really just curious. This clearly has no use today.


r/visualbasic • • Nov 26 '24

VB.NET Help Issue getting loan calculator to work

Thumbnail
gallery
5 Upvotes

r/visualbasic • • Nov 13 '24

Proof of Concept: Breakout/Arkanoid Style Clone in MS Access VBA

5 Upvotes

Hi all - I created a MS Access VBA project that I haven't seen before; a Breakout (aka Arkanoid/Brick Breaker) style clone with the ball, paddle, and bricks. It still has a few bugs, glitches, and weird flickering, but I got it working!

Full code and file here: https://github.com/TLDWTutorials/BreakoutClone

I also made a YouTube video about it as well. See: https://www.youtube.com/watch?v=GLEZmrcn-Vc

Feel free to use it, optimize it, and make it your own.


r/visualbasic • • Sep 09 '24

App resizing on its own, looking for pointers

5 Upvotes

Hello.

Some premise:

  • There is a VB app made by someone, somewhere, at some point in time, which may or may not have been coded with feet

  • The app runs on an older Windows tablet with no apparent trouble

  • The app is now being run on a newer tablet with higher screen resolution

  • I have never touched VB in my life

What it does:

  • Upon loading a dxf file, the resulting graph is plotted over a background grid

What happens:

  • Upon loading the dxf file, the app resizes all by itself to a lower size

I am fully ignorant of any of VB's idiosyncrasies, I usually do C/C#/Web.

Any idea where to start looking? Relevant words to google/search in the code? Is this a normal thing to occur? Any questions I may answer to help?

Post is unflaired because I don't know the version. The files appear to be .vba .vb.

Thanks!


r/visualbasic • • May 30 '24

Looking to hire remote programmer

5 Upvotes

Hello, not sure if this is the appropriate place to post this or not. I'm looking to bring on a junior developer to join my small, remote team that develops a customizes middleware application for universities and enterprise clients. Looking only for someone that is available during US business hours (open to hiring from LatAm) and can also handle tech support requests and communicate well with clients. Great opportunity for someone that craves autonomy and wants to learn and grow within a small team.

If anyone knows of out of the box places to look I'd appreciate it. Or if someone here is interested DM me with any questions you have.

Thanks for the help!


r/visualbasic • • Apr 30 '24

ComboBox Data from SQL Table

5 Upvotes

Hey all,

I have a SQL table as a Data Source in my Visual Basic 2022 program. I want one of the columns to populate a dropdown menu (ComboBox). I've looked on-line, but there are a mixed bag of answers it seems.

Is there a simple way to populate the ComboBox with one column's worth of data from my SQL table?

TIA


r/visualbasic • • Apr 05 '24

VB.NET Help Generating a code to open a new form

5 Upvotes

I’m new in vb.net 2010 and one of our project is making a virtual classroom like google classroom. Is it possible to have the teacher make some sort of password or code in the form and the student have to input the password in order to open a new form?


r/visualbasic • • Mar 12 '24

How to cleanly exit a VB.NET program?

5 Upvotes

Although I've been coding in VB.Net for years, I've never been able to cleanly exit, despite many attempts, and google searches.

For example, I have a simple, single form application. When somebody clicks the close button (the x on the top right of the window) I want the software to cleanly exit.

I have recently tried again with the below code. It runs and doesn't complain. But if I run the exe outside of visual studio, it remains in memory and have to kill it in the task manager.

Any advice would be greatly appreciated.

  Private Sub ProgramClosing() Handles MyBase.FormClosing

        Application.Exit()


    End Sub

r/visualbasic • • May 09 '23

I have very simple question that I couldn't make sense. Why do we have to put Textbox1.Text before "Hello"

Thumbnail
gallery
5 Upvotes

r/visualbasic • • Jan 12 '23

Problem open web link with process.start in visual studio 2022

5 Upvotes

Hi all
when I try to open a web link with Process.start it gives me an unhandled exception error ... can you explain why?

The instruction is this: Process.start("www.google.com")

Thank you