-4

i'm attempting to write a Java class to perform basic string manipulation functions.

I want this class to be callable in some manner like:

String tmp = StringUtils.RemoveSpaces(str).RemoveSlashes();

or

String tmp = StringUtils.RemoveSlashes(str).RemoveSpaces();

I'm struggling to figure out how to structure this class. I guess some method or variable within the class will be static, and the methods will return 'this'. So how would my RemoveSlashes method return a string to 'tmp' if it's returning this? Will i be forced to use RemoveSlashes.toString() or RemoveSlashes.getString() or something to that effect. Seems a bit convoluted...

I'd appreciate if you could help me with the method definitions and return types.

Todd
  • 30,472
  • 11
  • 81
  • 89
  • 2
    Consider Builder pattern https://en.wikipedia.org/wiki/Builder_pattern#Java – Kaspars Rinkevics Aug 15 '17 at 13:22
  • 1
    Related: https://stackoverflow.com/questions/31754786/how-to-implement-the-builder-pattern-in-java-8 – Tom Aug 15 '17 at 13:23
  • Doing it like this will force you to implement all methods twice: onnce as a static method taking a String as argument and returning an object that contains the temporary result, and once as an instance method of this object. It's doable, but it would be simpler to rather use StringUtils.fromString(str).removeSlashes().removeSpaces().toString(). Note the respect of the Java naming conventions, BTW. In any case, you'll need a final method getting the string out of the object wrapping it. – JB Nizet Aug 15 '17 at 13:25
  • Also, you will forever be confusing any Java programmer who is only giving your code a quick look-over if you continue to name your methods starting with capital letters. That makes them visually look like class names. It's one of the most-followed optional conventions in Java. – Tim M. Aug 15 '17 at 13:57

1 Answers1

1

This might help you get started.

public class StringUtil {

    public static void main(String args[]) {
        String url = "http://something.com/ \\ponies";
        String newValue = StringUtil.str(url).removeSlashes().removeSpaces().uppercase().getValue();
        System.out.println(newValue);
    }

    private String value;

    public StringUtil(String value) {
        this.value = value;
    }

    public static StringUtil str(String value) {
        return new StringUtil(value);
    }

    public StringUtil removeSlashes() {
        value = value.replace("\\", "");
        return this;
    }

    public StringUtil removeSpaces() {
        value = value.replace(" ", "");
        return this;
    }

    public StringUtil uppercase() {
        value = value.toUpperCase();
        return this;
    }

    public String getValue() {
        return value;
    }
}
Adam
  • 81
  • 4