Apex Method of the Day – Method (and other) Declarations in Anonymous Blocks

An anonymous block is Apex code that does not get stored in the metadata, but that can be compiled and executed using… Developer Console, Force.com IDE [or] The executeAnonymousSOAP API call

A method can be defined and called within an Anonymous Block:

Decimal d1 = 123;
Decimal d2 = 456;
system.debug(multiply(d1,d2));

Decimal multiply(Decimal val1, Decimal val2)
{
   return val1 * val2;
}

An exception can be defined and thrown within an Anonymous Block:

if(true) throw new AnonymousException('Foo!');
system.debug('We will not reach here');

class AnonymousException extends Exception {}

A class can be defined and instantiated within an Anonymous Block:

Mean m = new Mean();

for(Account item : [select AnnualRevenue from Account where AnnualRevenue<>null limit 100])
   m.add(item.AnnualRevenue);

system.debug(m.get());

class Mean
{
   Decimal total = 0;
   Decimal count = 0;

   void add(Decimal value)
   {
      total+=value;
      count++;
   }

   Decimal get()
   {
      return total/count;
   }
}

Force.com Apex Code Developer’s Guide – Anonymous Blocks

This entry was posted in Documentation and tagged , . Bookmark the permalink.

2 Responses to Apex Method of the Day – Method (and other) Declarations in Anonymous Blocks

  1. Pingback: The Secret Life of an SObject: Equality, Sets and Maps | FooBarForce

  2. Pingback: Constructive Forces at Work | FooBarForce

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s