This is one of the simple operators yet less used due to clarity over its purpose. Let’s looks at it
1.ANDALSO :
Take an example where we are evaluating the business logic.
Output
Case 1: In this case program will execute the IsValidUser function, it returns valid and then execute the HasAccessToUpdateOrders function which is false and everything is ok.
Case 2. Consider here IsValidUser returns false then logically there is no way that user might have any Access to update Orders, however the programs still executes the function HasAccessToUpdateOrders. Logically this should have been avoided, unnecessary execution consuming resources and time. Hence when we use AND both sides of expression will be executed before considering the final result.
So to avoid this we have short-circuiting, so now the same stuff with ANDALSO. And the output seems to evaluate only the first part since it’s false it doesn’t evaluate the second expression and improves the performance.
Output:
2. ORELSE:
Taking same example from above but instead of IsUser we consider IsAdmin, so if user is Admin then he should have access to update orders no need to check further.
Output:
Case 3: In this case program will execute the IsAdmin function, it returns false and then execute the HasAccessToUpdateOrders function which is true and everything is ok.
Case 4: Consider here IsAdmin returns true then logically user have all access to update Orders, however the programs still executes the function HasAccessToUpdateOrders. Logically this should have been avoided, unnecessary execution consuming resources and time. Hence when we use OR both sides of expression will be executed before considering the final result.
So to avoid this we have short-circuiting, so now the same stuff with ORELSE. And the output seems to evaluate only the first part since it’s true it doesn’t evaluate the second expression and save redundant expression evaluation.
Conclusion :
AndAlso & OrElse can help improve performance by avoiding unnecessary code execution or database hits.
It can also be used to check if object is null, to avoid runtime errors.
Ex:
If Not myObject Is Nothing AndAlso myObject.Count Then…
Comments (0)