I may be taking a simplistic view but could you not just refactor your code to
Code:
Try
DB.Initialize
DB.Query
If DB.Found = True Then
DB.Execute
End If
Catch
Log(LastException)
End Try
DB.Close
ReturnApiResponse
The example I showed is an over simplified code.
Here is the real scenario. In real life I may have more code.
[CODE lang="b4x" highlight="8,9,22,23,24,31,32,33"]Private Sub PutProductByIdExample (id As Int)
Try
Dim str As String = WebApiUtils.RequestDataText(Request)
Dim data As Map = str.As(JSON).ToMap
Catch
HRM.ResponseCode = 422
HRM.ResponseError = "Invalid json object"
ReturnApiResponse
Return
End Try
Try
' Check conflict product code
DB.Initialize(Main.DBType, Main.DBOpen)
DB.Table = "tbl_products"
DB.Where = Array("product_code = ?", "id <> ?")
DB.Parameters = Array As String(data.Get("product_code"), id)
DB.Query
If DB.Found Then
HRM.ResponseCode = 409
HRM.ResponseError = "Product Code already exist"
ReturnApiResponse
DB.Close
Return
End If
DB.Find(id)
If DB.Found = False Then
HRM.ResponseCode = 404
HRM.ResponseError = "Product not found"
ReturnApiResponse
DB.Close
Return
End If
DB.Reset
DB.Columns = Array("category_id", _
"product_code", _
"product_name", _
"product_price", _
"modified_date")
DB.Parameters = Array(data.Get("category_id"), _
data.Get("product_code"), _
data.Get("product_name"), _
data.GetDefault("product_price", 0), _
data.GetDefault("modified_date", WebApiUtils.CurrentDateTime))
DB.Id = id
DB.Save
HRM.ResponseCode = 200
HRM.ResponseMessage = "Product updated successfully"
If HRM.OrderedKeys Then
HRM.ResponseObject = DB.Results2.Get(0)
Else
HRM.ResponseObject = DB.First
End If
Catch
Log(LastException)
HRM.ResponseCode = 400
HRM.ResponseError = "An error occured"
End Try
ReturnApiResponse
DB.Close
End Sub[/CODE]
I can use nested if-else but I prefer to avoid it.
If there is a validation failed, the code can just straight jump to the bottom and I don't need to write the repeating code to close DB, return something and exit the execution every time.