0

I always have the same question when I must to work with nested objects structure. An example:

class Criteria {
  filters: Filter[];
}
class Filter {
  field: string;
  operator: Operator;
  value: string;
}
class Operator {
  operator: '=' | '!=';
}

I try to apply Demeter's Law at return methods on that cases, but what's the best practice on creation step with that structures?

  • Create all objects from the client
class Client {
  constructor() {
    const criteria = new Criteria([new Filter('field1', new Operator('='), 'value1')]);
  }
}
  • Create all objects from the root object (Criteria) passing only primitives from the client to root class.
class Client {
  constructor() {
    const criteria = new Criteria([{field: 'field1', operator: '=', 'value': 'value1'}]);
  }
}
Jose Luis
  • 11
  • 1

1 Answers1

0

It depends on what the objects are for, so you may see both kinds of patterns in good code -- your example strips away everything that would indicate one vs the other.

I think in good code the first pattern -- the client creates the objects -- will be more popular. That is because those objects would be injected dependencies, and following the SOLID principles, the Criteria implementation should not have dependencies on all the different types of filters. If that were not the case, then why do you have a Filter class at all?

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87