Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern.

Here is a simple if-else ladder that I have:


       if(dataKeyinresponse === 'year') {
           bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
           nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
        } else if(dataKeyinresponse === 'quarter') {
            let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
            // nestedbed = new Date(moment(new Date(item['key'])).add(3, 'months').format('YYYY-MM-DD'));
            nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
        } else if(dataKeyinresponse === 'month') {
            nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
        } else if(dataKeyinresponse === 'week') {
            //Relying more on the ES start date for week
            nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
        } else {
          // bed = bucketStartDate;
          nestedbed = new Date(item['key']);
        }

And now, I have applied the strategic pattern to it:


interface emptyBucketInterface {
    fnGetEmptyBuckets();
}
class year implements emptyBucketInterface {
    fnGetEmptyBuckets() {
        bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
        nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
        return {
            "bsd": bsd,
            "nestedbed": nestedbed
        };
    }
}
class quarter implements emptyBucketInterface {
    fnGetEmptyBuckets() {
        let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
        nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
        return {
            "tempDate": tempDate,
            "nestedbed": nestedbed
        };
    }
}
class month implements emptyBucketInterface {
    fnGetEmptyBuckets() {
        nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
        return {
            "nestedbed": nestedbed
        };
    }
}
class week implements emptyBucketInterface {
    fnGetEmptyBuckets() {
        nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
        return {
            "nestedbed": nestedbed
        };
    }
}

However, I'm uncertain about how to determine which class to invoke based on a condition.

In the previous if-else ladder, it checks for the value of dataKeyinresponse and then executes certain statements.

But in the strategic pattern, I'm unsure how to evaluate the condition and then trigger the appropriate class.

Any assistance or guidance would be greatly appreciated.

Answer №1

An illustration of how the strategy pattern works:

public class ExampleClass {
    private final Map<String, StrategyInterface> strategies = new HashMap<String, StrategyInterface>();

    public ExampleClass() {
        strategies.put("option1", new OptionOne());
        strategies.put("option2", new OptionTwo());
        strategies.put("option3", new OptionThree());
        strategies.put("option4", new OptionFour());
    }

    public void executeAction(String action) {
        strategies.get(action).performStrategy();
    }
}

For a deeper understanding, refer to: which demonstrates creating strategies via a factory method.

Suggestion: It's recommended to use capitalized first letters for class names like strategyInterface => StrategyInterface

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I wish to adjust the font size as well as resize the table elements simultaneously

Adjusting the height and width of the table should automatically adjust the font size as well. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Resizable - Default functiona ...

Verify whether the chosen options from a dropdown list coincide with a predetermined value

I am working with a form that generates dropdown lists dynamically. <c:forEach var="companyList" items="${company.detailList}" varStatus="status"> <tr> <td>c:out value="${companyList.employeeName}" /></td> <td> <select ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

A guide on sending arguments to a react function component from a JSX component via onClick event handling

Below is a brief excerpt from my extensive code: import React from "react"; const Home = () => { return ( imgFilter.map((imgs) => { return ( < Col sm = "3" xs = "12" key ...

Using PHP to perform live calculations with arrays in real time

Currently, I am working on developing a new system for a client that allows them to create bookings and invoices to send to their clients. One specific requirement my client has is the need for a table column to be added below the container columns in whi ...

Struggling to use the bind method for the loadScene callback function in cocosCreator or cocos2d-x?

When the loadScene() callback function is bound, the information retrieved from getScene() becomes inaccurate. Upon transitioning from the Entry Scene to the Lobby Scene, I perform post-processing tasks. The implementation was done in TypeScript. Entry. ...

The jQuery .load function does not function properly when an ajax query is already underway

My web application utilizes dynamic loading of content within the same div (.content) through either an ajax request or a .load() request. An example of the ajax request code snippet is: $(document).on('click', '.button1', functio ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

Issue with Translate3d functionality in fullpage.js not functioning as expected

Currently, I am in the process of constructing a website using fullpage.js with WordPress. Everything is functioning well except for one issue - when attempting to disable the plugin by using destroy() or changing setAutoScrolling to false, the translate3d ...

What is the name attribute of an ES2015 function?

var individual = { announceIdentity() { console.log(this.identity); }, get firstID() { return "Superman"; } }; individual.announceIdentity.identification // "identity" individual.firstID.identifier // "get firstID" I recently came acros ...

accordions that are supposed to adapt to different screen sizes are

My custom responsive accordions are not functioning as expected. The requirement is to display headings and content for desktop view, but switch to accordions on smaller devices. I have managed to do this, however, when resizing the window, the functionali ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

Versatile route able to handle any request thrown its way

My Node.js app is up and running smoothly using the Express.js framework. All routes in my application are set to post routes, such as: app.post('/login', function(req, res){ //perform login validation }); app.post('/AppHomepage', fun ...

Having trouble with the auto-complete feature in the search box when using Jquery

I'm currently working on implementing TypeAhead functionality for a search textbox. Within the form, I have 2 radio buttons and if one of them is selected, I need the type-ahead feature to populate the list of masters in the search box. //html < ...

Facing a Null Pointer Exception when Deserializing Gson?

When attempting to parse JSON data in order to extract certain values, I encountered a particular issue. { "username":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a1babdb0babba692b5bfb3bbbefcb1bdbf">[email protect ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...