Is Dot

A ProtoPattern. Possibly an AntiPattern?

Summary: Refactor frequently used conditions into a UtilityClass? with a very short name, such as "Is". The class' externally used members return booleans. The class' externally used members' names do not start with "is". Optionally, make the class' externally used members "static".

Context: The language (such as Java) has many JavaProblems that result in errors and/or bloated code. Specifically:

Forces: NegativeExample?:
 String getLastCharacter(String arg) {
     if (arg == null) {
         return null;
     }
     if (arg.equals("")) {
         return "";
     }
     int len = arg.length();
     return arg.substring(len - 1, len);
 }
There are two guard clauses in this code to deal with the JavaProblems mentioned above. When dealing with Java Strings, it is common for the guard clauses to take up more space than the meat of the code. Also, both guard clauses deal with the same concept: what if the string is too short to have a last character? In one case, the string is null (and thus has zero characters). In the second case, it exists, and has zero characters.

Refactored Example:

 public class Is {
  static boolean nullOrEmpty(String arg) {
     if (arg == null) {
         return true;
     }
     if (arg.length() == 0) {
         return true;
     }
     return false;
  }
 }

String getLastCharacter(String arg) { if (Is.nullOrEmpty(arg)) { return arg; } int len = arg.length(); return arg.substring(len - 1, len); }
By using a class name of "Is" instead of "StringUtils?", the calling code is much more readable. For example, "if (Is.nullOrEmpty(arg))" versus "if (StringUtils?.isNullOrEmpty(arg))".

Because the class name is "Is", the externally called method names do not need to start with "is".

Because the externally called method name is static, there is no need for a variable declaration in the client code. This avoids code bloat.

Resulting Context:

Known Uses:

1. HexCalc? (a BaseSix ScientificCalculator? under development) -- JasperPaulsen

RelatedPattern?s: UncleBobsNamingConventions, HelperPattern



Discussion:

If the goal is to avoid CodeBloat, would this be an improvement?

  static boolean nullOrEmpty(String arg) {
     return arg==null || arg.isEmpty();
  }

If this successfully compiles, and the people reading/writing the code find this easier to read, yes. Otherwise, no.

In an actual program, the method definition appears just once, whereas it is used many times. A modest amount of CodeBloat is acceptable if it occurs OnceAndOnlyOnce.


See also: UncleBobsNamingConventions, JavaProblems, JavaLanguage, ProtoPattern, HelperPattern, ForeignMethod


EditText of this page (last edited September 30, 2012) or FindPage with title or text search