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

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

The newest version!

Why is this an issue?

Hard-coding a URI makes it difficult to test a program for a variety of reasons:

  • path literals are not always portable across operating systems
  • a given absolute path may not exist in a specific test environment
  • a specified Internet URL may not be available when executing the tests
  • production environment filesystems usually differ from the development environment

In addition, hard-coded URIs can contain sensitive information, like IP addresses, and they should not be stored in the code.

For all those reasons, a URI should never be hard coded. Instead, it should be replaced by a customizable parameter.

Further, even if the elements of a URI are obtained dynamically, portability can still be limited if the path delimiters are hard-coded.

This rule raises an issue when URIs or path delimiters are hard-coded.

Exceptions

This rule does not raise an issue when:

  • A constant path is relative and contains at most two parts.
  • A constant path is used in an annotation
  • A path is annotated

How to fix it

Code examples

Noncompliant code example

public class Foo {
  public static final String FRIENDS_ENDPOINT = "/user/friends"; // Compliant path is relative and has only two parts

  public Collection<User> listUsers() {
    File userList = new File("/home/mylogin/Dev/users.txt"); // Noncompliant
    Collection<User> users = parse(userList);
    return users;
  }
}

Compliant solution

public class Foo {
  // Configuration is a class that returns customizable properties: it can be mocked to be injected during tests.
  private Configuration config;
  public Foo(Configuration myConfig) {
    this.config = myConfig;
  }
  public Collection<User> listUsers() {
    // Find here the way to get the correct folder, in this case using the Configuration object
    String listingFolder = config.getProperty("myApplication.listingFolder");
    // and use this parameter instead of the hard coded path
    File userList = new File(listingFolder, "users.txt"); // Compliant
    Collection<User> users = parse(userList);
    return users;
  }
}

Exceptions examples:

public class Foo {
  public static final String FRIENDS_ENDPOINT = "/user/friends"; // Compliant path is relative and has only two parts

  public static final String ACCOUNT = "/account/group/list.html"; // Compliant path is used in an annotation

  @Value("${base.url}" + ACCOUNT)
  private String groupUrl;

  @MyAnnotation()
  String path = "/default/url/for/site"; // Compliant path is annotated

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy