vendredi 14 décembre 2018

Which patterns can I apply to avoid method overloading all of the methods in this class?

Currently I am looking at refactoring a class and having been studying up on design patterns, I'm curious which if any are applicable to this scenario. How the current class looks:

public WebDriver window(int index) {//stuff};
public WebDriver window(String nameOrId) {//stuff};
public WebDriver windowByTitle(String title) {//title specific stuff};

public WebDriver frame(int index) {//stuff};
public WebDriver frame(String nameOrId) {//stuff};
public WebDriver frameByTitle(String title) {//title specific stuff};

public WebDriver alert(int index) {//stuff};
public WebDriver alert(String nameOrId) {//stuff};
public WebDriver alertByTitle(String title) {//title specific stuff};

now lets say that every single one of these 9 methods, I want to add an optional secondary paramater, that is a Duration for example:

public WebDriver window(int index, Duration of) {//stuff}

but I need such functionality on every one of these methods and don't want to create 9 overloaded methods, reusing a lot of the core code. Each one of these methods creates a new Wait which calls a standard constructor to create it, assuming a default Duration, but I want to offer the ability to provide their own Duration as well.

What pattern is best to take care of such a problem? I plan to rewrite the class completely but I want to create a good solid design.

My Thoughts:

  1. Strategy pattern (WindowSwitchStrategy, FrameSwitchingStrategy, AlertSwitchingStrategy)
  2. Some sort of Builder that when we create just one method we can build up state to decide if the duration should be passed onto the new Wait(); constructor or not.

Pseudo of window(int index) {} :

    try {
        new Wait().until(windowIsReady());
    } catch(TimeoutException ex) {
        //ex stuff
    }

//would like an optional duration here, and if so we do this instead, but giving great reusability when we don't need an explicit duration specified by the caller:
new Wait(duration).until(windowIsReady());

Wait looks like this:

public Wait() {}
public Wait(Duration duration) {}

Thanks

Aucun commentaire:

Enregistrer un commentaire