It has been said that the constant wrapping of JDK (or other language APIs) is a sign of over-engineering (see e.g. Concrete symptoms of over-engineering).
In Java, however, being as verbose as it is, and having standard APIs that are designed for absolute control rather than fluent or convenient (read: one-liner) access, I often find myself writing little wrapper utilities for often-used JDK classes/methods.
Here's an example to elicit some feedback...
In languages like PHP (shock!), Python, etc. it's easy to construct a formatted string from some literal text plus parameters (one-liner, easy to code and read). In Java it's the String '+' operator or (since 1.5): String.format()
.
String.format()
, useful as it is, can still clutter code. So my first line of defense is to always import it statically, reducing it to just: format()
.
Having recently required lots of formatted strings in a project - and always wanting to minimise the cognitive clutter of code - I wrote a static method called $()
on my String util class (yes, $ is valid in a Java member name):
/**
* Shorthand/alias for Java's {@link String#format(String, Object...)}.
*/
public static String $(String format, Object...args) {
return format(format, args);
}
After static import in any client code (done automatically if using my custom Eclipse quick template), it reduces:
String id = String.format("%s^^^&%s&ISO", patient.getIdNumber(), OID__SA_ID_NUMBER_AUTHORITY);
to
String id = $("%s^^^&%s&ISO", patient.getIdNumber(), OID__SA_ID_NUMBER_AUTHORITY);
Not a massive saving, but it does add up if you have this scattered all over your code. Nooo! I hear you saying. What kind of a confusing method name is '$'!? It's not confusing if used in a small team that share an in-house util library. This kind of aliasing is rife in more dynamic languages, e.g. Javascript (think JQuery $(...), where everyone understands it).
Good idea, bad idea?
Aucun commentaire:
Enregistrer un commentaire