Skip to content

[Feature]: Please do not cast Locator to LocatorImpl. #1899

@RichMacDonald

Description

@RichMacDonald

🚀 Feature Request

https://github.com/microsoft/playwright-java/blob/main/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java

The following method:

  private LocatorAssertionsImpl(Locator locator, boolean isNot) {
    super(isNot);
    this.actualLocator = (LocatorImpl) locator;
  }

casts Locator to a LocatorImpl. This breaks the purpose of an interface. There may be other implementations of Locator and this causes a cast exception.

For example, I use the Delegate pattern to wrap a Playwright Locator with my own Locator. This lets me add some extra methods that I like to use (syntactical sugar). It also lets me write code that doesn't need to know if it is dealing with a Page or Locator.

Example

No response

Motivation

It is code smell to cast an interface to a class. It also prevents anyone else from providing a different implementation. In many organizations, this will be classified as a bug.

Wrapping the Locator interface with a LocatorDelegate implementation lets me add some convenience methods that I use in my code. Methods that I find useful but the playwright developers feel differently about. For example, I could never remember how to execute "Tab" so I wrote a method in my LocatorDelegate:

public Locator pressTab() {
	page().keyboard().press("Tab");
	return this;
}

I also find the distinction between Page and Locator a little awkward. My LocatorDelegate can hide from a user the fact that we are referencing a Page or a Locator (make the Page act like a Locator).

The unfortunate cast does not break my code. I can always "dereference the delegate" before calling PlaywrightAssertions.assertThat(locator);.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions