Don't repeat yourself: Natural place for clculations on the FieldItemList of a custom FieldType wanted I have a custom field type that contains a number field, among others.

class MyFieldItem extends FieldItemBase {
    public static function propertyDefinitions($field_definition) {
        $properties = [];
        $properties['some_number'] = DataReferenceTargetDefinition::create(
            'integer'
        );
        ...
    }
    ...
}


I need the sum of all values of the property some_number. A function adding the numbers would look like this:

function addAllNumbers($items) {
    $sum = 0;
    foreach ($items as $item) {
        $sum += $item-&gt;get('some_number')-&gt;getValue();
    }
    return $sum;
}


I need this sum for many purposes, like to display it in the formatter, or to validate forms.

Now, I've found that I'm calculating this sum in several places in my code. But an important programming principle tells me: "Don't repeat yourself!"

Where is a natural place to perform calculations on the FieldItemList of a custom FieldType?

I see several candidates for such a place.


The .module file. However, this is hardly connected to the custom FieldType and often a confusing collection of random things.
The MyFieldItem class defining the custom FieldType. Here, the iteration would go over $this-&gt;parents. However, I don't see a way to access the FieldType object from within the Formatter.
The formatter. However, then it would be necessary to somehow format the FieldItemList during the form validation.
Some utility class. But probably, other developers would find that strange in the future.



  There should be one-- and preferably only one --obvious way to do it.
  (The Zen of Python, by Tim Peters)
The natural place would be a method in a custom field item list:

class MyFieldItemList extends FieldItemList {

  public function addAllNumbers() {
    $sum = 0;
    foreach ($this-&gt;list as $item) {
      $sum += $item-&gt;some_number;
    }
    return $sum;
  }

}


Set the list class in the field type:

 * @FieldType(
 *   ...
 *   list_class = "\Drupal\mymodule\MyFieldItemList",