I've got a class called List_Field
that, as the name suggests, builds list input fields. These list input fields allow users to select a single item per list.
I want to be able to build list input fields that would allow users to select multiple items per list, so I have the following dilemma:
Should I do that through implementing a multiple_choice_allowed
property into the existing List_Field
property, or should I implement a Multiple_Choice_List_Field
subclass of the List_Field
class?
What's the engineering principle that I should follow when confronted with dilemmas like this one?
No. An interface defines how a class should look like (as a bare minimum). Whether you implement this in a base class or in the lowest subclass doesn't matter.
The subclass inherits state and behavior in the form of variables and methods from its superclass. The subclass can just use the items inherited from its superclass as is, or the subclass can modify or override it.
Classes in Java exist in a hierarchy. A class in Java can be declared as a subclass of another class using the extends keyword.
Creating a subclass can be as simple as including the extends clause in your class declaration (such as in the declaration in ImaginaryNumber above). However, you usually have to make other provisions in your code when subclassing a class, such as overriding methods.
Take a look at the SOLID principles. They'll help you in your designs. In particular, the single responsibility principle will tell you not to mix the two concerns in one class, and the Liskov substitution principle will tell you not to create subclasses that break the contract of superclasses, like what you're also proposing.
So what would be the solution in your case? You could create an abstract base class that would be agnostic to the type of selection and then create 2 subclasses, one for single selection and another for multiple selection.
Depends on presence/lack of object evolution - if you want special case, sub-classing or injecting (DI) "select" behaviour (strategy) is good.
But if you also want to allow Field_List to change its behaviour dynamically, then property or mutating method is the only way to go.
Example: Sign-up screen with different "plans" - basic, where you can only select one thing and premium, where you can select as much as you want. Change of plan will switch between drop-down and multiple checkboxes, while still having the very same object including its contents.
I would vote for property/mutate method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With