All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S4274.html Maven / Gradle / Ivy

There is a newer version: 8.6.0.37351
Show newest version

Why is this an issue?

An assert is inappropriate for parameter validation because assertions can be disabled at runtime in the JVM, meaning that a bad operational setting would completely eliminate the intended checks. Further, asserts that fail throw AssertionErrors, rather than throwing some type of Exception. Throwing Errors is completely outside of the normal realm of expected catch/throw behavior in normal programs.

This rule raises an issue when a public method uses one or more of its parameters with asserts.

Noncompliant code example

 public void setPrice(int price) {
  assert price >= 0 && price <= MAX_PRICE;
  // Set the price
 }

Compliant solution

 public void setPrice(int price) {
  if (price < 0 || price > MAX_PRICE) {
    throw new IllegalArgumentException("Invalid price: " + price);
  }
  // Set the price
 }

Resources

Programming With Assertions





© 2015 - 2025 Weber Informatics LLC | Privacy Policy