46

Nominalized Adjectives as Names for Decorators

 5 years ago
source link: https://www.tuicool.com/articles/hit/qie67rF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

There is a strong tendency among Java and C# programmers to prefix or suffix their extended types, such as naming a “smart” View as SmartView or a Work that is “delegated” as DelegatingWork . In this post, I will focus on decorators and how this widespread naming scheme reduces readability and adds no value to the code’s context. I think it’s time that we retire this needless naming redundancy.

fyyi2aB.jpg!web Milton, from Office Space

Composable decorators are small, highly cohesive objects that work off of another instance of their same type and, thus, are unable to function on their own. You can think of decorators as adjectives .

final Collection<Product> products = new FilteredCollection<>(
      Product::active,
      new MappedCollection<>(
          Subscription::product,
          new JoinedCollection<>(
              subscriptions1,
              subscriptions2,
              ...
          )
      )
  );

The problem with the traditional naming scheme is the needless repetition — we know from the outset that products is a Collection , but the code keeps hammering this point over and over again as we read on. This code is tedious to write, but, more importantly, it is tedious to read because of how the words are composed:

'Product’ is a filtered collection, a mapped collection, and a joined collection

Normal, everyday speech is not encumbered like this; nouns are routinely omitted when sufficient meaning can be extracted from the context. You don’t normally say The rich people and the poor people. You just say the rich and the poor . Nouns are omitted and adjectives are nominalized .

Following this same principle, let's make the code below read like this:

‘Product’ is a filtered, mapped, joined collection

It would have to look like this:

final Collection<Product> products = new Filtered<>(
      Product::active,
      new Mapped<>(
          Subscription::product,
          new Joined<>(
              subscriptions1,
              subscriptions2,
              ...
          )
      )
  );

I recommend that we make our code more terse by removing redundancy and allowing the code’s context to work in our favor for readability’s sake. For example, let’s use nominalized adjectives as names for our decorators.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK