Complex custom rule creation triggering build failure

We want to implement a SonarQube rule to block the build if the database was called inside a for-loop/iteration
In the following code, we want to create a custom rule (complex) to fail if any EmployeeDao method was called inside a for-loop/iteration:

    class OrganizationService {

        private EmployeeService employeeService;

        public void doSomeLogic() {
            List<Employee> employeeList = employeeService.getEmployees();
            ... some logic here
            employeeList.forEach(employee -> employeeService.updateEmployee(employee));
    class EmployeeService {

        private EmployeeDao employeeDao;

        public List<Employee> getEmployees() {
            return null;

        public void updateEmployee(Employee employee) {
    class EmployeeDao {
        public void update(Employee employee) {
    class Employee { }

We want sonar to fail for this line:

    employeeList.forEach(employee -> employeeService.updateEmployee(employee));

Is this a valid approach? or sonar is not the correct tool in our situation?

Hello @Ahmad_Salah ,

Sorry for the long waiting timeā€¦ Sonar products are not adequate solutions for the situations you try to cover.

  1. Our tools are not expected nor designed to trigger build failure. They are independent in the pipeline and should be used for quality gate and clean code validation.
  2. While not impossible, such custom rules are hard to implement and would require a large effort of specification, implementation, and inner mechanics of the java analyzer. Such rules are also extremely sensitive to False Positivesā€¦ which might annoy your user. On top of this, if you intend to make builds fail, you are heading to drive tons of developers mad.

Hello Michael,

Thank you for the detailed answer. I agree that implementing this inside Sonar will result in a fragile solution.
Do you recommend other solutions or tools that can help apply this rule in our automation pipelines? Manual PR reviews are already taking care of this rule right now.