10
\$\begingroup\$

I like to overcomplicate things, this is fairly simple though but I would like to keep it simpler without lowering readability. Not just to improve my code but also my self.

private String checkTrailingSlash(String website) {
    if(!website.endsWith("/")){
        website = website + "/";
    }
    return website;
}
\$\endgroup\$

5 Answers 5

23
\$\begingroup\$

You could use a ternary operator to inline the condition into a single return statement:

private String checkTrailingSlash(String website) {
    return website.endsWith("/") ? website : website + "/";
}
\$\endgroup\$
0
11
\$\begingroup\$

Honestly, I'm not sure how much simpler you can make this.

I'd suggest a slightly clearer name though - maybe ensureTrailingSlash? checkX sounds more like a predicate. My other suggestion would be to add some spaces in your if-conditional, depending on your taste:

if (!website.endsWith("/")) {

This could be a static method, as well.

\$\endgroup\$
9
\$\begingroup\$

It would be less verbose to write

website += "/";

instead of

website = website + "/";

So, yeah, you totally overcomplicated it. =)

Also, instead of checkTrailingSlash, it would be clearer if renamed to ensureTrailingSlashExists.

\$\endgroup\$
0
4
\$\begingroup\$

If you don't like if statements in your code, then you could use something like this:

website=website.replaceAll("([^/])$","$1/") ;

it uses a regex to replace last character only if it is NOT a / with the last character plus the /.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ "I would like to keep it simpler without lowering readability" I would argue that a regex approach rarely doesn't lower readability \$\endgroup\$
    – Theoriok
    Commented Apr 5, 2019 at 6:34
  • \$\begingroup\$ Yes but it has the big advantage not to be pipeable \$\endgroup\$ Commented Mar 22, 2021 at 18:34
  • \$\begingroup\$ Alternatively you could use lookbehind: website.replaceFirst("(?<!/)$","/"). This avoids having to use a backreference. Using the regex "/?$" looks even simpler, but has the disadvantage that it allocates a new string even when the original has a trailing slash already. \$\endgroup\$ Commented Nov 23, 2021 at 6:44
1
\$\begingroup\$

Since often browsers also support backslashes, you can also consider this:

public static String addTrailingSlashIfMissing(String str) {
    String slashChar = str.contains("\\") ? "\\" : "/";
    return str.endsWith(slashChar) ? str : str + slashChar;
}

which can be also useful for file system paths.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.