Saturday, February 20, 2016

Call the Chain of Responsibilty


Design patterns are pretty boring. Experimenting with design patterns? That's where the fun is!

While messing about with spreadsheet formatting objects (e.g. date, text, numeric), it occurred to me that there might be a Dartier (cooler) solution than what I am currently using:
abstract class CellFormatter {
  CellFormatter nextHandler;

  void processRequest(Event e) {
    if (handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler.processRequest(e);
  }

  // Subclasses handle requests as needed
  bool _handleRequest(Event e) => false;
  // ...
}
In this handler, I am both implementing and connecting the successors. The nextHandler property points to the next object in the chain. The processRequest() method is responsible for sending requests to that next object when the current object opts against handling the request (e.g. when a number formatter sees text in a cell).

There is nothing wrong with this approach, but I have a nagging dislike for the naming convention that I have here. One method is called processRequest() and the other is _handleRequest(). "Process" and "handle" both have similar meanings so it takes a little extra noodling here to understand what is happening. Since processRequest() is public, that is a good indication that it is the public interface to the chain. Less obvious is that processRequest() is responsible for connecting to the successor whereas the _handleRequest() is meant solely for subclasses to actually handle the request.

The main problem here is the dual nature of processRequest(). To the outside world, it is… processing the request, so it is well-named in that respect. Actually looking at the code, however, it serves the different purpose of linking successors. And naming _handleRequest() as I have only adds to the confusion. This is not horrible, but I can do better.

Perhaps renaming processRequest() as just process() will help. To the outside world, it retains a similar connotation. Inside the code, it seems more distinct from _handleRequest(). Or maybe…

I can rename it as call().

The beautiful thing about a method named call() in Dart is that automatically makes the current class into a function. That means that I can continue sending the request to the chain successor as with nextHandler.call(e) or I can treat nextHandler as a function itself, nextHandler(e):
abstract class CellFormatter {
  CellFormatter nextHandler;

  void call(Event e) {
    if (_handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler(e);
  }
  // ...
}
And, since the call() happens to have the correct signature for event listeners, I can supply the first object in the chain directly to the on-change listener:
  var textFormat = new TextFormatter();
  var dateFormat = new DateFormatter(textFormat);
  var numberFormat = new NumberFormatter(dateFormat);

  container.onChange.listen(numberFormat);
That reads much better—and it wasn't horrible to begin with! When the container sees a change event, it number formats the appropriate cell. The class code is similarly clear: when called, it either handles the request or calls the next successor. Wonderful!

I had thought about moving on from last night's "good enough" chain of responsibility. I am certainly glad I opted to linger a bit longer, this was a nice win. I do wonder if this is the gods' way of telling me to linger more often. Or maybe to call() more often. I'm sure one of those is the moral of this story.

Play with the code on DartPad: https://dartpad.dartlang.org/f5bbc86a28002987741c.


Day #101

36 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. hotmail.com brand continues to be hampered by that history in the minds of many users.

    Here’s a comparison of the Hotmail look compared to the new Outlook.com design brand continues to be hampered by that history in the minds of many users.

    Here’s a comparison of the Hotmail look compared to the new Outlook.com design

    ReplyDelete
  3. facebook.com today unveiled its vision for the future of work: a virtual reality experience called Horizon Workrooms that uses avatars and VR headsets to replicate in-person collaboration.

    The tech giant is hoping to ride pandemic-driven tailwinds that have sparked remote work and adoption of VR, particularly for Facebook’s Oculus subsidiary.

    Horizon Workrooms works both across virtual reality and the web, and uses features such as digital whiteboards, hand tracking, spatial audio, and more to help colleagues work together, even if they are physically apart. Other companies including Microsoft have unveiled similar experiences recently.

    ReplyDelete
  4. It's both a blessing and a curse that I not only fully understood aol mail what was being said but also remembered my father acting in a similar fashion when I was a kid.

    ReplyDelete
  5. Even though I mostly use gmail.com for work-related correspondence, I have kept my Yahoo account from the middle of the millennium since I never found a method to completely eliminate spam from it.

    ReplyDelete
  6. hey guys share information related to e shram card

    ReplyDelete
  7. The Microsoft msn.com mobile app provides access to all of Outlook's advanced capabilities

    ReplyDelete
  8. facebook.com Any hot take that News Corp, Yahoo or Daily Mail in Australia comes up with is going to be trash.


    ReplyDelete
  9. I, too, use hotmail.com , and in recent weeks, I've been inundated with the most bizarre and puzzling spam imaginable.

    ReplyDelete
  10. What gives with yahoo mail not recognising my email all of a sudden?

    ReplyDelete
  11. Replies
    1. David, you can check my blog on gmail sign in as well. Thank you.

      Delete
  12. The color palette you've chosen is visually appealing and harmonizes perfectly with your brand image. hotmail sign up

    ReplyDelete
  13. Fantastic blog! Your knowledge and writing style are truly commendable. Speaking of email services, have you tried Hotmail? It's a reliable and user-friendly platform. Check it out at hotmail.com and keep up the excellent content!

    ReplyDelete
  14. It is an unquestionable masterpiece of blogging genius! hotmail

    ReplyDelete
  15. Get ready to set out on a remarkable journey that will capture your attention, stoke your imagination, and uplift your spirit. hotmail

    ReplyDelete
  16. Wonderful blog! Your writing style and depth of knowledge are absolutely admirable. outlook

    ReplyDelete
  17. Wonderful blog! Your writing abilities and level of understanding are excellent. whatsapp web

    ReplyDelete
  18. Dive into the world of the Chain of Responsibility pattern and witness how it streamlines your application's flow, creating a robust and maintainable codebase. 🔄🔗🚀 gmail

    ReplyDelete
  19. Wonderful blog! Your writing abilities and level of understanding are excellent. In relation to email services, You may want to try Gmail. It is a dependable platform with simple navigation. Look it up at gmail

    ReplyDelete
  20. Your blog is a never-ending inspiration. I'm appreciative of how it has improved my life.
    hotmail

    ReplyDelete
  21. It's impressive how much study you done for this topic.
    amazing action
    chase offers

    ReplyDelete
  22. I am enjoying free version of Hotmail want to tell you all read the blog of Hotmail and enjoy free Hotmail version.

    ReplyDelete
  23. Bedava okey oynamak için doğru yer olan klasik okey oyna ile klasik okey, renkli okey, esli okey oynamak çok pratik ve hızlı. Sen de gel ve okey oynamanın tadını çıkart.
    Koz maça ve ihaleli batak gibi bir çok batak oyunu türünü barındıran canlı batak salonlarımızda hem online batak oyna hem de sohbet et.
    Güzel görünümü ve sorunsuz işleyişi ile tavla salonlarımızda klasik tavla oyna tavla kurallarına bağlı kalınarak açtığımız tavla oyunumuza sen de davetlisin.

    ReplyDelete
  24. Your blog is a heavenly observatory of knowledge. Your posts are like looking at the stars through the telescope of your words, revealing constellations of insight. Truly an astronomical experience!
    hotmail

    ReplyDelete
  25. Visited your blog and your recent post is a real intellectual treat. It's like a well-baked idea, rich in flavor and depth. Ready for more servings on your blog menu!

    ReplyDelete
  26. Dropped on your blog and found your post to be a real intellectual concert. It's like attending a symphony of ideas. Can't wait for more great performances on your blog!
    hotmail login

    ReplyDelete
  27. facebook login says it is moving beyond 2D screens toward “immersive experiences like augmented and virtual reality to help build the next evolution in social technology.”

    ReplyDelete