Please refer to best practices for Selenium here: Selenium Tips and Tricks (to be updated)
I. Programing
1. The code should use clear names
Variables should have names that explain their purpose.
Methods should have names that either explain what the method does or the result returned by the method.
2. Classes should be small
A class should contain an average of less than 30 methods.
3. Methods should be small
Methods should not have more than an average of 30 code lines.
4. Do one Thing
This applies to both classes and methods.
If a method does more than one thing, consider splitting it in 2.
If a class has more than one responsibility, consider breaking it in more classes.
5. Don’t Repeat Yourself
Any duplication, inside a page object class, a page method, a test class or a test method should be avoided.
6. Explain yourself in code
Write code that is self-explanatory, that is so easy to understand so no comments are needed.
7. Make sure the code formatting is applied
Code formatted correctly is easier to read by other developers.
8. Use Exceptions rather than Return codes
If a method cannot fulfill its purpose, instead of returning an obscure error code,
throw an exception since the code is in an abnormal state.
9. Don’t return Null
There are many ways of avoiding returning null.
You can use Optional introduced in Java 8.
Or you can return an empty list.
10. Make class final if not being used for inheritance
Making the class final ensures that it is not extended. All page classes and page element classes should be final.
11. Limit the accessibility of packages,classes, interfaces, methods, and fields
Parent classes (base page class, base test class) should be abstract.
All methods of a parent class should be declared as protected since they should only be used in the child classes.
Only a small number of methods of any class should be public.
If a class should be used only by other classes in the same package, use the default access modifier.
12. Avoid excessive logs
If you are logging tracing information for all page classes and their methods, when you run the whole suite of tests, you will get excessive logs that are very difficult to read.
This becomes even worse if the automated tests are run in parallel on different virtual machines.
13. Avoid creating unnecessary objects
reference:
One thought on “Best practices when writing automation code”