Apex - return this

This way you can call your methods "as a flow" to generate an object:

EmailUtil email = new EmailUtil(new String[] {})
  .subject('My subject')
  .htmlBody('my body')
  .senderDisplayName('My name');

Because you return the current object with this you can access it and its methods/attributes.

I personally like this way to do.


It's called Fluent Pattern, and as already mentioned, it enables chaining. You can see it demonstrated in the Composite pattern in Apex Design Patterns.

It's worth reading the excellent answers on Why Would I Not Enable Chaining? for a deeper dive into the impact, but it's incredibly useful for building data. For example, I use it in my SObjectFactory library to simplify specification of multiple fields.

List<Opportunity> records = new SObjectBuilder(Opportunity.sObjectType)
    .put (Opportunity.AccountId, SObjectFactory.provideGenericParent(Account.sObjectType))
    .put(Opportunity.CloseDate, Date.today())
    .count (Limits.getLimitQueries() + 1)
    .create().getRecords();