Constructive Forces at Work

A constructor in Apex is called when an instance of a class is created. Code-wise constructors might look like member methods, but they differ in a couple of significant ways.

First, constructors can’t be called any other time than when creating an instance of a class, and second, constructors do not return values. Ever had the build error “Invalid constructor name: foo“? We soon learn that this actually means “Doh! You forgot to provide a return type for your method”.

This does mean, as it does in Java, that Apex constructors are not members that can be inherited:

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

So, a subclass constructor can call a constructor of its superclass. Actually, constructors call superclass constructors automatically in Apex if we don’t do it explicitly. Try running this anonymous code block:

public class ClassOne {
    ClassOne() {
        system.debug('1');
    }
}
public class ClassTwo extends ClassOne {
    ClassTwo() {
        system.debug('2');
    }
}
public class ClassThree extends ClassTwo {
    ClassThree() {
        system.debug('3');
    }
}
ClassThree c = new ClassThree();

Note that class definitions in anonymous blocks are virtual by default, so we don’t need to supply the virtual modifier here.

And here’s a part of my debug log:

19:19:35.059 (59838092)|SYSTEM_CONSTRUCTOR_ENTRY|[16]|<init>()
19:19:35.059 (59944318)|SYSTEM_CONSTRUCTOR_ENTRY|[12]|<init>()
19:19:35.060 (60019420)|SYSTEM_CONSTRUCTOR_ENTRY|[7]|<init>()
19:19:35.062 (62725333)|USER_DEBUG|[3]|DEBUG|1
19:19:35.062 (62740937)|SYSTEM_CONSTRUCTOR_EXIT|[7]|<init>()
19:19:35.062 (62772600)|USER_DEBUG|[8]|DEBUG|2
19:19:35.062 (62780817)|SYSTEM_CONSTRUCTOR_EXIT|[12]|<init>()
19:19:35.062 (62807978)|USER_DEBUG|[13]|DEBUG|3
19:19:35.062 (62816118)|SYSTEM_CONSTRUCTOR_EXIT|[16]|<init>()

We have defined three classes where the second extends the first and the third extends the second. In each case we have defined a constructor, for debugging the order of execution, but we haven’t explicitly called a superclass constructor.

We find that each constructor implicitly invokes the superclass constructor before executing its own body. This works recursively until there are no more superclasses, so that the constructor method bodies are executed in order going down the inheritance chain from most-super-class to the actual class we are constructing.

We can influence the chaining behaviour to some degree by calling specific constructors with this and super.

If we have a class with several constructors, each with different arguments, we can delegate from one constructor to another of the same class using this(…), or select a particular constructor of a superclass using super(…):

public class ClassOne {
    ClassOne() {
        system.debug('1');
    }
}
public class ClassTwo extends ClassOne {
    ClassTwo() {
        system.debug('2');
    }
    ClassTwo(String value) {
        this();
        system.debug('2 ' + value);
    }
}
public class ClassThree extends ClassTwo {
    ClassThree() {
        system.debug('3');
    }
    ClassThree(String value) {
        super(value);
        system.debug('3 ' + value);
    }
}
ClassThree c = new ClassThree('foo');
19:39:29.054 (54167458)|SYSTEM_CONSTRUCTOR_ENTRY|[24]|<init>(String)
19:39:29.054 (54305037)|SYSTEM_CONSTRUCTOR_ENTRY|[20]|<init>(String)
19:39:29.054 (54384541)|SYSTEM_CONSTRUCTOR_ENTRY|[11]|<init>()
19:39:29.054 (54460886)|SYSTEM_CONSTRUCTOR_ENTRY|[7]|<init>()
19:39:29.057 (57619207)|USER_DEBUG|[3]|DEBUG|1
19:39:29.057 (57636883)|SYSTEM_CONSTRUCTOR_EXIT|[7]|<init>()
19:39:29.057 (57673115)|USER_DEBUG|[8]|DEBUG|2
19:39:29.057 (57684149)|SYSTEM_CONSTRUCTOR_EXIT|[11]|<init>()
19:39:29.057 (57743445)|USER_DEBUG|[12]|DEBUG|2 foo
19:39:29.057 (57766853)|SYSTEM_CONSTRUCTOR_EXIT|[20]|<init>(String)
19:39:29.057 (57829601)|USER_DEBUG|[21]|DEBUG|3 foo
19:39:29.057 (57848548)|SYSTEM_CONSTRUCTOR_EXIT|[24]|<init>(String)

It is important to note that in order to preserve the order of execution of the chain of constructors, super or this must be the first line of the body of a constructor.

Constructors however are optional, and so to preserve the constructor chain, the compiler will provide a default zero-argument constructor for us just as long as we don’t provide any constructors ourselves:

If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. You must create your own.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_constructors.htm

Which also means of course that if you do create a constructor in an abstract/virtual class that takes argument(s), you must then also provide a zero-argument constructor in order to extend the class, even if you don’t need one (it has an empty body). If you don’t then you will get a build error when you extend the class:

Parent class has no 0-argument constructor for implicit construction

Links

http://salesforce.stackexchange.com/questions/24275/inheriting-non-implicit-constructors-on-apex-classes

Force.com Apex Code Developer’s Guide – Using Constructors

