Critique my refactor

Long story short, this place has a popup with params. For transfer verification location. All the sudden it stopped working on one tank but works on all the others. I still have no idea why. But what I do know know is the code and process looked really messy. So i figured I’d just refactor it and hope it fixes the issue.

But I don’t program as often as i’d like. So I wanted others opinions or if they see I did something wrong, or have a better way to refactor something etc…

I’m gonna post the original code below: Then below that post my refactored code. I appreciate anyone who takes the time to look at it.

#orignial guys code
valve = event.source.parent.getComponent('Label').text
#Grabs valve table
system.nav.openWindow("Main Windows/TableImport")
window = system.gui.getWindow("Main Windows/TableImport")
data = window.rootContainer.getComponent("Valve Table").data
system.nav.closeWindow("Main Windows/TableImport")
valve_desc = event.source.parent.getComponent('Label 1').text
valve_dest = ""
for row in range(data.rowCount):
	index_row = data.getValueAt(row, 0)
	if index_row == valve:
		valve_dest = data.getValueAt(row, 1)
		break
#Goes through table to see if valve is a "valve"
for row in range(data.rowCount):
	index_row = data.getValueAt(row, 0)
	print valve
#Starts valve comparison if the valve exists
	if index_row == valve:		
#Checks if valve has multiple destinations
		if valve == "AB_211220" or valve == "XV_211102" or valve == "AB_210720" or valve == "XV_210402" or valve == "XV_210502" or valve == "XV_210102" or valve == "XV_211002" or valve == "XV_210603" or valve == "XV_210803" or valve == "XV_210903":
#Opens tank detail's window to get destination 
			system.nav.openWindow("Tanks Details")			
			window = system.gui.getWindow("Tanks Details")
			desti_cap = window.rootContainer.getComponent("Container")
			desti_cap = desti_cap.getComponent("Tansfer_Container")
			desti_cap = desti_cap.getComponent("Destination Indicator").text
			desti = desti_cap.lower()			
			system.nav.closeWindow("Tanks Details")			
			message = valve_desc + " will open to " + '"' + desti + '"' + ". Enter Destination:"
			system.gui.messageBox(message, "Destination Check")
			input = system.gui.showTouchscreenKeyboard("")			
#Compares input with chosen destination
			if input == desti:
			   value = event.source.Setvalue
			   event.source.parent.Set_tag_state = value
			else:
			   system.gui.messageBox("Input did not match destination")			   
		else:
			#Grabs valve table
#			system.nav.openWindow("Main Windows/TableImport")
#			window = system.gui.getWindow("Main Windows/TableImport")
#			data = window.rootContainer.getComponent("Valve Table").data
#			system.nav.closeWindow("Main Windows/TableImport")
			message = valve_desc + " will open to " + '"' + valve_dest + '"' + ". Enter Destination:"
			system.gui.messageBox(message, "Destination Check")
			input = system.gui.showTouchscreenKeyboard("")			
			#message = valve_desc + " will open to " + '"' + valve_dest + '"' + "."
			#input = system.gui.inputBox(message, "")			
			#Searches valve number to match destination with input
			for row in range(data.rowCount):
				index_row = data.getValueAt(row, 0)
				if index_row == valve:
				   index_col = data.getValueAt(row, 1)
				   if index_col == input:
					  #system.gui.messageBox("Input matches destination")
					  value = event.source.Setvalue
					  event.source.parent.Set_tag_state = value
				   else:
					  system.gui.messageBox("Input did not match destination")
		break					  
	elif (row+1) == data.rowCount:
			#system.gui.messageBox("This is not a valve")
			value = event.source.Setvalue
			event.source.parent.Set_tag_state = value






#value = event.source.Setvalue
#
#event.source.parent.Set_tag_state = value

