#180 Once methods

brian Fri 21 Mar 2008

I've debated about this before (with myself), but I find that 90% of the time I override a field getter, it is to do lazy evaluation and results in a lot of boiler plate code. So I think I'm going to add an Eiffel style once keyword which can be used with an instance method to compute it once:

Before:

override UserAgent userAgent
{
  get
  {
    if (@userAgent == null)
    {
      header := headers["User-Agent"]
      if (header != null)
        @userAgent = UserAgent.fromStr(header)
    }
    return @userAgent
  }
}

After:

once UserAgent userAgent()
{
   header := headers["User-Agent"]
   if (header != null) return UserAgent.fromStr(header)
   return null
}

brian Fri 21 Mar 2008

Once methods are now available! They are basically syntax sugar:

once Int x() { return 1972 }

Compiles to:

Int x()
{
  if (x$Store == "_once_") x$Store = x$Once()
  return (Int)x$Store
}

private Obj x$Once() { return 1972 }

private Obj x$Store := "_once_"

See the Method chapter for more info.

tactics Tue 15 Apr 2008

Very sexy~

brian Tue 15 Apr 2008

stolen straight from Eiffel!

Login or Signup to reply.