All About Assert Part II: What Assert Is Good For

Now that we know what Assert does, lets figure out what it’s good for.  The two most common uses of Assert are:

  1. Perform high-privilege operations on behalf of untrusted code
  2. Convert one permission demand to another

Yesterday’s example demonstrating what Assert does shows the most common use for this stack walk modifier, namely allowing untrusted code to do trusted things.  In that example, untrusted code running from the Internet was allowed to take advantage of a performance optimization which required reading a file off of the user’s hard disk.

The other place where Assert finds a lot of use is when you want to convert one permission demand into another more appropriate one.  Lets assume that all the calculating I’ve been doing with my high precision value of Pi has caused my server to slow down.  Because of this, I’ve decided to limit the code that can use any of my high precision libraries by requiring a HighPrecisionMathPermission that I’ve written.

In this case, my custom Pi class would still Assert FileIO and Environment permission (since I don’t require my users to have these permissions), and demand a HighPrecisionMath permission, with the net effect of “converting” a FileIO and Environment demand into a HighPrecisionMath demand.  While implementing this, I would first do the demand for HighPrecisionMathPermission since I don’t need to Assert if my callers don’t have this permission in their grant set, and minimizing the amount of time that an Assert is in effect is always a good idea.

Comments (1)