If face a logic error error such (Expired user, invalid ID), then what is the best way to tell the parent method of this error
Since you want the parent method to know the error, it seams that you are not sure that ID
is valid and the User
is not expired before you call the GetUser
method. Right?
If you are not sure that parameters you pass into the function are valid, then using exceptions is not justified and you should return error information instead.
You can return error information more functional way similar to what Scala, Go and Rust languages suggest.
Create a generic class to return either an error or a value
public class Either(of ErrorType, ValueType)
public readonly Success as boolean
public readonly Error as ErrorType
public readonly Value as ValueType
public sub new(Error as ErrorType)
me.Success = False
me.Error = Error
end sub
public sub new(Value as ValueType)
me.Success = True
me.Value = Value
end sub
end class
Create an enumeration of errors that your function can have
public enum UserError
InvalidUserID
UserExpired
end enum
Create a function that takes a User ID as an argument and returns either an error or a User
function GetUser(ID as integer) as Either(of UserError, User)
if <business logic to find a user failed> then
return new Either(of UserError, User)(UserError.InvalidUserID)
end if
if <user expired> then
return new Either(of UserError, User)(UserError.UserExpired)
end if
return new Either(of UserError, User)(User)
end function
In the caller (parent) method check for the error and apply business logic
dim UserID = 10
dim UserResult = GetUser(10)
if UserResult.Success then
rem apply business logic to UserResult.Value
else
rem apply business logic to UserResult.Error
end if
Note: if you rewrite this code using Exceptions you will get exactly the same amount of code.