Why we need Abstraction and Interfaces-Perfect Example in Selenium WebDriver

Perfect Example of why you need Abstraction is:

WebDriver driver = new ChromeDriver();

In above line “WebDriver” is an interface which lists all the methods required to be present for Browser Interactions; irrespective of Browser type.

No how would all the Browser’s Driver namely, firefox, IE, Safari etc could ensure that they have all the required methods for Browser Interaction.

This is achieved by OOPs abstraction concept.(Interfaces and Abstract classes in Java is a tool to implement Abstraction).

Lets assume we do not have Interfaces and Abstract classes implementation for Web Driver.

In that case, for a multi-Browser tests, code would like as below:

//Psedo Code

if  ( BrowserType==”Chrome”){

ChromeDriver driver = new ChromeDriver();

}elseif(BrowserType==”Firefox”){

FireFox driver = new FirefoxDriver();

}

Now lets just say ChromeDriver team got a new method which they added in ChromeDriver class and user of selenium test thought of using that method.

Since, FirefoxDriver team did not add it, above test will fail for mozilla browser.

Only way to ensure that all the drivers (ChromeDriver, FireFox Driver) have same set of method and properties is by pointing them to a single source. A source which contains all the required methods for Browser Interaction.

This in realty is achieved by extending ChromeDriver, FirefoxDriver classes etc to “WebDriver” interface which contains signature of all the methods required to be present in a driver. So when there is a need for any new Method, it will be added in “WebDriver” interface and all the extended classes will have to implement it.

This is also a good example of Polymorphism, as driver alone can take multiple forms, it can be used for ChromeDirver Class as well as Fire fox class.

WebDriver driver = new ChromeDriver();

1 thought on “Why we need Abstraction and Interfaces-Perfect Example in Selenium WebDriver”

Comments are closed.