The appropriate way of implementing toggleable features into my code?

Viewed 31

(I'm a beginner)

What is the recommended/cleanest/most efficient way of implementing features that can be toggled on/off by users?

I'm planning to add some features to my app that the user can toggle on or off in a Settings page. E.g., haptic feedback when tapping certain Views. In my code, this View has a onClickListener that executes the haptic feedback and some other methods. In the Settings page for my app, I'll put something like "Enable haptic feedback" with a Switch. Example

The first idea that comes to mind is just putting if wherever the vibrate method is called. Something like...

    myView.setOnClickListener(new View.OnClickListener) {
        if (hapticsSwitch.isEnabled) {
            vibrate(10) //10 ms feedback
        }
    
        //more methods...  
    }

However, this if would need to be repeated whenever I call any toggleable feature in my app. So perhaps a cleaner way would be putting this if inside those features' methods. E.g.

    public void vibrate(Long duration) {
        if (hapticsSwitch.isEnabled) {
        // ...
        }
    }

But I have no experience with toggleable features. So, what is the recommended/cleanest/most efficient way of implementing toggleable features into my code?

1 Answers

That is a very nice question and its not specific to toggle, but to "single level of abstraction" as uncle bob calls it. In my opnion the right thing to do is to put it inside the vibrate function and inside any function that is influenced by that parameter.

There are 2 things you should consider:

  1. Does Vibrate(long duration) can do its job well without hapsticsSwitch. I think the answer to that is no and it will work well only if its caller did the if statement you suggested, other developer can easily fall in that pit and create a bug

  2. How easy it will be to change that logic when this condition will be changed from only looking at hapsticsSwitch && newFeaturehow many changes will you have to make. In my opinion it will be nuch harder to go over all the callers of vibrate.

Final note, I think you might want to use the vibrate without the condition in your app it does not mean you should move the of statement from vibrate(Long duration) to its caller, but you need to split your functions to something like vibrateIfNeeded(Long duration) and vibrate(Long duration) function that vibrate if needed will call.

Tip: read the book called "clean code" by robert c. Martin

Related