Hard-coding a URI makes it difficult to test a program for a variety of reasons:
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.
This rule does not raise an issue when an ASP.NET virtual path is passed as an argument to one of the following:
System.Web.HttpServerUtilityBase.MapPath(), System.Web.HttpRequestBase.MapPath(),
System.Web.HttpResponseBase.ApplyAppPathModifier(), System.Web.Mvc.UrlHelper.Content() System.Web.VirtualPathUtility Microsoft.AspNetCore.Mvc.VirtualFileResult, Microsoft.AspNetCore.Routing.VirtualPathData
public class Foo {
public List<User> ListUsers() {
string userListPath = "/home/mylogin/Dev/users.txt"; // Noncompliant
return ParseUsers(userListPath);
}
}
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 List<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
string userListPath = Path.Combine(listingFolder, "users.txt"); // Compliant
return ParseUsers(userListPath);
}
}