kouretinho
kouretinho

Reputation: 2260

Is the -Impl suffix a legitimate naming convention for a Hook method in Java?

I was going over some old code and found the following naming convention at a template method implementation.

// TEMPLATE METHOD
// Check condition and fail fast if condition is met.
// Otherwise call the hook method (to be implemented by subclasses).
@Override
public boolean accept(String text) {
    if (condition) {
        return false;
    }

    // call to the hook method. Each subclass implements its own logic
    return acceptImpl(text);
}

// HOOK METHOD
protected abstract boolean acceptImpl(String text);

I would expect the hook method to be named doAccept() or acceptHook() instead of acceptImpl().

Is the "-Impl" suffix used in practice for hook methods? or Is it a confusing naming practice?

Upvotes: 1

Views: 1549

Answers (1)

jaco0646
jaco0646

Reputation: 17066

First, note that the example here is not a hook method by the Gang of Four definition. On pages 327-328, the GoF Template Method pattern defines the types of operations which are called by template methods, including the following.

  • primitive operations (i.e., abstract operations);
  • hook operations, which provide default behavior that subclasses can extend if necessary.

Obviously this example demonstrates the former (abstract operation) rather than the latter (default operation). Immediately following the list of operations, the GoF emphasizes the difference between these two types.

It's important for template methods to specify which operations are hooks (may be overridden) and which are abstract operations (must be overridden).

This leads us to...

Naming conventions. You can identify the operations that should be overridden by adding a prefix to their names. For example... template method names with "Do-": "DoCreateDocument", "DoRead", and so forth.

Unfortunately, the GoF doesn't appear to provide a convention to distinguish between hook and abstract operations. The question regarding an "impl" suffix is clearly subjective; in my experience, "impl" is typically used in conjunction with the single-implementation anti-pattern.

Upvotes: 1

Related Questions