1

I have a class that extends another. In the constructor I pass in a bunch of arguments but I've now realised I need to pass in different arguments based on what I'm running the code on:

public searchPage(WebDriver driver, LoadableComponent<?> parent, Properties props) {
    super(driver, parent, Boolean.FALSE, props,action.UK);

In this example the action is using the UK value from the enum, my problem is if I run this on another client I may need to call action.FR

Is there a way I can put a condition in the constructor? For example if something in the prop file says FR then pass action.FR

vahid abdi
  • 9,636
  • 4
  • 29
  • 35
Doctor Who
  • 1,287
  • 5
  • 25
  • 46
  • how about defining two different constructors? pass the differentiating factor as a parameter. – ray Feb 24 '14 at 11:11
  • Factory function? You can put the condition in the factory. Dunno if that's the best option, but it seems pretty simple. – user2357112 Feb 24 '14 at 11:11

4 Answers4

3

Wouldn't it make more sense to just pass the enum value in via the constructor? That way the same constructor will work, no matter what the user puts in.

Example

public searchPage(WebDriver driver, LoadableComponent<?> parent, Properties props, Country country) {
    super(driver, parent, Boolean.FALSE, props, country);
}

// Assumes Country is your enum type. Was just a guess for a placeholder.
christopher
  • 26,815
  • 5
  • 55
  • 89
1

You can't have conditions before the super() call as it needs to be the first. On the other hand, the language does not prevent having expressions in the call, so you could have:

super(driver, parent, Boolean.FALSE, props, getAction(props));

where getAction() would be something like:

private Action getAction(Properties props) {
    ...

Note that for safety you do not want getAction() be something that can be overridden by subclasses, so it should be private, final or static. (Otherwise, according to Murphy, someone will implement one dependent on the state of the incompletely initialized object).

That said, it may be best to use something like a factory pattern instead.

kiheru
  • 6,588
  • 25
  • 31
0

As the constructor call (in this example super()) needs to be first call in the constructor - no, you can't.

The way to resolve this can be for example making two different constructors.

Eel Lee
  • 3,513
  • 2
  • 31
  • 49
0

I feel you can use Builder pattern here. When number of arguments in constructor are many, then it is advised to use Builder pattern.

Client code will specify which type of action he wants to use. For builder pattern,see

Your client code will look like:

SearchPageBuilder builder = new SearchPage.SearchPageBuilder();
builder.setDriver(driver);
builder.setLoadableComponent(parent);
builder.setProperties(props);
builder.setAction(action.UK);
SearchPage page = builder.build();
Community
  • 1
  • 1
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72