Question: Equals sign (and others) in constant


Equals sign (and others) in constant

Answers 2
Added at 2016-12-14 15:12

I am currently refactoring a codebase inherited from another developer. In several classes, i found constants that contained the symbols =, ? and & (and others). They are used to build URLs, like so:

class SomeClass {
    private static final String EQUALS = "=";
    private static final String AMPERSAND = "&";
    private static final String QUESTION_MARK = "?";
    private static final String FORWARD_SLASH = "/";
    // ...

    public String getSomeURL() {
        return ProjectConstants.BASE_URL + entityName + FORWARD_SLASH + 
             anotherName + QUESTION_MARK + parameterName + EQUALS + parameterValue;

I do not see the benefit of this. What is the reason for this style instead of just writing variable + '/' + variable + "?parameterName=" + parameterValue?

Answers to

Equals sign (and others) in constant

nr: #1 dodano: 2016-12-14 15:12

I think there are not any deep technical reasons here

The only little thing I see: they make typos like "==" less likely to happen, as EQUALS + EQUALS is obviously more obvious to spot.

On the other hand, that shouldn't really matter in reality; because in reality you would be calling helper methods to build those URLs anyway. So, once you got the helpers right, few chances of ever having typos in that "generated" content.

But even then I would not be using String constants but char values.

nr: #2 dodano: 2016-12-14 15:12

The constants are useful, but poorly named. If they're used in URL construction, they should be named like this:

private static final String PARAMETER_ASSIGNMENT = "=";
private static final String PARAMETER_SEPARATOR = "&";
private static final String QUERY_INTRODUCER = "?";
private static final String PATH_SEPARATOR = "/";

That way, their names will refer to their semantics (which they should) and not to their contents (the whole point is to abstract away from the contents!).

The code of getSomeURL() will then much more directly signal what it really does:

public String getSomeURL() {
    return ProjectConstants.BASE_URL + entityName +
           PATH_SEPARATOR + anotherName +
               parameterName + PARAMETER_ASSIGNMENT + parameterValue;
Source Show
◀ Wstecz