---
url: https://trigger.beyondthecloud.dev/after-undelete/add-ons/finalizer.md
description: >-
  Run code once per chunk after an after undelete Writer or Dispatcher, with the
  restored records that qualified - aggregate queries, bulk registrations.
---

# AfterUndelete.Finalizer

Run code once per chunk with the records that qualified, such as one aggregate query or one bulk registration.

**Signature**

```apex
public interface Finalizer {
    void finalizeOnAfterUndelete(TriggerTypes.UndeleteRecords records);
}
```

* `finalizeOnAfterUndelete(records)`: called once per chunk, after this handler’s records, only if at least one record qualified; after the dispatch for a Dispatcher.

**Example**

::: code-group

```apex [Skeleton]
public with sharing class ContactWriter implements AfterUndelete.Writer, AfterUndelete.Finalizer {
    private TriggerTypes.UnitOfWork unitOfWork;

    public Boolean writeOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterUndelete(TriggerTypes.UndeleteRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }

    public void finalizeOnAfterUndelete(TriggerTypes.UndeleteRecords records) {
        for (Id accountId : records.getIdsOf(Contact.AccountId)) {
            this.unitOfWork.toUpdate(new Account(Id = accountId, Description = 'Contacts changed'));
        }
    }
}
```

:::

## Rules {#rules}

* **Keep the unit of work in a field.** Store the `unitOfWork` from the action, as the Skeleton does. What you register here commits with the Writer's other writes.
* **Not an end-of-restore hook.** It runs at this handler's turn, before later handlers and before the unit of work commits.
* **Direct DML runs at once.** It is not merged with any unit of work.