#my code
# Gets Valve
valve = event.source.parent.getComponent('Label').text
# List of vales with multiple locations. 
ValveMultLocs =["AB_211220","XV_211102","AB_210720","XV_210402","XV_210502","XV_210102","XV_211002","XV_210603","XV_210803","XV_210903"]
for loc in ValveMultLocs:
    if loc == valve:
    # Get Tank Number
    GetTank = event.source.parent.parent.Page
    # Read the selected Transfer To for apropriate tank
    TransferTo = system.tag.read("System1/Project1/Tank Details/"+GetTank+"/TransferTo").value
    # validate transfer
    message = "Do you want to open" GetTank + "to" + TransferTo
    system.gui.messageBox(message)
    # ask user to verify transfer location
    UserInputTransfer = system.gui.showTouchscreenKeyboard("Verify Transfer Location")
    if UserInputTransfer = TransferTo:
        message = GetTank + " will now open to " + TransferToHere 
        system.gui.box(message)
        value = event.source.Setvalue
        event.source.parent.Set_tag_state = value
        else:
        system.gui.messageBox("Transfer input did not match Tank Details selection.")
else:
    #Dictionary to place valve location dataset in.
    CRvalveTo = {}
    #Dataset of valve locations
    ValveDataset = system.tag.read("System1/Project1/HOA/Valves").value
    #Puts dataset into a dict
    for rowRead in ValveDataset:
        CRvalveTo[rowRead['id']] = rowRead['description']
    #Gets transfer location
    valveCrossx = CRvalveTo[valve]
    UserInputTransfere = system.gui.showTouchscreenKeyboard("Verify Transfer Location")
    if UserInputTransfere = valveCrossx:
        message = valve + " will now open to " + valveCrossx 
        system.gui.box(message)
        value = event.source.Setvalue
        event.source.parent.Set_tag_state = value
        else:
        system.gui.messageBox("Transfer input did not match Tank Details selection.")

It looks like there’s some typos or other problems in the new code, e.g system.gui.box, = instead of ==, missing indentation, etc.

That said, the overall logical structure seems fine.
This block is a bit odd:

# Gets Valve
valve = event.source.parent.getComponent('Label').text
# List of vales with multiple locations. 
ValveMultLocs =["AB_211220","XV_211102","AB_210720","XV_210402","XV_210502","XV_210102","XV_211002","XV_210603","XV_210803","XV_210903"]
for loc in ValveMultLocs:
    if loc == valve:

If you’ve got a defined list of locations, why not a dropdown list rather than a label?
I would also probably use a set instead of a list (though in practice this is a micro optimization) and switch to using the in operator:

ValveMultLocs = {"AB_211220","XV_211102","AB_210720","XV_210402","XV_210502","XV_210102","XV_211002","XV_210603","XV_210803","XV_210903"}
if valve in ValveMultLocs:

@PGriffith I’ll straighten that out.

I see the confusion let me clarify a little more on the working. We do have a defined list. Well originally it was a CSV that gets loaded to a table on a separate window. But this is not something the user interacts with, which is why I didn’t opt for a drop down. I think looping through a csv table on another window is kind of sloppy. So I figured I could just move it to a dataset tag.

The label is on the popup and the value is an indirect binding. The label has no user interaction. We simply use that label to know which valve they have opened. And then use that to further dictate the verification process. And pop up messages. We have two kinds of valves. One which is set in stone as to where it goes. And the other is based off of a user selection on a popup windows. Mostly for transferring product.

I’m not sure what you mean by?

I agree the In could save me a line and I appreciate that.

{a, b, c} is a set literal (in contrast to [a, b, c], a list literal or (a, b, c) a tuple literal).
In theoretical computer science terms, checking whether a set contains a given item is constant time (big-O notation: O(1)). Checking whether a list contains a given item requires checking every item in the list, so it will take longer as the list to check gets longer (big-O: O(n)). I mention that it’s a micro-optimization because with a list of only a few elements like this, it’s almost certainly not going to make any appreciable difference in execution speed.

@PGriffith ah I see. I just thought dictionary in my head. I will read up on that more,

Thank you!. Only other thing I might do is move away from the gui boxes to windows popups.

We have a lot of issues here, And I’m starting to attribute it to threading issues while not confirmed. I’m hoping this and other refactoring will help ease the load on the system.

Fixed all the suggestions, Knocked off about 26 lines of code, which I think is pretty good.

1 Like

The best code is no code. The second best is less code :grin:

4 Likes

Well I guess I can throw some push buttons in. lol

Reminds me of a quote I heard regarding computer science / programming

“Perfection is achieved not when there is nothing left to add, but when there is nothing left to take away”

3 Likes