-
Notifications
You must be signed in to change notification settings - Fork 3
/
[G23] Prefer Polymorphism to IfElse or SwitchCase.cs
59 lines (54 loc) · 1.63 KB
/
[G23] Prefer Polymorphism to IfElse or SwitchCase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public void HandleInput(string inputType, string inputValue)
{
switch (inputType)
{
case "button":
HandleButtonInput(inputValue);
break;
case "keyboard":
HandleKeyboardInput(inputValue);
break;
case "mouse":
HandleMouseInput(inputValue);
break;
default:
Console.WriteLine("Invalid input type.");
break;
}
}
// In this example, the HandleInput function takes an input device type and value
// and uses a switch construct to determine which processing method to use based on the input device type.
// This breaks the rule because the switch construct can be replaced by polymorphic objects,
// such as creating an InputDevice base class and derived classes for each device type,
// and using the HandleInput method within each class.
// The code to be used using polymorphism might look like this:
public abstract class InputDevice
{
public abstract void HandleInput(string inputValue);
}
public class ButtonInputDevice : InputDevice
{
public override void HandleInput(string inputValue)
{
// Button Input Handling
}
}
public class KeyboardInputDevice : InputDevice
{
public override void HandleInput(string inputValue)
{
// Keyboard Input Handling
}
}
public class MouseInputDevice : InputDevice
{
public override void HandleInput(string inputValue)
{
// Mouse Input Handling
}
}
public void HandleInput(InputDevice inputDevice, string inputValue)
{
inputDevice.HandleInput(inputValue);
}
// This avoids the switch statement and uses polymorphism instead.