How to explain why a developer should avoid case statements and create new classes?

I have several times to try to explain to the developer why they should change a class that has multiple instances

switch(m_type) {
  case TYPE_A:
    ...
    break;

  case TYPE_A:
    ...
    break

  ...
}

Where m_type is a (final) reference to an enum specifying the type of instance.

Whenever I see this, I think it's time to split the class into several subclasses, where the particular class you create determines the type. The argument I always return is this: "It seems you should not create all these classes with hardly any code, what will they do there? Like 2 methods or something!"

, , , . , , .., . , , . , , , , , , , .

, , , - , ?

,

+3
8

: : . .

- :

Replace Type Code , . , , . . , .

, .

+2

, case, . . C- , Java, . () () .

, , , # 2 , , , , .

, . switch . , , , . , , .

+2

, . , "" , , , .

+1

Single-Choice , , . . , switch, , . , , , .

+1

, , switch.

0

, . vtable ( ++) , , , .

0

, - . , case, , , , .

.

0

The code you specify directly violates the Open / Closed Principle (“O” in SOLID). As for OOP, this should be enough to do your thing .; -)

0
source

Source: https://habr.com/ru/post/1772823/


All Articles