Search code examples
javaselenium-webdrivercoding-style

Java (Selenium WebDriver) - how to write compact code


I'm questioning myself on how to write more compact code and avoid calling object in every line like this:

object.method1();
object.method2();
object.method3();
// etc

Recently I was surfing the net and found something like this:

object.method1();
.method2();
.method3();
// etc

So, how to achieve the style above without calling the object each time?

Sorry for such a basic question maybe, but Idk how it's named and how to google it. Hope for your help. Thanks a lot!


Solution

  • This is called Fluent pattern, also known as Chain of invocation.

    In short: Your test is composed of high level steps and for each step/method you should know what it returns, if it doesn't navigate to another object then return the current instance (this), else return the next object.

    e.g. login successful > account page, failed login > login page