Posted in Documentation | Tagged | Leave a comment

Dynamic Field Sets

One of the things I love about Force.com is how easy it can be to stitch together blocks of functionality provided in the platform, saving you development effort. Spending a little extra time working out how to best use platform features can also save effort downstream – when you align yourself with the platform you can usually benefit from enhancements and additional functionality very quickly as it is added by Salesforce.

I was recently asked whether we could assign Field Sets for Visualforce pages to a user’s profile (without using Field Level Security to limit access to the fields entirely). Although this is not out-of-the-box functionality, I felt sure that this should be possible with a little effort by stitching together Field Sets and Hierarchical Custom Settings.

Continue reading

Posted in Tutorials | Tagged , , , | 1 Comment

Back from the Dream side of the Force

Just back from Dreamforce ’13, which was, what’s Marc’s word for it?… oh, yes… awesome.

As per my last post, I had two sessions in the DevZone this year: Practical Introduction to Chatter Publisher Actions (with Carolina Ruiz @CarolEnLaNube), and Tests and Testability: Apex Structure and Strategy

The slides for these sessions are available to download as PDF:

DF13TestsAndTestability

DF13ChatterPublisherActionsAndSalesforce1

The session recordings are also now available:

Tests and Testability – youtube

Chatter Publisher Actions and Salesforce1 – youtube

I am planning a number of posts on Tests and Testability, in which I will reuse and expand on the DF13 material.

Posted in News | Tagged | 2 Comments

A journey to the Dream side of the Force

I will very shortly be off to San Francisco to attend Dreamforce 2013. I am delighted to be speaking at two DevZone sessions this year:

Practical Introduction to Chatter Publisher Actions

This session is on Tuesday, November 19th at 1:30 PM, and I am very fortunate to be presenting alongside FinancialForce colleague, Carolina Ruiz @CarolEnLaNube

Chatter Publisher Actions provide a new way of interacting with Salesforce applications, allowing users to take control of records and processes from within the Chatter feed. Publisher Actions are inherently mobile – providing an easy route to engaging users with your applications via touch devices. Join us as we demonstrate specific use cases, and code examples to help developers take advantage of this new feature of the Force.com platform.

Tests and Testability: Apex Structure and Strategy

I’m presenting this session solo on Wednesday, November 20th at 9:00 AM.

Join us as we look at unit tests in Apex – what they are and where they fit within an efficient and effective testing strategy. We’ll also consider the demands that implementing such a strategy makes on how Apex code is structured in a Force.com application. You’ll leave with an appreciation of the test pyramid, and some specific examples of mocking techniques.

If you’re going to be at Dreamforce this year then it would be great to see you! Register for these sessions here:
Practical Introduction to Chatter Publisher Actions
Tests and Testability: Apex Structure and Strategy

I will also be posting articles on these topics here on foobarforce soon after Dreamforce.

FinancialForce.com has some great sessions planned this year – so do check them out too!

Posted in News | Tagged | 1 Comment

Apex Method of the Day – String.isEmpty(String myString)

Boolean result = String.isEmpty(myString);

Rather than:

Boolean result = (myString==null || myString=='');

Force.com Apex Code Developer’s Guide – String Methods

Posted in Documentation | Tagged , | 1 Comment

Speedy Force.com Documentation Search in Chrome

Google Chrome has a great feature for customising your searches from the “omnibox” (URL/search box) which you can use to speed up your searches of the Force.com developer documentation.

Continue reading

Posted in Tutorials | Tagged , | 2 Comments

The Secret Life of an SObject: Equality, Sets and Maps

Equality

When testing for equality between sObjects in Apex, it is the sObjects’ properties - the values of the sObjects’ fields – which are compared. So two separate sObject instances that have the same field values are considered equal:

Account foo1 = new Account(), foo2 = new Account();
foo1.Name = 'bar';
foo1.AnnualRevenue = 12345;
foo2.Name = 'bar';
foo2.AnnualRevenue = 12345;
system.assert(foo1 == foo2);

But, if we were to mimic our sObject using a custom Apex type, we would find that by default, two instances with the same property values would not be considered equal:

MyAccount foo1 = new MyAccount(), foo2 = new MyAccount();
foo1.Name = 'bar';
foo1.AnnualRevenue = 12345;
foo2.Name = 'bar';
foo2.AnnualRevenue = 12345;
system.assert(foo1 != foo2);

public class MyAccount
{
   public String Name;
   public Decimal AnnualRevenue;
}

See Method Declarations in Anonymous Apex

This is because with Apex classes we have to decide how we want equality to be evaluated, by defining our own equals method.

If we don’t define an equals method then the equality operator will compare object references (memory locations) – in other words asking “are these references to the exact same instance?”

If we wish, we can make the same reference comparison with sObjects too, using the exact equality and exact inequality operators.

Account foo1 = new Account(), foo2 = new Account();
foo1.Name = 'bar';
foo1.AnnualRevenue = 12345;
foo2.Name = 'bar';
foo2.AnnualRevenue = 12345;
system.assert(foo1 !== foo2);
foo2 = foo1;
system.assert(foo1 === foo2);

We cannot however define our own equals method for sObjects. Continue reading

Posted in Documentation | Tagged , , | 3 Comments