G
G
gomerIT2021-11-01 17:18:12
JavaScript
gomerIT, 2021-11-01 17:18:12

SOLID Single responsibility - should I write a separate class in this case?

The goal is to calculate the sum of all two values ​​of keys a and b in an object that are in an array, but also be able to calculate the sum for only one object.

const data = [{"id": 1, "a": 99, "b": 100}, {"id": 2, "a": 1 "b": 2}];
const oneEl = {"id": 3, "a": 2, "b": 10};

It is immediately clear that here you can write one method that will be used in another method, thereby solving two problems.
class Calc {
  calcAmount (obj) {
    const {a, b} = obj;
    return a + b;
  }

 calcAmountOfArray(data) {
   let sum = 0;
   data.forEach((item) => {
     sum += this.calcAmount(item);
   });

  return sum;
 }
}

Everything seems to be logical, but didn’t I violate the single responsibility by doing this? Let's say a new key "c" appears and you have to calculate its amount. My intuition tells me to create a separate class for the calcAmount method, but is it worth it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pin2t, 2021-11-10
@pin2t

Well, let's start with the fact that you don't need a class here at all. Because there is no data in the Calc class, only methods. Here are the functions you need, not the class.
There is no need to invent and come up with something related to these principles, they are very abstract. Even the author of SOLID himself changed shoes a hundred times what he meant by this S.
A simple function

arrayAmount(data) {
   let sum = 0;
   data.forEach((item) => {
     const {a, b} = item;
     sum += a + b;
   });

  return sum;
 }

will be sufficient

A
Aetae, 2021-11-01
@Aetae

calcAmountby SOLID must be a method on an object with these keys.
Those. let's say it came from the server

const data = [{"id": 1, "a": 99, "b": 100}, {"id": 2, "a": 1 "b": 2}];

Before you do anything with it, you convert it to a typed structure:
interface Calculable {
  calcAmount(): number;
}

class CalculableAB implements Calculable {
  constructor(obj) {
    Object.assign(this, obj);
  }
  calcAmount() {
    const {a, b} = this;
    return a + b;
  }
}

struct = data.map(obj => new CalculableAB(obj));

Well, then when working with anyone, Calculableyou simply call from him calcAmount(). How it is implemented there - you do not care.
This is of course hardcore OOP and in most small cases this is not necessary, but I think the essence is clear.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question