CSR :
|
|
Relates :
|
|
Relates :
|
Summary ------- Provide a String instance method to allow function application of custom transformations applied to an instance of String. Problem ------- Functional programming landed in Java with the introduction of lambdas in JDK 8. The main advantage of this style of programming is the clarity it brings to otherwise complex code. At the time, the focus was on the internal iteration of collection object types. Other base objects, such as String, don't have the same advantage because it's **not possible to extend base objects with new methods**. The main recourse is to provide static methods that take the base object as argments. Since static methods can't be chained they distort readabilty of the resulting code. ``` Example: static String naiveDropFirstWord(String string) { return List.of(string.split("\\W+")) .stream() .skip(1) .collect(Collectors.joining(" ")); } static String naiveTitleCase(String string) { return List.of(string.split("\\W+")) .stream() .transform(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); } String title = "darn poor title for a book"; String capped = naiveTitleCase(naiveDropFirstWord(title)).concat("."); Result: Poor Title For A Book. ``` In this example, the reader is forced to interpret portions of the expression from the inside out. Solution -------- Introduce a new String instance method `transform` that applies a Function against the string. ``` Example: static String naiveDropFirstWord(String string) { ... } static String naiveTitleCase(String string) { ... } String title = "darn poor title for a book"; String capped = title.transform(Example::naiveDropFirstWord); .transform(Example::naiveTitleCase) .concat("."); Result: Poor Title For A Book. ``` In this example, the steps can be discerned more clearly. Specification ------------- ``` /** * This method allows the application of a function to {@code this} * string. The function should expect a single String argument * and produce an {@code R} result. * * @param f functional interface to a apply * * @param <R> class of the result * * @return the result of applying the function to this string * * @see java.util.function.Function * * @since 12 */ public <R> R transform(Function<? super String, ? extends R> f) { return f.apply(this); } ```
|