Wednesday, December 18, 2013

Force Multiple Returns - "Breakers"

I would really, really like a way in .NET to unwind the stack twice in a return-like statement. This would be exceedingly useful in request handling methods that check some conditions and exit the big handler if the check fails. There is currently no way to do this without inserting "if check is false then exit" everywhere. It's even more of a pain in ASP .NET applications that require the request to be aborted if the page will not be fully served.

Sub Page_Load() Handles Me.Load
 If Not IsUserAdmin(Session("UserID")) Then
  Response.Redirect("PermissionDenied.html")
  Exit Sub
 End If
 ' actual page loading stuff
End Sub

Here, it would be excellent if the check function could cancel the Page_Load routine. (It might be necessary to pass the Response variable to an auth function.) I was thinking something like this:

Breaker(1) Sub EnsureUserAdmin(ID As Integer, _
 Handler As HttpResponse)
 If Not IsUserAdmin(ID) Then
  Handler.Redirect("PermissionDenied.html")
  Break 1
 End If
End Sub

Breakable Sub Page_Load() Handles Me.Load
 EnsureUserAdmin(Session("UserID"), Response)
 ' administrative things
End Sub

The parameter to the Breaker keyword specifies how many frames up the stack the method can break. The Breakable keyword flags the method as being able to use breaker methods.

I realize it's kind of redundant for void returners as they could be changed into Booleans, but for functions that can actually have a useful output, it would be a real pain to use a composite/nullable structure. Please, Microsoft?

No comments:

Post a Comment