Manolis Manolis - 1 year ago 81 Question

VB Method naming suggestion

I have a Method that:

  • checks if data are modified

  • if yes, asks the user: "Do you want to save?" (Y/N/Cancel)

  • if answer is yes, it saves the data

  • returns a boolean value whether the user has answered "Cancel", in which case the caller method needs to abort its Form.Close() event.

Problems (interconnected together):

  • I can't think of a proper name for the method.

  • It does many things at the same time.

  • The boolean return type is not very clear. I could directly return the user's answer, but it will be slightly more complicated to use, because the caller has to compare the return value of the function with the Cancel constant instead of comparing to True.

Do you have any suggestions? Thank you!

Private Function CancelDueToUnsaved() As Boolean
If Not _data.Modified Then Return False

Dim answ = MsgBox("Save changes?", MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question, "")

If answ = MsgBoxResult.Yes Then SaveData()

Return (answ = MsgBoxResult.Cancel)
End Function

Private Sub Form_Closing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If CancelDueToUnsaved() Then e.Cancel = True
End Sub

Answer Source

I would name it something like "SaveChanges" (as Tom mentioned) because it should show that the save data action happens here. Also a named parameter may improve readability if that's important:

Private Sub SaveChanges(ByRef cancelled as Boolean)
End Sub

You could also throw custom exception but it would be too much for a single boolean:

Private Sub SaveChanges()
If answ = MsgBoxResult.Cancel Then Throw New UserCancelException
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download