tag:blogger.com,1999:blog-5811973523581265272024-03-16T11:53:12.616-07:00japh(r) by Chris StromJust Another Perl… Ruby… Just a HackerAnonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.comBlogger1929125tag:blogger.com,1999:blog-581197352358126527.post-64204178053033338082016-10-04T21:03:00.000-07:002016-10-04T21:12:46.339-07:00On Learning (Compendious Thunks)<div class=top-chain-links></div><br />
<i>Cross-posted on:</i> <a href="https://www.compendiousthunks.com/musings/on-learning/">Compendious Thunks</a><br />
<br />
My name is Chris. I am an Obsessive <a href="https://pragprog.com/book/tpp/the-pragmatic-programmer">Pragmatic Programmer</a> learner.<br />
<br />
OK, that might sound completely made up (it is), but bear with me...<br />
<br />
What makes one a pragmatically obsessive learner? Well two things:<br />
<ul class="fa-ul"><li><i class="fa fa-check"></i> Learn a new language (or library, network stack, framework) every year</li>
<li><i class="fa fa-check"></i> Blog about it <a href="http://japhr.blogspot.com/2012/04/366-or-how-i-tricked-myself-into-being.html">every single day</a> for weeks, months and even <a href="http://japhr.blogspot.com/2014/01/i-blogged-for-1000-days-straight.html">years</a> (<a href="http://japhr.blogspot.com/2014/03/karmajasmine-testing-of-polymer-ready.html">1,044 days in a row</a> is the record to beat)</li>
</ul><br />
<h2>Is that the absolute best way to learn?</h2><br />
Beats me.<br />
<br />
No, really. If I've learned anything while exploring learning, it is that each of us has to find what works best for us. And we can't shirk the responsibility of learning in the programming field. It will pass you by if you let up for a week.<br />
<br />
What I can say about Obsessive Pragmatic Learning is that it's pretty darn effective for me. How could you not pick up a thing or two after 1900 blog posts? And, yup, I'd <em>highly</em> recommend giving it a try -- even to the point of daily blogging. <a href="#fn1">*</a><br />
<br />
<h2>But...</h2><br />
Lately, I begin to feel like certain fundamentals are slipping. I'm pretty sure that <a href="https://pragprog.com/book/tpp/the-pragmatic-programmer">The Pragmatic Programmer</a> never meant for anyone to learn new stuff to the exclusion of all other learning. That's on me.<br />
<br />
So... I commit now to taking a step back. Instead of learning another new library, a new language, or the next hot framework, I will instead invest in fundamentals. I will start with design patterns, then move onto software principles. <i>Eventually</i> I will move back to the next hot framework because I really do think there is a balance to be found.<br />
<br />
And I hope <em>you</em> will join me at...<br />
<br />
<h3>Compendious Thunks!</h3><br />
Effective learning doesn't have to be obsessive (and, let's face it, it probably shouldn't be). It should be committed. Toward that goal, I think we can help each other.<br />
<br />
So I present to you <a href="https://www.compendiousthunks.com">Compendious Thunks</a>. And a bargain:<br />
<p style="padding-left: 30px;"><em>For you:</em> You watch 5 minute screencasts to level up. Roughly twice a week, watch an episode on a pattern or principle, play with interactive code, and... get better! You continue your growth from good to greatness.</p><p style="padding-left: 30px;"><em>For me:</em> I keep learning and recommit myself to my fundamentals. And get feedback from you where I still need to get better or improve my understanding.</p>I'm making much of this free as I hope it'll prove useful. And the rest I'm making as informative as humanly possible.<br />
<br />
Let's redouble a focus on programming fundamentals together!<br />
<br />
<hr><br />
<a name="fn1"></a>* Well, blog daily as long as you don't wind up doing it for 1,045 days straight. I'd very much like to hold onto that little record, thank you very much!<br />
<br />
<br />
<p class=bottom-chain-links><a href="">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <span style="color: #ccc">next›</span> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com621tag:blogger.com,1999:blog-581197352358126527.post-13896358911783421412016-02-21T19:45:00.001-08:002016-02-21T19:45:55.129-08:00A Facade for the Chain of Responsibility<div class=top-chain-links></div><br />
How much should the client know about the implementation of the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a>? I have reworked my spreadsheet cell formatting example to the point that I am quite satisfied with the code organization and how it responds:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOjwuDYpyyq3JN_O5gPR9uGKMKunNsD3wknKq5Ilv0s-RgdAt9h9ZMWtZULP4Yq_EOFb7vMvugqWR7xYxAhKg8eoYtr_QSjUBeEynV0zMxhElFx_GvmuUxVKHDaUhgWKUlzsWtKHKb05nb/s1600/03-no_text_formatter_after.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOjwuDYpyyq3JN_O5gPR9uGKMKunNsD3wknKq5Ilv0s-RgdAt9h9ZMWtZULP4Yq_EOFb7vMvugqWR7xYxAhKg8eoYtr_QSjUBeEynV0zMxhElFx_GvmuUxVKHDaUhgWKUlzsWtKHKb05nb/s640/03-no_text_formatter_after.png" width=570 /></a><br />
<br />
What leaves me slightly less satisfied is how much the <a href="http://dartlang.org">Dart</a> constructing code needs to know about the underlying implementation. Currently, I have it constructing the individual links in the chain <i>and</i> assigning those links:<pre class=prettyprint><code> var textFormat = new TextFormatter();
var dateFormat = new DateFormatter(textFormat);
var numberFormat = new NumberFormatter(dateFormat);</code></pre>I do not think it too horrible that the constructing code needs to know about the individual formatters—especially since it needs to know how to remove some of them in response to checkbox changes. What bugs me here is the same thing that has bugged me about other examples that I have built—the requirement that the constructing code know which link is first, which link has to be constructed first, and with which links each can and should link. <br />
<br />
That is, the text-formatter is the default link, so it needs to be last in the chain, but it has to be constructed first so that the second-to-last link can point to it. It is also not a good idea to remove the text-formatter (even though I have a checkbox in the UI) because it is the default cell formatter. Lastly, I find it awkward to tell the on-change listener to number-format cells when establishing the request handler:<pre class=prettyprint><code> container.onChange.listen(numberFormat);</code></pre>Even though it looks like I am asking for number formatting, I am really asking for something in the cell formatting chain to handle the request—number format just happens to be the first.<br />
<br />
In some (most?) implementations of the chain of responsibility this might actually be OK or desired organization. In this case, I think a facade wants to be in front of this complexity. So I define <code>CellFormatter</code> such that it declares the individual link components:<pre class=prettyprint>class CellFormatter {
var _numberFormat = new NumberFormatter();
var _dateFormat = new DateFormatter();
var _textFormat = new TextFormatter();
var first;
// ...
}</pre>I also declare a pointer to the first cell-formatting object so that I know where to start requests and can easily update it. In the constructor, I then establish the links in the chain and initially set <code>first</code>:<pre class=prettyprint>class CellFormatter {
// ...
CellFormatter() {
_numberFormat.nextHandler = _dateFormat;
_dateFormat.nextHandler = _textFormat;
first = _numberFormat;
}
// ...
}</pre>The <code>call()</code> method is then simple enough—I send the event request onto the <code>call()</code> method of the first link in the chain:<pre class=prettyprint>class CellFormatter {
// ...
void call(Event e) { first.call(e); }
// ...
}</pre>And, as mentioned, it is easy to manipulate the chain with methods like <code>ignore()</code> and <code>obey()</code>. A simple implementation for the number formatter could be:<pre class=prettyprint>class CellFormatter {
// ...
void ignore(String format) {
if (format == 'number') first = _dateFormat;
// ...
}
void obey(String format) {
if (format == 'number') first = _numberFormat;
// ...
}
}</pre>I feel more comfortable putting this knowledge in a class than I would in the main code. At least for this example, this seems like too much maintenance to mingle with other code.<br />
<br />
This does lead to some significant improvements in the main code. Obviously, it is much simpler to instantiate one object instead of three (and to omit the linking):<pre class=prettyprint><code> var cellFormat = new CellFormatter();</code></pre>I also get the benefit of an easier to read (and hence easier to maintain) assignment of the cell-formatter:<pre class=prettyprint><code> container.onChange.listen(cellFormat);</code></pre>This one-liner reads nicely and has low cognitive requirements: when the spreadsheet container sees changes, it cell-formats the source elements. No worry about the chain or the first element in the chain. Formatting is done by the cell formatter. Simple!<br />
<br />
(see last night's post for why <code>cellFormat</code> behave like a function here)<br />
<br />
The nicest win in this approach may be in the code that ignores/obeys formatters. Previously, when ignoring the number formatter, I had to obtain a subscription from the initial listener so that I could then cancel it and start a new listener with the second link in the chain:<pre class=prettyprint><code>
var subscription= container.onChange.listen(numberFormat);
query('#no-numbers').onChange.listen((e){
var el = e.target;
if (el.checked) {
subscription.cancel();
subscription = c.stream.listen(dateFormat);
}
// ...
});</code></pre>Now that <code>CellFormatter</code> internally maintains a reference to the <code>first</code> item in the chain, I no longer need to worry about the stream subscription sending to the wrong first element. The resulting code is mercifully free from subscription code, only obeying or ignoring links as requested:<pre class=prettyprint><code>
container.onChange.listen(cellFormat);
query('#no-numbers').onChange.listen((e){
var el = e.target;
if (el.checked) {
cellFormat.ignore('number');
}
// ...
});</code></pre>That seems a nice improvement.<br />
<br />
Overall, I am very happy with the improvement in the code as a results of this approach. I have yet to examine it in depth, but I believe this is likely a facade pattern as it hides some of the underlying complexity of the chain of responsibility from the calling context. Regardless of what it is called, I very much like it!<br />
<br />
This seems a nice stopping point for my research into the chain of responsibility. Up next, who knows?<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/adf7e28a00eba10491e9">https://dartpad.dartlang.org/adf7e28a00eba10491e9</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #102</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/call-chain-of-responsibilty.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <span style="color: #ccc">next›</span> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com17tag:blogger.com,1999:blog-581197352358126527.post-56763056723518035142016-02-20T21:44:00.000-08:002016-02-21T19:51:39.452-08:00Call the Chain of Responsibilty<div class=top-chain-links></div><br />
Design patterns are pretty boring. Experimenting with design patterns? That's where the fun is!<br />
<br />
While messing about with spreadsheet formatting objects (e.g. date, text, numeric), it occurred to me that there might be a <a href="http://dartlang.org">Dartier</a> (cooler) solution than what I am currently using:<pre class=prettyprint>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;
// ...
}</pre>In this handler, I am both implementing and connecting the successors. The <code>nextHandler</code> property points to the next object in the chain. The <code>processRequest()</code> 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). <br />
<br />
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 <code>processRequest()</code> and the other is <code>_handleRequest()</code>. "Process" and "handle" both have similar meanings so it takes a little extra noodling here to understand what is happening. Since <code>processRequest()</code> is public, that is a good indication that it is the public interface to the chain. Less obvious is that <code>processRequest()</code> is responsible for connecting to the successor whereas the <code>_handleRequest()</code> is meant solely for subclasses to actually handle the request.<br />
<br />
The main problem here is the dual nature of <code>processRequest()</code>. 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 <code>_handleRequest()</code> as I have only adds to the confusion. This is not horrible, but I can do better.<br />
<br />
Perhaps renaming <code>processRequest()</code> as just <code>process()</code> will help. To the outside world, it retains a similar connotation. Inside the code, it seems more distinct from <code>_handleRequest()</code>. Or maybe…<br />
<br />
I can rename it as <code>call()</code>.<br />
<br />
The beautiful thing about a method named <code>call()</code> 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 <code>nextHandler.call(e)</code> or I can treat <code>nextHandler</code> as a function itself, <code>nextHandler(e)</code>:<pre class=prettyprint>abstract class CellFormatter {
CellFormatter nextHandler;
void call(Event e) {
if (_handleRequest(e)) return;
if (nextHandler == null) return;
nextHandler(e);
}
// ...
}</pre>And, since the <code>call()</code> happens to have the correct signature for event listeners, I can supply the first object in the chain directly to the on-change listener:<pre class=prettyprint><code> var textFormat = new TextFormatter();
var dateFormat = new DateFormatter(textFormat);
var numberFormat = new NumberFormatter(dateFormat);
container.onChange.listen(numberFormat);</code></pre><i>That</i> 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!<br />
<br />
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 <code>call()</code> more often. I'm sure one of those is the moral of this story.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/f5bbc86a28002987741c">https://dartpad.dartlang.org/f5bbc86a28002987741c</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #101</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/consequences-of-chain-of-responsibility.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/a-facade-for-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com36tag:blogger.com,1999:blog-581197352358126527.post-23605908483829276952016-02-19T21:42:00.000-08:002016-02-20T21:46:28.818-08:00Consequences of the Chain of Responsibility<div class=top-chain-links></div><br />
Before wrapping up my initial research on the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a>, I take one last look at the consequences of code that follows it. In particular, I would like to touch on configuration and maintainability tonight.<br />
<br />
The example that I currently favor for illustrating the pattern is a set of cell formatting objects for a spreadsheet application:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgs0NpZbOUrPDCLIn96WgeHHAtVxqlaxl7Cjtb-EJW0ZDzdokk0vGNd_GhuDwfH9RRmiyj5CkQ0niD-GhqsAI9AnnJcowZdcixiaBeu3lTJ1XFkZJlm1WNxKbukrDyoU6TO_fMJZqF10CJ0/s1600/01-format_chain.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgs0NpZbOUrPDCLIn96WgeHHAtVxqlaxl7Cjtb-EJW0ZDzdokk0vGNd_GhuDwfH9RRmiyj5CkQ0niD-GhqsAI9AnnJcowZdcixiaBeu3lTJ1XFkZJlm1WNxKbukrDyoU6TO_fMJZqF10CJ0/s640/01-format_chain.png" width=570 /></a><br />
<br />
To auto-format the cells, each formatting object in the chain is given an opportunity to claim responsibility for the content. In this example, a cell with all numbers is converted to a double with two digits after the decimal, a date is converted to ISO 8601 format, and everything else defaults to text.<br />
<br />
To test configuration, I add some checkboxes to disable some of the formatters:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjICEAx2ppoIN4EBX0hccklSkPYH53dMt5B9WLMp66zf_8ZW8DPZ92-GLx946ZfW2C3p5eOR-uuxqGTqqa4YZK6eskbqiHFZi95xomeSZD53iAc1qeFyJO8HQ6_uAnRSZfHRyip7N6AtA1z/s1600/02-no_text_formatter_before.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjICEAx2ppoIN4EBX0hccklSkPYH53dMt5B9WLMp66zf_8ZW8DPZ92-GLx946ZfW2C3p5eOR-uuxqGTqqa4YZK6eskbqiHFZi95xomeSZD53iAc1qeFyJO8HQ6_uAnRSZfHRyip7N6AtA1z/s640/02-no_text_formatter_before.png" width=570 /></a><br />
<br />
The main takeaway from this is that it is possible to easily change the chain of responsibility at runtime. The <a href="http://dartlang.org">Dart</a> listener for the no-text formatting checkbox might look like:<pre class=prettyprint><code> query('#no-text').onChange.listen((e){
var el = e.target;
if (el.checked) {
date.nextHandler = null;
}
else {
date.nextHandler = text;
}
});</code></pre>The <code>date</code> formatter normally points to the text handler. That is, if the date formatter thinks the current input field is <i>not</i> a date, then it forwards the request onto the text formatter. By ticking this checkbox, the date formatter now thinks that there is no next handler.<br />
<br />
Thanks to last night's <code>CellFormatter</code> base class, this just works:<pre class=prettyprint>abstract class CellFormatter {
CellFormatter nextHandler;
void processRequest(Event e) {
if (!isCell(e)) return;
if (handleRequest(e)) return;
if (nextHandler == null) return;
nextHandler.processRequest(e);
}
// ...
}</pre>With the checkbox ticked, the date formatter no longer has a <code>nextHandler</code> so the date formatter simply does nothing. The result in the UI is that a cell that was previously a numeric and was right-aligned retains the alignment because there is no longer a text formatter to reset it:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHSpxEboX_0tjd5vCWvq5AJolOFflSLQVlukSel93_RQoXUViHFJSFfo9fBeLptBdDq4L1F8kSwuQwjFAeETmo8TsjxgECqHtQEVNGcQGIiM85mQ7J3Dq4nphJx1nOqIVa6rGdV0ajhfe3/s1600/03-no_text_formatter_after.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHSpxEboX_0tjd5vCWvq5AJolOFflSLQVlukSel93_RQoXUViHFJSFfo9fBeLptBdDq4L1F8kSwuQwjFAeETmo8TsjxgECqHtQEVNGcQGIiM85mQ7J3Dq4nphJx1nOqIVa6rGdV0ajhfe3/s640/03-no_text_formatter_after.png" width=570 /></a><br />
<br />
This illustrates another important aspect of the chain of responsibility. It is best to ensure that requests do not just "fall off" the end of the chain like this. Ideally, I ought to have a default handler at the end then resets all styles.<br />
<br />
One last thing that I would like to touch on before calling it a day is how robust the pattern is in the face of change. Currently, the first formatter in the chain processes event requests when changes are seen in cells:<pre class=prettyprint><code> container.onChange.listen(number.processRequest);</code></pre>What if I also wanted to apply changes when clicks are seen inside cells? Well, aside from Dart's lack of an easy means to merge event streams, this is fairly easy to support.<br />
<br />
I create a <code>StreamController</code> object and add events to it whenever there are clicks or changes:<pre class=prettyprint><code> var c = new StreamController();
container.onChange.listen(c.add);
container.onClick.listen(c.add);</code></pre>Then, I hand the first formatter in the chain to this combo-stream:<pre class=prettyprint><code> c.stream.listen(number.processRequest);</code></pre>And that's all there is to it. Now I can force formatting by tabbing to another cell or, if I am feeling impatient, I can click on a cell to format its contents.<br />
<br />
Nice! That may finish my exploration of the chain of responsibility pattern in Dart (though there could be one more Darty trick to try). I do think this spreadsheet cell example will serve nicely in <a href="http://designpatternsindart.com/">Design Patterns in Dart</a>. The code is fairly simple, yet still feels like a real example, which is pretty close to ideal. Plus, it serves well when discussing some of the consequences of the pattern!<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/08105c648b253f64a47d">https://dartpad.dartlang.org/08105c648b253f64a47d</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #100</span> <br />
<br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/delegated-events-chain-of-responsibility.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/call-chain-of-responsibilty.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com7tag:blogger.com,1999:blog-581197352358126527.post-29967577130708622822016-02-18T23:31:00.000-08:002016-02-19T21:44:07.196-08:00Delegated Events Chain of Responsibility<div class=top-chain-links></div><br />
I came up with a simple DOM-based example of the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a> last night. That might serve as an simple introduction to the pattern on the modern web, but I would prefer something with a little more heft to support subsequent discussions. So tonight, I attempt to apply the pattern to cell formatting object.<br />
<br />
Given a bunch of cells in a table, I would like a series of objects to format input values correctly. Numbers should have 2 decimal places and be right-aligned. Dates should be iso8601 formatted and left aligned. Everything else should be treated as plain text and left aligned:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht4m0vM-pmNemDgv_wpYXGWjFRF9UDTyM4LHzs8xA-FI0pKUE2VJdJ2KdWN3S6ZU_xgRzIp04i28vvoioVO73z7mxBcCK6Rgg_4vFGEKFv5kC09vVtXFxZIm4TRd_IaphLbTNvSHpNeNXJ/s1600/01-format_chain.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht4m0vM-pmNemDgv_wpYXGWjFRF9UDTyM4LHzs8xA-FI0pKUE2VJdJ2KdWN3S6ZU_xgRzIp04i28vvoioVO73z7mxBcCK6Rgg_4vFGEKFv5kC09vVtXFxZIm4TRd_IaphLbTNvSHpNeNXJ/s640/01-format_chain.png" width=570 /></a><br />
<br />
The handler in this chain of responsibility implementation is going to be a listener for change events on the container:<pre class=prettyprint><code> container.onChange.listen(handler.processRequest);</code></pre>I do not want a separate listener for each cell—that could wind up being a very large number of cells and listeners. Instead, I use a <a href="http://api.jquery.com/on/#direct-and-delegated-events">delegated events</a> approach, listening on the container and filtering events based on the target.<br />
<br />
The handler in this example will be the <code>CellFormatter</code>. As with any chain of responsibility implementation, the first thing that it needs is a way to specify the next link in the chain. In this case, the next handler:<pre class=prettyprint>abstract class CellFormatter {
CellFormatter nextHandler;
// ...
}</pre>Next, I need to process events:<pre class=prettyprint>abstract class CellFormatter {
// ...
void processRequest(Event e) {
if (!isCell(e)) return;
if (handleRequest(e)) return;
if (nextHandler == null) return;
nextHandler.processRequest(e);
}
bool handleRequest(Event e) => false;
// ...
}</pre>First, I filter on cells (text input fields). Then I try to handle the current request. The default implementation here is for <code>handleRequest</code> to not handle the request, which it signals by returning false. It will be the job of the concrete subclasses to properly handle requests. If the request is not handled, then the request sent to the next object in the chain, if defined.<br />
<br />
With that, I am ready to process different formatting, like <code>NumberFormatter</code>:<pre class=prettyprint>class NumberFormatter extends CellFormatter {
bool handleRequest(Event e) {
var input = e.target;
RegExp exp = new RegExp(r"^\s*[\d\.]+\s*$");
if (!exp.hasMatch(input.value)) return false;
var val = double.parse(input.value);
input.value = val.toStringAsFixed(2);
input.style.textAlign = 'right';
return true;
}
}</pre>If the current change event targets an input that does not match the numeric regular expression, <code>handleRequest()</code> returns <code>false</code> and the event is sent along to the next formatter object in the chain. If it does point to a numeric input element, the value is parsed and formatted with two digits after the decimal point. The text alignment of the input element is set appropriately for a numeric field. And that's it.<br />
<br />
Other formatters follow similar approaches until the last item in the chain, the default text formatter. This formatter applies no formatting to the value, but ensures the left alignment of the field:<pre class=prettyprint>class TextFormatter extends CellFormatter {
bool handleRequest(Event e) {
var input = e.target;
input.style.textAlign = 'left';
return true;
}
}</pre>Armed with my formatters, I can create them in client code:<pre class=prettyprint><code> var number = new NumberFormatter();
var date = new DateFormatter();
var text = new TextFormatter();</code></pre>Then, I establish the successor chain:<pre class=prettyprint><code> number.nextHandler = date;
date.nextHandler = text;</code></pre>That is all there is to it. Now when the event listener sends a request to the first item in the chain:<pre class=prettyprint><code> container.onChange.listen(number.processRequest);</code></pre>I know that one of the handlers will receive and process the event. I think that will be a reasonably accessible example for most readers. I may fiddle a bit more with the example tomorrow to be sure.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/21f67a92a0269a2aed6b">https://dartpad.dartlang.org/21f67a92a0269a2aed6b</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #99</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/a-dom-chain-of-responsibility.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/consequences-of-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com2tag:blogger.com,1999:blog-581197352358126527.post-51739800478481621152016-02-17T23:10:00.000-08:002016-02-18T23:32:37.258-08:00A DOM Chain of Responsibility<div class=top-chain-links></div><br />
A major theme of the forthcoming <a href="http://designpatternsindart.com/">Design Patterns in Dart</a> is that design patterns are more useful for describing how systems are already designed, not for designing systems in the first place. The implications and applicability of patterns then aid programmers to understand how systems can evolve, once patterns are recognized in them. <br />
<br />
With that in mind... consider a <code><div></code> with ID of "bottom" inside a <code><div></code> with ID of "middle" inside a <code><div></code> with ID of "top":<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidlDojN8L9A2vZnmDtZ2VAhggKJ4Y5pn12FLUT6iexyiimsEf64QMtVFAmd8TMSldTie0N-h8QiAN67398vXnNMphDKLCy8TUjmXkFJgBy7CLFYct1vdbpfqY-lU1bIjjaDJo5tTXIt9cw/s1600/01-chain_of_responsibility.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidlDojN8L9A2vZnmDtZ2VAhggKJ4Y5pn12FLUT6iexyiimsEf64QMtVFAmd8TMSldTie0N-h8QiAN67398vXnNMphDKLCy8TUjmXkFJgBy7CLFYct1vdbpfqY-lU1bIjjaDJo5tTXIt9cw/s640/01-chain_of_responsibility.png" width=570 /></a><br />
<br />
There are three <a href="http://dartlang.org">Dart</a> element objects:<pre class=prettyprint><code> var bottom = query('#bottom'),
middle = query('#middle'),
top = query('#top');</code></pre>If the bottom-most sees a request in the form of a click without modifier key, then it handles the request, preventing successors from seeing the request:<pre class=prettyprint><code> bottom.onClick.listen((e){
if (e.ctrlKey) return;
if (e.shiftKey) return;
bottom.style.border =
bottom.style.border.contains('green') ?
'' : '3px green dashed';
e.stopPropagation();
});</code></pre>But if modifier key (shift or control) is held down while clicking in the middle of the "bottom" <code><div></code>, the request passes along to the successor. The next element object in line here is the "middle" <ocde><div></code>. If the request is received by this object with the shift key depressed, it handles the request, preventing successor from seeing the request:<pre class=prettyprint><code> middle.onClick.listen((e){
if (e.ctrlKey) return;
middle.style.border =
middle.style.border.contains('blue') ?
'' : '3px blue dashed';
e.stopPropagation();
});</code></pre>Finally, if it is not the control key, but the shift key that is depressed while clicking the "bottom" element, the request passes through both the <code>bottom</code> handler and the <code>middle</code> handler—both of which opt not to handle the request. In this case, the request is finally handled by <code>top</code>:<pre class=prettyprint><code class="lang-dart"> top.onClick.listen((_){
top.style.border =
top.style.border.contains('orange') ?
'' : '3px orange dotted';
});</code></pre>So is this a chain of responsibility pattern? Of course! There are concrete handler objects all of the same type. They all declare the same method to process a request object. The method may be in the form of an event listener instead of a pure method, but the overall intent and structure is the same. This is a chain of responsibility—and one that just about every web developer implemented at some point without thinking about the pattern.<br />
<br />
And the implications and applicability? Well, that's a tale for another day.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/12bf7fa9c76c6d16fe5f">https://dartpad.dartlang.org/12bf7fa9c76c6d16fe5f</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #98</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/in-which-i-take-things-one-step-too-far.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/delegated-events-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-43147462303123434582016-02-16T23:05:00.000-08:002016-02-17T23:12:17.815-08:00In Which I Take Things One Step Too Far...<div class=top-chain-links></div><br />
So the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a> in <a href="http://dartlang.org">Dart</a>… I've explored it with <code>noSuchMethod()</code>. I've explored it with mixins. But I have yet to explore it with <code>noSuchMethod()</code> in mixins.<br />
<br />
Things are gonna get a little crazy tonight.<br />
<br />
I continue to work with the <code>_PurchasePower</code> mixin for employee-like classes. It describes the ability of an employee to make purchasing decisions. It sets the successor in the responsibility chain to point to the employee next on the corporate ladder:<pre class=prettyprint>abstract class _PurchasePower {
get successor => reportsTo;
// ...
}</pre>In this case, it simply delegates to the <code>reportsTo</code> property of <code>Employee</code>—the receiver of the mixin. <br />
<br />
The <code>_PurchasePower</code> mixin completes the chain of responsibility pattern by declaring <code>processRequest()</code>. This method sends the request to the successor if the current class does not handle it, and <code>_processRequest()</code>, which performs the actual handling of the request:<pre class=prettyprint>abstract class _PurchasePower {
// ...
void processRequest(PurchaseRequest request) {
if (_processRequest(request)) return;
if (successor == null) return;
successor.processRequest(request);
}
bool _processRequest(_) => false;
}</pre>That works great when there is only one request to handle, but what if there are multiple requests to be handled (e.g. <code>processorName()</code> and <code>processRequest()</code>)?<br />
<br />
This is where it would be handy to be able to mixin <code>noSuchMethod()</code>. Instead of declaring <code>processRequest()</code> to possibly send the request to the successor, <code>noSuchMethod()</code> can do so. Except I hit a stumbling block right away here.<br />
<br />
First, I need to handle requests by converting <code>processRequest()</code> to <code>_processRequest()</code> and <code>processorName()</code> to <code>_processorName()</code>. Just prepend an underscore, right? Well, no.<br />
<br />
When I get the arguments inside <code>noSuchMethod</code>, I can figure out the method that was being invoked by checking <code>memberName</code>. From here, it should be a simple matter of interpolating noSuchMethod's <code>memberName</code> into a string:<pre class=prettyprint><code> noSuchMethod(args) {
var handlerMethod = "_${args.memberName}";
// ...
}</code></pre>The problem is that <code>memberName</code> is a <code>Symbol</code>, which gets converted to strings as "<code>Symbol('symbol_name_here')</code>. So the <code>handlerMethod</code> winds up being <code>_Symbol('_processRequest')</code>. Not at all what I want. <br />
<br />
I have two undesirable choices here—strip <code>Symbol('</code> and <code>')</code> from the resulting string or painstakingly lookup the string value. Neither is a good option, but the latter seems to be the most official way:<pre class=prettyprint><code> noSuchMethod(args) {
var handlerMethod = "_${MirrorSystem.getName(args.memberName)}";
// ...
}</code></pre>Yuck. And unfortunately, I am not done with the yuck. I cannot invoke methods with strings, so I have to convert that back to a <code>Symbol</code>:<pre class=prettyprint><code> noSuchMethod(args) {
Symbol handlerMethod = new Symbol("_${MirrorSystem.getName(args.memberName)}");
// ...
}</code></pre>Even now, I am not done with the yuck. And this next yuckiness takes me a while to track down.<br />
<br />
It turns out that you cannot use the <code>Symbol</code> constructor to create a symbol that is private. Well, that is not 100% true, it lets me create a symbol, but I am not allowed to use it to invoked the private method. Making this situation even more annoying is that I can invoke <code>_processRequest()</code> with a symbol literal: <code>#_processRequest</code>. But if I dynamically try to create that symbol, it silently fails to call the right method.<br />
<br />
Bummer. <br />
<br />
Even if I choose a different naming convention, I would not want the method that actually processes the request to be public. Only the method invoking the handler or sending the request to the successor should be public. So I am left to either move handler code into <code>noSuchMethod()</code> to sit beside the successor code or I can give the handler method a weird name.<br />
<br />
I opt for the latter by prepending <code>xxx_</code> to the name:<pre class=prettyprint><code> noSuchMethod(args) {
Symbol handlerMethod = new Symbol("xxx_${MirrorSystem.getName(args.memberName)}");
// ...
}</code></pre>With this approach, I eventually get the code working, but... yuck.<br />
<br />
Even if this were back in the <code>Employee</code> class, I would still face the same limitation from the <code>Symbol</code> constructor. In other words, this seems like an ill-advised approach in current Dart. <br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/9f9ca7397d88f6cf7e54">https://dartpad.dartlang.org/9f9ca7397d88f6cf7e54</a>.</i><br />
<br />
<br />
<br />
<span style="color: #ccc">Day #97</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/how-much-mixin-chain-of-responsibility.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/a-dom-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com11tag:blogger.com,1999:blog-581197352358126527.post-2395231894817085302016-02-15T20:17:00.000-08:002016-02-16T23:07:52.683-08:00How Much Mixin for the Chain of Responsibility?<div class=top-chain-links></div><br />
After last night, I am again a fan of mixins in <a href="http://dartlang.org">Dart</a>. Mixins will not solve all problems, but they seem to solve several cases of <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a> nicely. I still have some follow-up questions, though. Up tonight how much of the chain can I get into the mixin class (and how much should I get in there)?<br />
<br />
The mixin in my current example adds purchasing power traits to an <code>Employee</code> class. Give that <code>Employee</code> supports a <code>reportsTo</code> property, the <code>_PurchasingPower</code> mixin delegates the chain of reponsibility's successor to this property:<pre class=prettyprint>abstract class _PurchasePower {
get successor => reportsTo;
// ...
}</pre>If the handler method in the chain is unable to process the current request, it will forward it along to this property. For a manager, this property might point to a director. For a director, it might point to a VP. <br />
<br />
As for handling the request, I currently do that via two methods:<pre class=prettyprint>abstract class _PurchasePower {
// ...
void processRequest(PurchaseRequest request) {
if (_processRequest(request)) return;
if (successor == null) return;
successor.processRequest(request);
}
bool _processRequest(_) => false;
}</pre>The <code>processRequest()</code> method is responsible for the successor chain while <code>_processRequest()</code> is responsible for attempting to handle the actual request. The default implementation in the mixin is for <code>_processRequest()</code> to <i>not</i> handle the request. In practice, concrete handler classes are expected to override this behavior.<br />
<br />
I appreciate the separation of focus between the two methods. It is nice that subclasses only have to worry about overriding the processing of the request instead of handling the request and managing the successor chain. When <code>_PurchasePower</code> is mixed into the <code>Manager</code> class, for instance, it is completely unaware of the chain of responsibility:<pre class=prettyprint>class Manager extends Employee with _PurchasePower {
final double _allowable = 10 * 1000.0;
bool _processRequest(PurchaseRequest request) {
if (request.amount > _allowable) return false;
print("Manager will approve $request.");
return true;
}
}</pre>It either handles the request or it does not. Simple. <br />
<br />
And yet, I note that the manner in which it handles the request is very similar to the manner in which the <code>Director</code> class handles the same request:<pre class=prettyprint>class Director extends Employee with _PurchasePower {
final double _allowable = 20 * 1000.0;
bool _processRequest(PurchaseRequest request) {
if (request.amount > _allowable) return false;
print("Director will approve $request");
return true;
}
}</pre>The only thing that varies in the implementation of <code>_processRequest()</code> is the name of the employee that potentially has the appropriate purchasing power. The <code>Employee</code> base class can figure this out from the runtime type of the object:<pre class=prettyprint>class Employee {
// ...
String get title => "${this.runtimeType}";
String toString() => title;
}
</pre>By defining the <code>toString()</code> method, I tell Dart how to interpolate this object into any string. Making use of that in the <code>_PurchasePower</code> mixin, I can declare a common <code>_processRequest()</code> handler method as:<pre class=prettyprint>abstract class _PurchasePower {
final double _allowable = 0.0;
// ...
bool _processRequest(PurchaseRequest request) {
if (request.amount > _allowable) return false;
print("$this will approve $request.");
return true;
}
}</pre>My <code>_PurchasePower</code> chain of responsibility mixin is getting crowded now. That said, the payoff is pretty nice. The employee subclasses with purchasing power now only need to declare the maximum allowed amount that they can handle:<pre class=prettyprint>class Manager extends Employee with _PurchasePower {
final double _allowable = 10 * 1000.0;
}
class Director extends Employee with _PurchasePower {
final double _allowable = 20 * 1000.0;
}
class VicePresident extends Employee with _PurchasePower {
final double _allowable = 40 * 1000.0;
}</pre>The mixin takes care of both processing the request and handling the successor chain. Even with this wonderfully compact implementation, I still retain the ability to override the default behavior as when the <code>President</code> always halts the chain:<pre class=prettyprint>class President extends Employee with _PurchasePower {
final double _allowable = 60 * 1000.0;
void processRequest(PurchaseRequest request) {
if (request.amount > _allowable) {
print("Your request for $request needs a board meeting!");
}
else {
print("President will approve $request");
}
}
}</pre>Since there is no successor beyond <code>President</code> I override the <code>processRequest()</code> method, handling the request directly.<br />
<br />
And yes, the chain of responsibility still works as desired:<pre class="prettyprint"><code class="language-html">$ ./bin/purchase.dart 2000
Manager will approve $2000.00 for General Purpose Usage.
$ ./bin/purchase.dart 12000
Director will approve $12000.00 for General Purpose Usage.
$ ./bin/purchase.dart 22000
VicePresident will approve $22000.00 for General Purpose Usage.
$ ./bin/purchase.dart 52000
President will approve $52000.00 for General Purpose Usage
$ ./bin/purchase.dart 82000
Your request for $82000.00 for General Purpose Usage needs a board meeting!</code></pre>So the answer to tonight's question would seem to be that, if the process handler is sufficiently generic, I can put everything into the chain mixin. The resulting concrete handler implementations are wonderfully succinct. There is barely any readability cost in the mixin class in this example thanks to Dart's <code>toString()</code> method. And I still retain the ability to override behavior in subclasses should that be required. Certainly this will not always be possible, but when there is sufficiently common process handling, this is a nice little code win.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/7cd84acd86da602301d5">https://dartpad.dartlang.org/7cd84acd86da602301d5</a>.</i> <br />
<br />
<br />
<span style="color: #ccc">Day #96</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/the-chain-of-responsibility-with-mixins.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/in-which-i-take-things-one-step-too-far.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com2tag:blogger.com,1999:blog-581197352358126527.post-25524842117919958312016-02-14T21:21:00.000-08:002016-02-15T20:20:17.786-08:00The Chain of Responsibility is Better with Mixins<div class=top-chain-links></div><br />
Having spent the entirety of last night's post lamenting the practice of using pattern-specific naming conventions, tonight I… use some pattern specific naming conventions. Well, maybe.<br />
<br />
Tonight, I try out mixins as a possible implementation for the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a>. I am unsure how it will work, but before trying it, it seems as though I will need to use patterns names in the mixin class. <br />
<br />
Something that I hope to explore in <a href="http://designpatternsindart.com/">Design Patterns in Dart</a> are <a href="http://dartlang.org">Dart</a> twists on design patterns. On classic OO patterns, that should involve mixins. That said, the main reason that I think mixins might be appropriate in this case is that the example that I adapted from the Wikipedia pages bothers me:<pre class=prettyprint><code> var manager = new ManagerPurchasePower();
var director = new DirectorPurchasePower();
var vp = new VicePresidentPurchasePower();
var president = new PresidentPurchasePower();</code></pre>I realize that this is example code, but I am hard-pressed to think that I would ever code up objects named "purchasing power." It seem much more likely that I would create <code>Manager</code>, <code>Director</code>, etc. classes with purchasing power traits. Hence, the thinking that mixins might be a good solution.<br />
<br />
A more real-world example, I think, would be an <code>Employee</code> class:<pre class=prettyprint>class Employee {
String firstName, lastName;
Employee reportsTo;
}</pre>The <code>Manager</code>, <code>Director</code> classes would then extend this class:<pre class=prettyprint>class Manager extends Employee {
// Manager specializations here...
}
class Director extends Employee {
// Director specializations here..
}
// ...</pre>In this scenario, a purchasing power chain of responsibility can be described with:<pre class=prettyprint>abstract class _PurchasePower {
get successor => reportsTo;
void processRequest(PurchaseRequest request) {
if (_processRequest(request)) return;
if (successor == null) return;
successor.processRequest(request);
}
bool _processRequest(_) => false;
}</pre>The successor in this chain is delegated to the <code>reportsTo</code> property of <code>Employee</code>. I could also have replaced subsequent references to <code>successor</code> with <code>reportsTo</code> and the code would have remained equally readable. I opt to stick with the pattern participant name (successor) as a default starting point. The domain naming convention from last night may very well prove more maintainable. Then again, since this mixin class exists solely to implement the chain of responsibility pattern, perhaps its domain is really the pattern itself. Unsure, I opt for the pattern name for now.<br />
<br />
In handle-request method, I first try to process the request with a subclass overrideable <code>_processRequest()</code> method. If the subclass' <code>_processRequest()</code> handles the request, it returns <code>true</code>, breaking the chain. If the subclass' implementation returns <code>false</code> (or the default implementation is invoked), then the next item in the chain is asked to handle the request.<br />
<br />
Armed with this <code>_PurchasePower</code> class, I can mix it into the subclasses of <code>Employee</code> with the <code>with</code> keyword:<pre class=prettyprint>class Manager extends Employee with _PurchasePower {
final double _allowable = 10 * 1000.0;
bool _processRequest(PurchaseRequest request) {
if (request.amount > _allowable) return false;
print("Manager will approve $request.");
return true;
}
}</pre>For the <code>Manager</code> class, the purchasing power traits are expressed by the overridden <code>_processRequest()</code> method. If the purchase request amount is more than $10,000, then the manager is unable to approve the request. The chain of responsibility is then passed back to the <code>processRequest()</code> method in the <code>_PurchasePower</code> mixin. In that case the <code>successor</code> / <code>reportsTo</code> is then asked to handle the request.<br />
<br />
The successor chain is expressed in the <code>Employee</code> class, though technically it is only in the <code>_PurchasePower</code> mixin that this relationship recognized as a chain. The actual relationship is established in client code (alternatively, last night's solution can establish the relationship in the classes):<pre class=prettyprint><code> var manager = new Manager();
var director = new Director();
manager.reportsTo = director;</code></pre>Although I remain unsure of some of the specifics like naming, I very much appreciate this mixins approach. In hindsight, the original class names (e.g. <code>ManagerPurchasingPower</code>) were probably screaming at me that a mixin was trying to escape from my code. Regardless, encapsulating the pattern entirely in a mixin class while limiting <code>Employee</code> subclasses to employee-specific responsibilities feels like clean, maintainable code. So this feels very much like a win.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/752e601e8768cb2f26e5">https://dartpad.dartlang.org/752e601e8768cb2f26e5</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #95</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/wacky-successor-chain-of-responsibility.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/how-much-mixin-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-70855554099647421572016-02-13T22:14:00.000-08:002016-02-14T21:35:55.508-08:00Wacky Successor Chain of Responsibility<div class=top-chain-links></div><br />
Let's talk about the successor chain in the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a>. In the purchasing power example that I have been using so far, the handler maintains responsibility for defining new links via a <code>successor</code> setter method:<pre class=prettyprint>abstract class PurchasePower {
PurchasePower _successor;
void set successor(PurchasePower successor) {
_successor = successor;
}
// ...
}</pre>This required client code to establish the links between instances:<pre class=prettyprint><code> var manager = new ManagerPurchasePower();
var director = new DirectorPurchasePower();
var vp = new VicePresidentPurchasePower();
var president = new PresidentPurchasePower();
manager.successor = director;
director.successor = vp;
vp.successor = president;</code></pre>I am OK with the approach here, but I am not a fan of the name <code>successor</code>. Really, in general, I am not a fan of using pattern names or participants in patterns—not even in examples. I much prefer domain specific names that are optionally annotated with pattern names.<br />
<br />
In the case of organization purchase power, the successor would be better expressed as reports to / direct reports relationships:<pre class=prettyprint>abstract class PurchasePower {
// Successor in the chain of responsibility
PurchasePower _reportsTo;
void set reportsTo(PurchasePower reportsTo) {
_reportsTo = reportsTo;
}
// ...
}</pre>Now when I look at the chain of responsibility being established, there is less mental translation between design pattern naming and the current domain:<pre class=prettyprint><code> var manager = new ManagerPurchasePower();
var director = new DirectorPurchasePower();
var vp = new VicePresidentPurchasePower();
var president = new PresidentPurchasePower();
manager.reportsTo = director;
director.reportsTo = vp;
vp.reportsTo = president;</code></pre>Everything about this feels more comfortable. Maybe there are people out there that look at a problem, tap their chin while considering things until finally shouting, "a-ha! the chain of responsibility will work here!" For me, the relationship comes first, after which I might come up with an approach to decide which member in the relationship needs to handle things. Then, if I am really paying attention, I might even think "ooh, that's the chain of responsibility!" <br />
<br />
Hopefully if I keep plugging away at these patterns, I will get to the point at which they are more recognizable in situations like this. But I seriously doubt I will ever get to the chin-tapping state. And I am unsure that I would ever want to. I think the code is more maintainable with the domain names instead of the pattern names (and really, no one ever liked classes named abstract factory factory). <br />
<br />
But I digress.<br />
<br />
Another possible approach to the chain of responsibility is to exploit either the data structure in use or the domain. There is not really a data structure in play with this example, but the domain certainly implies a hierarchy—a manager will always report to a director, who will always report to a VP, etc. I can exploit that to eliminate the explicit assignment of <code>reportsTo</code> properties.<br />
<br />
I start with a static mapping of runtime types pointing to the last used instance of that type:<pre class=prettyprint>abstract class PurchasePower {
static Map<Type, PurchasePower> _instances = {};
PurchasePower() {
_instances[this.runtimeType] = this;
}
// ...
}</pre>Any subclass of the <code>PurchasePower</code> handler will invoke the constructor here, caching the last instance of the give type. That is, when a <code>ManagerPurchasePower</code> instance is created, this superclass constructor will be called storing the instance index by the type.<br />
<br />
The <code>DirectorPurchasePower</code> constructor can then make use of this, finding the most recent <code>ManagerPurchasePower</code> and assigning this instance as the <code>reportsTo</code>:<pre class=prettyprint>class DirectorPurchasePower extends PurchasePower {
// ...
DirectorPurchasePower() : super() {
_directReport(ManagerPurchasePower);
}
// ...
}</pre>After setting the default successor chain like this in the VP and President purchase power classes, I no longer have to explicitly specify the chain of responsibility. I simply create the various instances, start with the lowest and see which claims responsibility along the way:<pre class=prettyprint><code> var manager = new ManagerPurchasePower();
var director = new DirectorPurchasePower();
var vp = new VicePresidentPurchasePower();
var president = new PresidentPurchasePower();
var req = new PurchaseRequest(25*1000, "General Purpose Usage");
manager.processRequest(req);</code></pre>This particular recent instance storage and lookup implementation feels a little forced. Explicitly setting the chain was not too horrible and this approach is non-trivial. Still, it was good to explore the successor chain in a little more depth.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/ec62b7918eebf6e7e130">https://dartpad.dartlang.org/ec62b7918eebf6e7e130</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #94</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/chain-of-responsibility-but-with.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/the-chain-of-responsibility-with-mixins.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-19433565617111216672016-02-12T23:03:00.000-08:002016-02-13T22:16:20.800-08:00Chain of Responsibility, but with noSuchMethod<div class=top-chain-links></div><br />
Most of the fun of the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a> is building the chain. One of the implementations suggested in the <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a> involves Smalltalk's <code>doesNotUnderstand</code>. In <a href="http://dartlang.org">Dart</a>, that means it is time for some <code>noSuchMethod()</code> fun.<br />
<br />
In the purchasing power example that I adapted from Wikipedia, the handler currently supports the chain with:<pre class=prettyprint>abstract class PurchasePower {
PurchasePower _successor;
void set successor(PurchasePower successor) {
_successor = successor;
}
void processRequest(PurchaseRequest request) {
if (_successor != null) {
_successor.processRequest(request);
}
}
}</pre>If a concrete handler sets the successor, then the <code>processRequest()</code> method in this handler base class will forward the request on to the next handler in the chain. <br />
<br />
For example, the manager-level purchasing power handler will handle requests for less than $10k:<pre class=prettyprint>class ManagerPurchasePower extends PurchasePower {
final double _allowable = 10 * 1000.0;
void processRequest(PurchaseRequest request) {
if (request.amount < _allowable) {
print("Manager will approve $request.");
return;
}
super.processRequest(request);
}
}</pre>
<p>If the request is for more, then the superclass implementation of <code>processRequest()</code> is invoked, passing the request along to the next object in the chain. The nice thing about this approach is that a subclass that does not want to handle a request can simply omit a declaration of <code>processRequest()</code>, allowing the superclass to forward the request on to the chain successor.</p><p>So what does <code>noSuchMethod()</code> buy me in this scenario? Not a ton, but it does yield a more generalized approach to handling requests. In the baseclass, I replace the previous <code>processRequest()</code> with:</p><pre class=prettyprint>import 'dart:mirrors' show reflect;
abstract class PurchasePower {
// ...
noSuchMethod(args) {
if (_successor == null) return;
reflect(_successor).delegate(args);
}
}</pre><p>If a concrete class does not define a method like <code>processRequest()</code> (or invokes it directly in the superclass), then the invocation winds up in <code>noSuchMethod()</code>. If there is no successor in the chain, then nothing is returned, terminating the chain. Otherwise, thanks to the magic of <code>delegate()</code>, the successor is reflected so that the method being invoked can be sent to the successor along with any arguments. </p><p>With that, when <code>processRequest()</code> in concrete handlers invokes the method of the same name in the superclass, <code>noSuchMethod()</code> kicks in, forwarding the request along to the successor. The behavior is exactly the same as with an explicit <code>processRequest()</code> in the superclass, only <code>noSuchMethod()</code> will work with any method, instead of a single method. </p><p>So, in the end, I don't know that this buys me much, except when multiple handlers are involved. Or when one simply wants to have fun with mirrors.</p><p><i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/894142038ed1185e8d4a">https://dartpad.dartlang.org/894142038ed1185e8d4a</a>.</i></p>
<span style="color: #ccc">Day #93</span>
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/the-chain-of-responsibility-pattern-in.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/wacky-successor-chain-of-responsibility.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-82075503585090722752016-02-11T21:41:00.000-08:002016-02-12T23:07:27.868-08:00The Chain of Responsibility Pattern in Dart<div class=top-chain-links></div><br />
How can anyone not love a pattern named <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility</a>? I mean c'mon, the name invokes all sorts of linked interaction between objects that somehow manage to cooperate on ownership for an action of some sort. It's the kind of thing that makes bureaucracy so awful, but there's a pattern in programming that makes it elegant. So what's not to love?<br />
<br />
I start my investigation of the pattern as I so often do, by copying the Java example on the Wikipedia page into lovely <a href="http://dartlang.org">Dart</a> code. The prime mover in the pattern—the interface used by the outside world—is the handler. It gets its name, as one might suspect, from its job to… handle a request (and then optionally forward the request on). The handler in the Wikipedia example describes purchasing power.<br />
<br />
In Dart, the purchasing power interface looks like:<pre class=prettyprint>abstract class PurchasePower {
PurchasePower _successor;
void set successor(PurchasePower successor) {
_successor = successor;
}
void processRequest(PurchaseRequest request);
}</pre>The "chain" portion of this pattern is handled by the <code>_successor</code> private variable. If this <code>PurchasePower</code> class does not want to handle the request, the <code>_successor</code> is specified as the next in the chain. The <code>processRequest()</code> method holds the responsibility for handling the request. It receives a purchase request and must decide to handle it or forward the request on to the <code>_successor</code>. <br />
<br />
The lowest level of purchasing power in the example is that of a lowly manager:<pre class=prettyprint>class ManagerPurchasePower extends PurchasePower {
final double _allowable = 10 * 1000;
void processRequest(PurchaseRequest request) {
if (request.amount < _allowable) {
print("Manager will approve $request.");
}
else if (_successor != null) {
_successor.processRequest(request);
}
}
}</pre>
<p>The upper limit that a manager can approve of is $10,000. If the request is for less than that, then the chain ends with the approval by the manager. If it is more than that, then the <code>_successor</code> is then asked to process the same request.</p><p>The object being processed by the pattern's handler is a purchase request:</p><pre class=prettyprint>class PurchaseRequest {
double amount;
String purpose;
PurchaseRequest(this.amount, this.purpose);
String toString() =>
"\$${amount.toStringAsFixed(2)} for $purpose";
}</pre><p>It requires a dollar amount and a description of the reason for the purchase. I provide a <code>toString()</code> method so that the entire object can be interpolated in a string (as it is when the manager approves the request).</p><p>That is the whole of the pattern. For it to be a true chain, I declare director, VP and presidential purchasing power. Anything that the president, who will be last in succession, cannot purchase needs board approval and not another successor:</p><pre class=prettyprint>class PresidentPurchasePower extends PurchasePower {
final double _allowable = 60 * 1000;
void processRequest(PurchaseRequest request) {
if (request.amount < _allowable) {
print("President will approve $request");
}
else {
print("Your request for $request needs a board meeting!");
}
}
}</pre>
In client code, I can create each of these purchasing power objects:<pre class=prettyprint><code> var manager = new ManagerPurchasePower();
var director = new DirectorPurchasePower();
var vp = new VicePresidentPurchasePower();
var president = new PresidentPurchasePower();</code></pre>Then I can specify the chain:<pre class=prettyprint><code> manager.successor = director;
director.successor = vp;
vp.successor = president;</code></pre>Lastly, I can parse the dollar amount being requested and start the chain on its merry path:<pre class=prettyprint><code> var amount = (args[0] == null) ?
1000 : double.parse(args[0]);
var req = new PurchaseRequest(amount, "General Purpose Usage");
manager.processRequest(req);</code></pre>With that, I can quickly determine who to bug for the new company automobiles (including my Tesla):<pre class=prettyprint>$ ./bin/purchase.dart 5000
Manager will approve $5000.00 for General Purpose Usage.
$ ./bin/purchase.dart 10000
Director will approve $10000.00 for General Purpose Usage
$ ./bin/purchase.dart 20000
Vice President will approve $20000.00 for General Purpose Usage
$ ./bin/purchase.dart 50000
President will approve $50000.00 for General Purpose Usage
$ ./bin/purchase.dart 75000
Your request for $75000.00 for General Purpose Usage needs a board meeting!</pre><p>That was a nice start to exploration of the chain of responsibility pattern. I am already looking forward to kicking the tires on this pattern a little more.</p><p><i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/818215777ae57169e6a1">https://dartpad.dartlang.org/818215777ae57169e6a1</a>.</i></p>
<p><span style="color: #ccc">Day #92</span> </p><p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/factory-method-pattern-and-polymer.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/chain-of-responsibility-but-with.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-556666449402598562016-02-10T23:40:00.001-08:002016-02-11T21:43:08.469-08:00Factory Method Pattern and Polymer Paper Elements<div class=top-chain-links></div><br />
I may regret this, but my web-based <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a> example lacked a "modern" touch. Well, that's not entirely true, it could add relatively new input elements like number, telephone, and week inputs to a form:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQx1AVW2M53SkMXgFmlNAZePFJCpzFRGFKiNV9d3iDLOeDSxVI7gqVgG7JF6IKTIH9z8G2EgFiwD8vFvKi7sO23hh9hLirgzYZk1OdSVqlFCilJM07LNIZVji2bZThl_KEg9L-GVoWYNZT/s1600/01-build_old_factories.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQx1AVW2M53SkMXgFmlNAZePFJCpzFRGFKiNV9d3iDLOeDSxVI7gqVgG7JF6IKTIH9z8G2EgFiwD8vFvKi7sO23hh9hLirgzYZk1OdSVqlFCilJM07LNIZVji2bZThl_KEg9L-GVoWYNZT/s640/01-build_old_factories.png" width=570 /></a><br />
<br />
But darn it, what about awesome <a href="http://www.polymer-project.org/docs/elements/paper-elements.html">Paper Elements</a>? Will a <code><paper-input></code> element serve as a product of the pattern? It sure would be neat if I could simply drop it into the pattern without many changes.<br />
<br />
But alas, it seems that some changes are going to be required. Even though it behaves like an input field, the <a href="https://www.dartdocs.org/documentation/paper_elements/0.7.1/paper_elements.paper_input/PaperInput-class.html">PaperInput</a> class implements <code>HtmlElement</code>, not <code>InputElement</code> like my <code>FormBuilder</code> class wants:<pre class=prettyprint>abstract class FormBuilder {
// ...
void addInput() {
var input = _labelFor(inputElement);
container.append(input);
}
InputElement get inputElement;
// ...
}</pre>The factory method in this example is the <code>inputElement</code> getter, which returns an <code>InputElement</code>. Because of the <code>PaperElement</code> inheritance, I have to change that to return the more general <code>HtmlElement</code>:<pre class=prettyprint>abstract class FormBuilder {
// ...
HtmlElement get inputElement;
// ...
}</pre>How many other changes am I going to have to make?<br />
<br />
Well, I certainly have to list <a href="http://www.polymer-project.org/">Polymer</a> as a dependency in my project's <code>pubspec.yaml</code>. To get <code><paper-input></code>, I need <code>paper_elements</code> as well:<pre class=prettyprint>name: factory_method_code
dependencies:
polymer: ">=0.15.1 <0.17.0"
paper_elements: ">=0.7.0 <0.8.0"
transformers:
- polymer:
entry_points:
- web/index.html</pre>
Next, I have to import the paper element into the containing page:<pre class=prettyprint><!doctype html>
<html lang="en">
<head>
<!-- ... -->
<link rel="import" href="packages/paper_elements/paper_input.html">
<script type="application/dart" src="input_factory.dart"></script>
</head>
<body><!-- ... --></body>
</html>
</pre>I have to do the same with the backing code in the <code>input_factory.dart</code> script:<pre class=prettyprint>import 'package:polymer/polymer.dart';
import 'package:paper_elements/paper_input.dart';
abstract class FormBuilder {
// ...
}
// Concrete factories here...</pre>The final Polymer-y thing that needs to happen is an <code>initPolymer()</code> call in my <code>main()</code> entry point, also in the <code>input_factory.dart</code> script:<pre class=prettyprint>main() async {
await initPolymer();
// Start up the factory code once Polymer is ready...
}</pre>That's it for the Polymer preliminaries. Now what needs to change in the pattern itself to accommodate <code>PaperInput</code>? Mercifully, not much. In the <code>RandomBuilder</code> class, which is a concrete factory implementation of the <code>FormBuilder</code>, I add a new random option (#5) for <code>PaperInput</code>:<pre class=prettyprint>class RandomBuilder extends FormBuilder {
RandomBuilder(el): super(el);
Element get inputElement {
var rand = new Random().nextInt(7);
if (rand == 0) return new WeekInputElement();
if (rand == 1) return new NumberInputElement();
if (rand == 2) return new TelephoneInputElement();
if (rand == 3) return new UrlInputElement();
if (rand == 4) return new TimeInputElement();
if (rand == 5) return new PaperInput();
return new TextInputElement();
}
}</pre>Unfortunately, I also have to make a change in the superclass. Previously, when all of the products were <code>InputElement</code> instances, I could count on them supporting the <code>type</code> property (e.g. telephone, number, time), which I could use as a default <code>text</code> label on the page:<pre class=prettyprint>abstract class FormBuilder {
// ...
_labelFor(el) {
var text = el.type;
var label = new LabelElement()
..appendText("$text: ")
..append(el);
return new ParagraphElement()..append(label);
}
}</pre>That will not work for <code>PaperInput</code>, which does not support the <code>type</code> property. If I had control of the product classes, I could force <code>PaperInput</code> to support <code>type</code>. Since that is not possible, I either have to create wrapper classes or, more easily, add an object type test for <code>InputElement</code>:<pre class=prettyprint>abstract class FormBuilder {
// ...
_labelFor(el) {
var text = (el is InputElement) ? el.type : el.toString();
// ...
}
}</pre><p>By itself, that one line is not too horrible. That said, I can imagine things going quickly off the rails here by adding a non-<code>InputElement</code> into the mix. For a limited use case like this example, however, it works.</p><p>In the end, it was fairly easy to get a <code>PaperInput</code> element added to the mix of my <code>InputElement</code> factory method. Most of the effort was the usual Polymer overhead. The resulting interface mismatch likely will not cause too much trouble in this case, but could get ugly quickly in other scenarios.</p>
<p><span style="color: #ccc">Day #91</span> </p><p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/a-nearly-modern-factory-method-pattern.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/the-chain-of-responsibility-pattern-in.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-56748799281166819242016-02-09T22:16:00.001-08:002016-02-10T23:43:25.751-08:00A Nearly Modern Factory Method Pattern<div class=top-chain-links></div><br />
I could make do with the examples of the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a> that I have been using. Still, I would prefer an example that touches the modern web a little closer. Or at least the web. So tonight I try my hand at a venerable, if simple, form builder.<br />
<br />
I am not going to worry too much about the details of adding different types of HTML form inputs at this point. To kick things off, I start by adding variations of text input fields to a container. So my <a href="http://dartlang.org">Dart</a> abstract creator class declares that it needs to be constructed with a container element:<pre class=prettyprint>abstract class FormBuilder {
Element container;
FormBuilder(this.container);
}</pre>Next, I declare an <code>addInput()</code> method that will append an input field to the container:<pre class=prettyprint>abstract class FormBuilder {
// ...
void addInput() {
var input = _labelFor(inputElement);
container.append(input);
}
// ...
}</pre>The <code>_labelFor()</code> helper method is unimportant in this discussion. It merely adds a text label to the input element. What is important here is the <code>inputElement</code> property. That is going to be the factory method in the factory method pattern. It lacks the usual trailing parentheses because it will be a getter method:<pre class=prettyprint>abstract class FormBuilder {
// ...
InputElement get inputElement;
// ...
}</pre>It lacks a method body because the definition of what <code>inputElement</code> does will have to come from subclasses.<br />
<br />
Putting these all together, I have a prototypical "creator" in the factory method pattern:<pre class=prettyprint>abstract class FormBuilder {
Element container;
FormBuilder(this.container);
void addInput() {
var input = _labelFor(inputElement);
container.append(input);
}
InputElement get inputElement;
// ...
}</pre>It declares a factory method, <code>inputElement</code>, and an operation that uses that factory, <code>addInput()</code>. The <code>creator</code> in the classic factory method pattern is an interface for concrete implementations. <br />
<br />
For a first pass at a concrete creator class, I declare a <code>RandomBuilder</code> class. As the name implies, the <code>inputElement</code> factory method randomly chooses from a selection of input element types:<pre class=prettyprint>import 'dart:math' show Random;
class RandomBuilder extends FormBuilder {
RandomBuilder(el): super(el);
InputElement get inputElement {
var rand = new Random().nextInt(6);
if (rand == 0) return new WeekInputElement();
if (rand == 1) return new NumberInputElement();
if (rand == 2) return new TelephoneInputElement();
if (rand == 3) return new UrlInputElement();
if (rand == 4) return new TimeInputElement();
return new TextInputElement();
}
}</pre>The other piece of the pattern is the "product." The product in this case the standard <code>InputElement</code> from <code>dart:html</code> — nobody ever said that the product had be a hand-coded class, after all. Given that, the concrete products are the various types of input elements that are randomly returned from the getter factory method.<br />
<br />
And there you have it: a simple, web implementation of the factory method pattern! <br />
<br />
I can use this in client code by creating a new form builder element as part of a button click handler:<pre class=prettyprint><code> var button = new ButtonElement()
..appendText('Build Input')
..onClick.listen((_){
new RandomBuilder(container).addInput();
});</code></pre>This might be a little too simplistic, but I rather like the example. It feels accessible for most web developers. It could also serve as a building block for further examples. I may continue to explore slightly more modern examples tomorrow, though other patterns beckon. Stay tuned!<br />
<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/ed63a78724e4a8605793">https://dartpad.dartlang.org/ed63a78724e4a8605793</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #90</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/silly-factories-in-factory-method.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/factory-method-pattern-and-polymer.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-39933827733990346912016-02-08T22:13:00.001-08:002016-02-09T22:18:17.584-08:00Silly Factories in the Factory Method Pattern<div class=top-chain-links></div><br />
Tonight, I look into using <a href="http://dartlang.org">Dart</a> factory constructors in the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a>. Since they both have the word "factory" in them they can probably be used together, right? Well, probably not, but I can no longer resist pairing the two.<br />
<br />
Normal generative constructors in Dart behave like constructors in just about any object-oriented language. They create a new instance of the current class, optionally setting some instance variables. Factory constructors, on the other hand, are responsible for building and initializing the object being created. This means that factory constructors can return anything—not limited to the current class.<br />
<br />
Take, for instance, a <code>Person</code> class:<pre class=prettyprint>class Person {
int age;
Person(this.age);
}</pre>When a new <code>Person</code> is instantiated with <code>new Person(21)</code>, the generative constructor creates an instance of <code>Person</code> and assigns the <code>age</code> instance variable to <code>21</code>. Easy peasy.<br />
<br />
Now I introduce two subclasses (both still using plain-old generative constructors):<pre class=prettyprint>class Child extends Person {
Child([age=12]) : super(age);
}
class Adult extends Person {
Adult([age=18]) : super(age);
}</pre>There is nothing special here. Both classes default to an age appropriate for the type of person being created. What these allow me to do is declare a (named) factory constructor back in <code>Person</code>:<pre class=prettyprint>class Person {
factory Person.random() =>
new Random().nextBool() ? new Child() : new Adult();
}</pre>This <code>Person.random()</code> constructor creates and returns full-blown object. It cannot rely on the language to generate the object, instead it has to do all of the work itself. With that, I can randomly generate children and adults from the <code>Person</code> superclass:<pre class=prettyprint><code> new Person.random();
// => Instance of 'Adult'
new Person.random();
// => Instance of 'Adult'
new Person.random();
// => Instance of 'Child'</code></pre>What is really weird about these factory constructors is that they do not have to return an instance of the current class or a subclass. Instead, I can declare a <code>Person</code> constructor that returns a string:<pre class=prettyprint>class Person {
// ...
factory Person.string() { return "A person"; }
}</pre>And that works perfectly fine:<pre class=prettyprint><code> new Person.random();
// => Instance of 'Adult'
new Person.random();
// => Instance of 'Adult'
new Person.random();
// => Instance of 'Child'
new Person.string();
// => 'A person'</code></pre>To be completely honest, that is not "perfectly fine." The Dart type analyzer does complain:<pre class=prettyprint>[warning] The return type 'String' is not a 'Person', as defined by the method 'string'</pre>But despite the warning, the code compiles and runs (see <a href="https://dartpad.dartlang.org/a9d6e9a9b654300bf696">this DartPad</a>).<br />
<br />
Anyhow, back to the task at hand. How can I use these factory constructors in the factory method pattern? Well, I probably cannot since one is a constructor and the other a method, but let's do it anyway. I currently have a <code>GameFactory</code> class that creates a bunch of different board game products:<pre class=prettyprint>class GameFactory {
// ...
// The factory method
createBoardGame([String game]) {
if (game == 'Checkers') return new CheckersGame();
if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
return new ChessGame();
}
}</pre>Instead of a factory method, I can use a factory constructor:<pre class=prettyprint>class GameFactory {
// ...
factory GameFactory.createBoardGame([String game]) {
if (game == 'Checkers') return new CheckersGame();
if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
return new ChessGame();
}
}
</pre>Since <code>BoardGame</code> is not a subclass of <code>GameFactory</code>, the Dart type analyzer complains something fierce about this. But it compiles and runs anyway:<pre class=prettyprint><code> new GameFactory.createBoardGame('Checkers').play();
new GameFactory.createBoardGame('Thermo Nuclear War').play();
new GameFactory.createBoardGame().play();</code></pre>So what does this buy me? Like war, absolutely nothing.<br />
<br />
In fact, I lose the ability to associate the factory constructor board games with the rest of the series. Each of those three board games are completely independent of the game factory series, which can no longer keep a reference to each for a final score:<pre class=prettyprint><code> var series = new GameFactory('Professor Falken', 'Joshua');
series.start();
new GameFactory.createBoardGame('Checkers').play();
new GameFactory.createBoardGame('Thermo Nuclear War').play();
new GameFactory.createBoardGame().play();</code></pre>So in the end, factory constructors and the factory method pattern are amusing together, but I can see no practical benefit. It was still totally worth messing around with them though!<br />
<br />
<i>Play with the amusing code on DartPad: <a href="https://dartpad.dartlang.org/4a59d56472d11cde9354">https://dartpad.dartlang.org/4a59d56472d11cde9354</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #89</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/factory-games-with-mirrors.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/a-nearly-modern-factory-method-pattern.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com3tag:blogger.com,1999:blog-581197352358126527.post-75727305046853798722016-02-07T21:55:00.000-08:002016-02-08T22:16:09.315-08:00Factory Games with Mirrors<div class=top-chain-links></div><br />
Up tonight I finally carry through on my threat to apply mirrors to the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a> in <a href="http://dartlang.org">Dart</a>. I am unsure if my beloved mirrors can have their usual improving effect (in my eyes at least), but I am always happy to have an excuse to play with reflection and mirrors. <br />
<br />
Tonight's excuse comes in the form of the language specific implementations mentioned in the <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a>. They mentioned that factory methods in Smalltalk often return the class to be created instead of an object. Aside from having to import the <code>dart:mirrors</code> library, it is not much more difficult to do the same thing in Dart.<br />
<br />
The prime mover in the factory method pattern is the creator class. In the "game factory" example with which I have been toying, the <code>GameFactory</code> class creates a series of games between two players, then allows them chose any number of board games to play. The returns-a-class version might look something like:<pre class=prettyprint>// Creator
class GameFactory {
String playerOne, playerTwo;
GameFactory(this.playerOne, this.playerTwo);
// ...
// The factory method
Type boardGameClass([String game]) {
if (game == 'Checkers') return CheckersGame;
if (game == 'Thermo Nuclear War') return ThermoNuclearWar;
return ChessGame;
}
}</pre>That will force the client code to reflect on the classes, which is an obnoxious thing to ask of client code. So instead, I import <code>dart:mirrors</code> and return a class mirror from the <code>boardGameClass()</code> method:<pre class=prettyprint>import 'dart:mirrors' show reflectClass, ClassMirror;
// Creator
class GameFactory {
// ...
ClassMirror boardGameClass([String game]) {
if (game == 'Checkers') return reflectClass(CheckersGame);
if (game == 'Thermo Nuclear War') return reflectClass(ThermoNuclearWar);
return reflectClass(ChessGame);
}
}</pre>Let's take a look at the resulting client code next. When it worked directly with objects, the client code looked like:<pre class=prettyprint>main() {
var series = new GameFactory('Professor Falken', 'Joshua');
series.start();
var game;
game = series.createBoardGame('Checkers');
game.play();
game = series.createBoardGame('Thermo Nuclear War');
game.play();
// Defaults to a nice game of chess
game.createBoardGame();
game.play();
}
</pre>That is pretty simple: start by creating a game factory instance, then create a game / play the game, create a game / play a game, etc.<br />
<br />
With mirrors, the code now becomes:<pre class=prettyprint>main() {
var series = new GameFactory('Professor Falken', 'Joshua');
series.start();
var game;
game = series.
boardGameClass('Checkers').
newInstance(new Symbol(''), []).
reflectee;
game.play();
game = series.
boardGameClass('Thermo Nuclear War').
newInstance(new Symbol(''), []).
reflectee;
game.play();
// Defaults to a nice game of chess
game = series.
boardGameClass().
newInstance(new Symbol(''), []).
reflectee;
game.play();
}</pre>Look, I love mirrors more than just about anyone, but even I have to admit that is horrible. There is far too much noise obscuring the relatively simple intent of the code. I am not a fan of being forced to supply a constructor as a <code>Symbol</code>—it seems like the default constructor could be inferred (I'm sure there is a good reason it is not though). Similarly, I do not like being forced to supply an empty list of arguments to the <code>newInstance()</code> constructor method. But the truth is, even if both of those complaints went away, the <code>newInstance()</code> and <code>reflectee</code> calls would still make a mirror approach significantly less desirable than the plain-old object approach.<br />
<br />
So mirrors are always undesirable in the factory method pattern, right? Well, not so fast. If there is a situation in which the client might want to create products with varying constructor arguments, then this mirror approach could come in handy. For instance, if we want to teach Joshua about thermonuclear war, we can create a alternate constructor for assigning different starting values for the two players:<pre class=prettyprint>class ThermoNuclearWar extends BoardGame {
List playerOnePieces = [ '1,000 warheads' ];
List playerTwoPieces = [ '1,000 warheads' ];
ThermoNuclearWar(): super();
ThermoNuclearWar.withWarheads(this.playerOnePieces, this.playerTwoPieces);
String get winner => "None";
}</pre>The client code can then run through as many scenarios as it takes to teach that thermonuclear war is a very strange game indeed:<pre class=prettyprint><code> game = series.
boardGameClass('Thermo Nuclear War').
newInstance(new Symbol(''), []).
reflectee;
game.play();
game = series.
boardGameClass('Thermo Nuclear War').
newInstance(
new Symbol('withWarheads'),
[['1 warhead'], ['1 warhead']]
).
reflectee;
game.play();
game = series.
boardGameClass('Thermo Nuclear War').
newInstance(
new Symbol('withWarheads'),
[['1 warhead'], ['1,000 warheads']]
).
reflectee;
game.play();</code></pre>This would result in output like:<pre class=prettyprint>$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
ThermoNuclearWar
Player One starts with: 1,000 warheads
Player Two starts with: 1,000 warheads
--
Winner: None
ThermoNuclearWar
Player One starts with: 1 warhead
Player Two starts with: 1 warhead
--
Winner: None
ThermoNuclearWar
Player One starts with: 1 warhead
Player Two starts with: 1,000 warheads
--
Winner: None
</pre>Afterwards, the game series can then switch back to a nice game of chess:<pre class=prettyprint><code> // Defaults to a nice game of chess
game = series.
boardGameClass().
newInstance(new Symbol(''), []).
reflectee;
game.play();</code></pre>So there is a reason for using mirrors in the factory method pattern after all. Yay! That said, they do not make as much sense as returning classes in Smalltalk. I will have to continue my search for Dart-specific features that can be brought to bear on the factory method pattern tomorrow.<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/d2a79f59113c888d0788">https://dartpad.dartlang.org/d2a79f59113c888d0788</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #88</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/ive-got-factory-in-my-factory-in-my.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/silly-factories-in-factory-method.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-66711361458051276282016-02-06T22:05:00.001-08:002016-02-07T21:57:59.127-08:00I've Got a Factory in My Factory in My Class Hierarchy of Factories (or Something Like That)<div class=top-chain-links></div><br />
Yesterday I worked up a <a href="http://dartlang.org">Dart</a> example of the <a href="">factory method pattern</a> in which a "game factory" could pit two players against each other in a series of board games:<pre class=prettyprint>main() {
var series = new GameFactory('Professor Falken', 'Joshua');
series
..start()
..createBoardGame('Checkers').play()
..createBoardGame('Thermo Nuclear War').play()
..createBoardGame().play();
}</pre>Most of the concrete implementation of the pattern is placeholder <code>print()</code> statements. The code so far establishes a series of games between two players, creates a board game via the factory method from which the pattern gets its name, then plays the game. Currently, this results in output along the lines of:<pre class=prettyprint>$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
CheckersGame
Player One starts with: 12 pieces
Player Two starts with: 12 pieces
--
Winner: Player One
ThermoNuclearWar
Player One starts with: 1,000 warheads
Player Two starts with: 1,000 warheads
--
Winner: None
ChessGame
Player One starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
Player Two starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
--
Winner: Player One</pre>That seems a decent example of the pattern except that the placeholder code is starting out with ugliness. Specifically, the products in the patterns—the various board games—are on the repetitive side:<pre class=prettyprint>class ChessGame extends BoardGame {
List playerOnePieces = [
'1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
];
List playerTwoPieces = [
'1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
];
}</pre>What the various <code>BoardGame</code> classes need is a common way to create the initial set of pieces on the board. If only there were a design pattern that could help with that…<br />
<br />
Say, that sounds like a factory method pattern! Now, I know what you're thinking, a factory inside a factory—that's typical pattern fanboyism. I'm not going to argue with you, but I beg your patience for just a bit...<br />
<br />
If <code>BoardGame</code> is now a factory, I need it to declare a factory method for its subclasses to implement. Since it needs to generate game pieces for the start of a game, I have it require a <code>_createPieces()</code> method:<pre class=prettyprint>abstract class BoardGame {
GamePieces playerOnePieces, playerTwoPieces;
BoardGame() {
playerOnePieces = _createPieces();
playerTwoPieces = _createPieces();
}
GamePieces _createPieces();
// ...
}</pre>Both player one and player two will be assigned the same number of pieces to begin, so the constructor assigns both player one's and player two's pieces to the results of the <code>_createPieces</code> factory method. But the abstract <code>BoardGame</code> does not know how to create chess, checkers, etc. pieces. Subclasses need to define these:<pre class=prettyprint>class ChessGame extends BoardGame {
GamePieces _createPieces() => new ChessPieces();
}
class CheckersGame extends BoardGame {
GamePieces _createPieces() => new CheckersPieces();
}
class ThermoNuclearWar extends BoardGame {
GamePieces _createPieces() => new ThermoNuclearPieces();
String get winner => "None";
}</pre>With that, my board game classes are significantly DRYer and better able to define the functionality behind the actual game play.<br />
<br />
But back to the factory-in-a-factory craziness that I have inflicted on myself. I think it actually makes sense. From an illustrative standpoint, it is over the top, but it feels like a reasonable, organic structure. Perhaps last night's <code>GameFactory</code> → <code>GameBoard</code> creator/product was somewhat artificial, but I need to generate different gameboards at runtime, so that makes a decent amount of sense. If anything, tonight's approach feels even better. Each boardgame needs to layout and assign pieces to the players, so a factory method serves nicely in that capacity.<br />
<br />
In fact, it makes so much sense that it is a flavor of the factory method pattern: the parallel class hierarchy variation. By taking this approach, I know that, for each type of board game in the <code>BoardGame</code> class hierarchy, there will be a corresponding entry in the hierarchy of the <code>GamePieces</code> classes. The <code>ChessGame</code> needs to use <code>ChessPieces</code> in order to populate the game:<pre class=prettyprint>class ChessGame extends BoardGame {
GamePieces _createPieces() => new ChessPieces();
}</pre>Armed with that knowledge, the client code can make use of this as well. For example it could restart a game or start a new one:<pre class=prettyprint><code> series.start();
var game;
game = series.createBoardGame('Checkers');
game.play();
// Start over
game.playerOnePieces = game._createPieces();
game.playerTwoPieces = game._createPieces();
game.play();</code></pre>That might be a little more useful in another example (a <code>restart()</code> method would make most sense in this example), but it still serves to illustrate some of the potential of this parallel hierarchy approach. I may examine a different example tomorrow to get a better handle on this. Or I may switch to mirrors. Either way, it is sure to be more fun with factories!<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/639e49cfc1b2ee3cb82a">https://dartpad.dartlang.org/639e49cfc1b2ee3cb82a</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #87</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/factory-method-without-factory.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/factory-games-with-mirrors.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-33273563872303372492016-02-05T22:33:00.000-08:002016-02-06T22:10:30.394-08:00Factory Method without Factory Subclasses<div class=top-chain-links></div><br />
I am already bored by the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a>. Time for <a href="http://dartlang.org">Dart</a> mirrors! I kid of course. About the bored, not the mirrors. I goes without saying that I'm going to add mirrors.<br />
<br />
The <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a> mentions two major varieties of the pattern: one that uses an abstract class, forcing subclasses to define the factory implementations, and the other in which the creator class provides a default factory implementation. I tried the the former last night, so tonight I try with a default implementation. <br />
<br />
For this example, I adopt the Delphi example on the Wikipedia page, which describes a game factory. For this example, two players want to play a series of games against each other. The creator for that might look like:<pre class=prettyprint>// Creator
class GameFactory {
String playerOne, playerTwo;
GameFactory(this.playerOne, this.playerTwo);
String toString() => "*** $playerOne vs. $playerTwo ***";
// The factory method
BoardGame createBoardGame([String game]) {
if (game == 'Checkers') return new CheckersGame();
if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
return new ChessGame();
}
}
</pre>The constructor requires the names of both players. Once they are ready to play a game, they might choose a game from a text based listing of games, passing the name to <code>createBoardGame()</code>. In this example, there are no subclasses for the creator—the <code>GameFactory</code> knows how to create all products. <br />
<br />
The "products" in this version of the pattern are different board games that can be played in the system. Each will need a list of pieces that can be played:<pre class=prettyprint>// Product
class BoardGame {
List playerOnePieces = [];
List playerTwoPieces = [];
String get winner => new Random().nextBool() ?
"Player One" : "Player Two";
String toString() =>
" ${this.runtimeType}\n"
" Player One has: ${playerOnePieces.join(', ')}\n"
" Player Two has: ${playerTwoPieces.join(', ')}\n"
" Winner: $winner\n";
}</pre>So a chess game would look like:<pre class=prettyprint>class ChessGame extends BoardGame {
List playerOnePieces = [
'1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
];
List playerTwoPieces = [
'1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
];
}</pre>There is some redundancy there, but I will worry about that another time. For now, I have my single creator class and various product classes. Which means that I am ready for some client code.<br />
<br />
I start with the creator, which starts the game series between two players:<pre class=prettyprint><code> var series = new GameFactory('Professor Falken', 'Joshua');
print(series);</code></pre>Then they can play various games, choosing each from the text listing on the main menu:<pre class=prettyprint><code> game = series.createBoardGame('Checkers');
print(game);
game = series.createBoardGame('Thermo Nuclear War');
print(game);
game = series.createBoardGame();
print(game);</code></pre>Running this would result in something like the following output:<pre class=prettyprint>$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
CheckersGame
Player One has: 12 pieces
Player Two has: 12 pieces
Winner: Player Two
ThermoNuclearWar
Player One has: 1,000 warheads
Player Two has: 1,000 warheads
Winner: None
ChessGame
Player One has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
Player Two has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
Winner: Player One
</pre>So there you go: a factory method pattern example in which the creator is a concrete class, provided a default product, and can supply all products. It does not feel terribly different from last night's example. In fact, it feels almost too simple to warrant the creator class. Except for the need to remember the two players' names, this could almost be done in client code.<br />
<br />
I am unsure if this is the example that I would like to use in <a href="http://designpatternsindart.com/">Design Patterns in Dart</a> as it is a tad simplistic. Then again, there are some opportunities for improving the code that may make it more illustrative. That's something for tomorrow. Plus mirrors!<br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/0018524156ade602d043">https://dartpad.dartlang.org/0018524156ade602d043</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #86</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/factory-method-pattern-take-2.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/ive-got-factory-in-my-factory-in-my.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-17475984437490722052016-02-04T22:01:00.001-08:002016-02-05T22:36:04.930-08:00Factory Method Pattern (Take 2)<div class=top-chain-links></div><br />
Crazy what happens when you start writing a book, take a break for a year and a half, then come back. I had completely forgotten that I <a href="http://japhr.blogspot.com/search/label/factory%20method%20pattern">have already researched</a> the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory method pattern</a> for <a href="http://designpatternsindart.com/">Design Patterns in Dart</a>. But research it I did.<br />
<br />
Crazy too is that the approach I was taking to design patterns back then is very different to the one that I have been doing on this recent chain of posts. My focus recently has been to understand the consequences of patterns and different approaches to the pattern. Back then I spent the entire time benchmarking. I think it is especially funny that I included benchmarks for a mirror based solution—some things don't change.<br />
<br />
To gain a better understanding of the pattern, I start anew. For my initial example, I adapt the Java example maze from the Wikipedia page which itself was adapted from the C++ example in the <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a>. <br />
<br />
The prime mover in this pattern is the "creator" class. In the maze example, the <code>MazeGame</code> is the creator:<pre class=prettyprint>abstract class MazeGame {
List<Room> rooms = [];
MazeGame() {
Room room1 = _makeRoom();
Room room2 = _makeRoom();
room1.connect(room2);
addRoom(room1);
addRoom(room2);
}
Room _makeRoom();
void addRoom(Room r) { rooms.add(r); }
}</pre>The constructor for this class creates 2 rooms, connects them, and adds the 2 rooms to the game. The <code>_makeRoom()</code> method is left abstract by virtue of having no method body. In other words, it is up to concrete implementations of this class to define how to make a room. This is the crux of the pattern. The <code>MazeGame</code> does not know the exact type of rooms with which it will be working, so it delegates that responsibility to subclasses.<br />
<br />
The first concrete creator might create nothing but magic rooms in a magic maze:<pre class=prettyprint>class MagicMazeGame extends MazeGame {
@override
Room _makeRoom() => new MagicRoom();
}</pre>A second concrete creator might create nothing but ordinary rooms for an early level in the game:<pre class=prettyprint>class OrdinaryMazeGame extends MazeGame {
@override
Room _makeRoom() => new OrdinaryRoom();
}</pre>More interestingly, there is nothing stopping me from generating any kind of room in a subclass:<pre class=prettyprint>class CrazyMazeGame extends MazeGame {
@override
Room _makeRoom() =>
new Random().nextBool() ? new OrdinaryRoom() : new MagicRoom();
}</pre>That is the pattern in a nutshell. The things being created are "products" in this pattern. Products in this pattern have no requirements other than there must be multiple types—otherwise there is no reason for a subclass to choose. The <code>Room</code> product that will work with that above code might look like:<pre class=prettyprint>// Product
class Room {
List<room> connectedRooms = [];
void connect(Room other) {
connectedRooms.add(other);
}
}
// Concrete Product #1
class MagicRoom extends Room {}
// Concrete Product #1
class OrdinaryRoom extends Room {}</pre>With that, client code can make use of the creator class:<pre class=prettyprint><code> MazeGame crazyGame = new CrazyMazeGame();
print(crazyGame);</code></pre>Which results in something like:<pre class=prettyprint>$ ./bin/maze.dart
CrazyMazeGame has 2 rooms: Instance of 'MagicRoom', Instance of 'OrdinaryRoom'
</pre>That will do for an introduction to the pattern. There are still implications to explore. I would also like to come up with a "modern web" example of the pattern. Way back when, I used this pattern in a <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> knockoff, so I might do that again. It would be better, however, to come up with something a little more accessible to most programmers. Grist for forthcoming days.<br />
<br />
<i>Play with the code so far on DartPad: <a href="https://dartpad.dartlang.org/561d021f19910a79c194">https://dartpad.dartlang.org/561d021f19910a79c194</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #85</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/degenerate-abstractions.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/factory-method-without-factory.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-26351839637843876292016-02-03T22:43:00.001-08:002016-02-04T22:02:57.438-08:00Degenerate Abstractions<div class=top-chain-links></div><br />
What do you get when you remove all but one refined abstraction from the <a href="https://en.wikipedia.org/wiki/Bridge_pattern">bridge pattern</a>? I already looked into what happens when you <a href="http://japhr.blogspot.com/2016/01/degenerate-bridges.html">only need one implementor</a>. The <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a> even included a discussion about one implementor, terming it a "degenerate case." What about the opposite?<br />
<br />
The prime mover in the bridge pattern is given the seemingly vague name of "The Abstraction." There are two required characteristics for the abstraction. First, it needs to perform some action whose exact implementation can vary. Second, it needs to have subclasses—different specific types of the abstraction. These subclasses are called refined abstractions mostly because they had to call them something and "concrete abstraction" is a contradiction in terms.<br />
<br />
The idea is that client code can use different refined abstractions with different implementations. Maybe the client chooses which implementation to use. Maybe the refined abstraction chooses. It doesn't matter. Each refined abstraction should work with each action implementation. Furthermore developers should be able to make changes to the implementation without requiring corresponding changes to the refined abstractions and vice versa.<br />
<br />
When there is only one implementation, the Gang of Four book concludes that there is still value to the pattern. Even if only one implementation for the action is ever used, the separation of the implementation from abstraction still buys independent changes to each. So the same thing should be true of multiple implementations and a single abstraction, right?<br />
<br />
Let's take a look at the web example that I have been using. The backend communication has two implementations, one to send messages over websockets and the other to send messages over plain-old HTTP. In <a href="http://dartlang.org">Dart</a>, this looks like:<pre class=prettyprint>abstract class Communication {
void send(String message);
}
// Concrete Implementor 1
class HttpCommunication implements Communication {
void send(message) {
HttpRequest.postFormData('/status', {'message': message});
}
}
// Concrete Implementor 2
class WebSocketCommunication implements Communication {
WebSocket _socket;
WebSocketCommunication() { _startSocket(); }
_startSocket() async { /* ... */ }
void send(message) {
_socket.send("message=$message");
}
}</pre>My original <i>intent</i> (it's important that I use that specific word) is to have multiple <code>Messenger</code> refined abstractions will allow people to post status updates:<pre class=prettyprint>// Abstraction
abstract class Messenger {
Communication comm;
Messenger(this.comm);
void updateStatus();
}</pre>In this thought experiment, I am coding the web version while another team is building a mobile <code>Messenger</code>. The <code>Messenger</code> interface tells both teams how to build our classes. We will be communicating with some form of <code>Communciation</code> and we need an <code>updateStatus()</code> method to post messages over those communication channels.<br />
<br />
But something happens. Just after we start, the company decides that it is web-only and fires the entire mobile team. Since I want to avoid premature generalization, I get rid of the <code>Messenger</code> interface and dump everything into <code>WebMessenger</code>:<pre class=prettyprint>// Degenerate Abstraction
class WebMessenger {
Communication comm;
InputElement _messageElement;
WebMessenger(this._messageElement) : comm = new HttpCommunication();
void updateStatus() {
comm.send(message);
}
String get message => _messageElement.value;
}
</pre>I still support the <code>Communication</code> implementor, defaulting to the <code>HttpCommunication</code> concrete implementation. I still support the <code>updateStatus()</code> method. I also have code specific to a web page, which grabs the message to post from an input element. But, despite the new web-specific code, the original intent is still the same. I want to be able to make changes to the communication implementation without affecting the <code>WebMessenger</code> abstraction. I still want to be able to assign different <code>Communication</code> objects, in this case at runtime when a different radio button is selected:<pre class=prettyprint><code> queryAll('[name=implementor]').
onChange.
listen((e) {
var input = e.target;
if (!input.checked) return;
if (input.value == 'http')
message.comm = new HttpCommunication();
else
message.comm = new WebSocketCommunication();
});</code></pre>So the intent remains the same. And, maybe someday the company will come to its senses and rehire a mobile team. At that point, the abstraction interface can be pulled back out and I will have a true bridge. In the meantime, what do I have? <br />
<br />
This sure looks like a simple <a href="https://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a> to me:<pre class=prettyprint>class WebMessenger {
Communication comm;
// ...
void updateStatus() {
comm.send(message);
}
// ...
}</pre>In that sense, a <code>WebMessenger</code> <i>has a</i> <code>Communication</code> object. The specific implementation of <code>Communication</code> can vary depending on what strategy is chosen. So is it a strategy? <br />
<br />
I think the answer is that it remains a bridge because of the intent—intent is big in patterns. Even though it winds up looking exactly like a strategy, the structure was originally chosen to support a multiple abstraction structure. Plus, it could easily be refactored to get back to an interface that makes the pattern more explicit.<br />
<br />
What I find interesting, however, is what another developer might think should she come along 6 months from now. Without the interface, she should reasonably conclude that the intent is a simple strategy pattern. Under that assumption, she might very well make any number of subsequent design decisions that make it very hard to switch back to a bridge. So in that sense, who cares what the intent was? Unless the intent is made explicit in some form, it would seem that structure trumps intent. <br />
<br />
And so, my final answer is that a degenerate abstraction in the bridge pattern does not guarantee that the pattern remains a bridge. More often than not, a degenerate abstraction in the bridge pattern means that it is a bridge pattern no more. In its place is a strategy pattern, intent be damned.<br />
<br />
<br />
<span style="color: #ccc">Day #84</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/in-which-i-quarrel-with-bridge-names.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/factory-method-pattern-take-2.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-87759563156456134362016-02-02T23:05:00.001-08:002016-02-03T22:45:25.741-08:00In Which I Quarrel with Bridge Names<div class=top-chain-links></div><br />
I confess that I find the names in the <a href="https://en.wikipedia.org/wiki/Bridge_pattern">bridge pattern</a> awkward. <br />
<br />
Why are there "refined abstractions" instead of "concrete abstractions"? Why is it "concrete implementor" instead of "refined implementor"? Why did we settle on names like "abstraction" and "implementor" which closely mirror programming concepts like "abstract classes" and "interface implementation"? <br />
<br />
Also, why does the <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a> describe the pattern as decoupling "an abstraction from its implementation so that the two can vary independently" instead of "decoupling an abstraction from part of its implementation"? The pattern does not have the implementor implement all of the abstraction's functionality, just parts of it. <br />
<br />
Consider the "refined abstraction" <code>WebMessenger</code>:<pre class=prettyprint>// Refined Abstraction
class WebMessenger extends Messenger {
InputElement _messageElement;
WebMessenger(this._messageElement);
void updateStatus() {
comm.send(message);
}
String get message => _messageElement.value;
}</pre>Just about all of that is specific to the refined abstraction—obtaining a message from a web page input element. Only the <code>updateStatus()</code> method bridges between the abstraction and implementor. <br />
<br />
I suppose the abstraction (as opposed to the refined abstraction) has more of its implementation performed by the implementor:<pre class=prettyprint>abstract class Messenger {
Communication comm;
Messenger() : comm = new Communication();
void updateStatus();
}</pre>In there, <code>Communication</code> is a factory that assigns a concrete (not refined) implementor, which is then used in <code>updateStatus()</code>. In this simple case, the bridge might implement the whole interface. In a more substantial example from the Wikipedia page, the <code>Shape</code> abstraction on has part of its implementation handled by the concrete implementor:<pre class=prettyprint>abstract class Shape {
DrawingApi _drawingApi;
Shape(this._drawingApi);
void draw(); // low-level
void resizeByPercentage(double pct); // high-level
}</pre>The more I think about it, the less I like any of the naming conventions used. But I do not have particularly good alternatives. And, given enough thought, I grudgingly admit that the names adopted by the Gang of Four are reasonable and might be the best possible. <br />
<br />
The main player in the pattern is some abstract concept—a window, a shape, a messenger. The "abstraction" name also suggests more concrete versions of the abstractions, which are important parts of the pattern termed refined abstractions. The secondary character in the play is the implementor, which performs a specific task for the abstraction. In other words, the implementor implements specific tasks.<br />
<br />
There is probably not much to be done with "abstraction." I might alternatively call it a "concept," "thing," or "object." "Concept" is just as vague a name as "abstraction," and lacks the suggestion of refined concepts. I like thing, but what is a refined thing? I can hardly talk about Thing #1 and Thing #2 without heading down a Seussian side-trail. And "object" is a ridiculous term to introduce to an object oriented discussion. <br />
<br />
I also have to conclude that "refined abstraction" might be the best name. "Concrete abstraction" is too much a contradiction in terms like "heavy air." Sure it might make sense if you give it some thought, but best to use terms that do not require much thought—even if they do no carrying significant meaning. <br />
<br />
I may recast "implementor" in some of <a href="http://designpatternsindart.com/">Design Patterns in Dart</a>. I cannot completely rename things in a little-old, self-published book. Also, I know my readers are smart enough to work this out for themselves. But perhaps when I introduce "implementor," I will call it a "glorified gofer" since the abstraction tells it to run certain tasks (errands) on demand. <br />
<br />
So after all of that, I conclude what I suspected all along—the Gang of Four probably gave a decent amount of thought to names. And aside from a quibble over whether "its implementation" means all or part of the implementation, I think the Gang of Four have me convinced that their convention, though not ideal, is likely the best.<br />
<br />
<br />
<span style="color: #ccc">Day #83</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/02/factory-bridges-in-dart.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/degenerate-abstractions.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-22094777115991493972016-02-01T21:40:00.002-08:002016-02-02T23:06:33.992-08:00Factory Bridges in Dart<div class=top-chain-links></div><br />
I've constructed a bridge in a client. I've constructed a bridge in a constructor. So tonight, I construct a bridge in a factory. <br />
<br />
I must investigate the <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">factory</a> and <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">abstract factory</a> in <a href="http://dartlang.org">Dart</a>. Mostly because I am unsure how much value the standard structure of the pattern is needed in a language with <a href="https://www.dartlang.org/docs/dart-up-and-running/ch02.html#factory-constructors">factory constructors</a> baked right in. Since they are baked in, that's what I opt for tonight.<br />
<br />
The abstraction in my bridge pattern example continues to be a <code>Messenger</code>:<pre class=prettyprint>abstract class Messenger {
Communication comm;
Messenger(this.comm);
void updateStatus();
}</pre>The purpose of classes implementing this interface is to simply facilitate status updates. There are a number of communication methods bridged from this abstraction: HTTP, websockets, etc. In last night's pass at the bridge pattern, the specific implementation was chosen in the abstraction's constructor (i.e. <code>Messenger</code>) and subsequently changed when certain thresholds were reached. <br />
<br />
Tonight, I move the responsibility of choosing the implementation out of the abstraction and into a factory constructor. Because it make sense and is so darn easy, I declare a factory constructor in the <code>Communication</code> implementation:<pre class=prettyprint>import 'dart:math' show Random;
// Implementor
abstract class Communication {
factory Communication() => new Random().nextBool() ?
new WebSocketCommunication() : new HttpCommunication();
void send(String message);
}
</pre>I continue to find it strange that an abstract class can declare a constructor—even if it is a factory constructor. Each time, I must remind myself that it works for just this kind of case: choosing a subclass implementation. In this case, I randomly choose between the <code>WebSocketCommunication</code> and <code>HttpCommunication</code> concrete implementations.<br />
<br />
No changes are required to either of the concrete implementations. They both continue to establish their connections to the server and define the appropriate code to send messages. The <code>Messenger</code> abstraction and the subclass refined for use in web clients, <code>WebMessenger</code> do need to change slightly. <br />
<br />
The subclass no longer needs to concern itself with the <code>Communication</code> implementation. The <code>Messenger</code> can do that. Instead, the subclass can worry only about web page related things, like the text input element from which it will obtain messages to send back to the server:<pre class=prettyprint>class WebMessenger extends Messenger {
InputElement _messageElement;
WebMessenger(this._messageElement);
// ...
}</pre>The <code>Messenger</code> abstraction needs to do a little more work now, but not much. In addition to declaring the <code>Communication</code> instance variable, it now assigns it in the constructor:<pre class=prettyprint>abstract class Messenger {
Communication comm;
Messenger() : comm = new Communication();
void updateStatus();
}</pre>On a sidenote, I remain skeptical of initializer lists in constructors like that. I am trying to use them to see if they grow on me, but I think it just makes things noisy (especially if a constructor body is added to the mix).<br />
<br />
That pretty much does it. Through several page reloads, I find that the client does indeed randomly switch between implementations:<pre class=prettyprint>$ ./bin/server.dart
[WebSocket] message=asdf
[WebSocket] message=asdf
[WebSocket] message=asdf
[HTTP] message=asdf
[WebSocket] message=asdf
[HTTP] message=asdf
</pre>That was fairly straight-forward and low on the surprise scale. I note before concluding that none of this precludes me from setting the <code>Communciation</code> implementation in the client code. For example:<pre class=prettyprint>main() {
var message = new WebMessenger(query('#message'))
..comm = new HttpCommunication();
// ...
}</pre>I also note that making more purposeful choices than the current random implementation selection is straight-forward. I can simply choose based on VM info, browser info, or any other bit of information on which one might opt between HTTP and websocket communication. Any or all of those choices would be right at home in the factory constructor. Or perhaps someday in an abstract factory constructor.<br />
<br />
<p><i>Code for the bridge client and the backend server are <a href="https://github.com/eee-c/design-patterns-in-dart/tree/1c4d3d113077373ed1eca4ef352b9d15709dea19/bridge">on the Design Patterns in Dart public repository</a>.</i></p><br />
<br />
<br />
<span style="color: #ccc">Day #82</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/01/when-to-choose-your-own-implementation.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/in-which-i-quarrel-with-bridge-names.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-4499288836392033392016-01-31T20:29:00.000-08:002016-02-01T21:42:42.878-08:00When to Choose Your Own Implementation in the Bridge Pattern<div class=top-chain-links></div><br />
At this rate, every pattern in <a href="http://designpatternsindart.com/">Design Patterns in Dart</a> is going to include a websocket. That is a little crazy considering that I do not use websockets all that often in actual client code, but they have the dual benefits of having an accessible API and being conceptually easy to understand. So who knows, maybe I will find a way to include them in every single pattern.<br />
<br />
The pattern of current investigation is the <a href="https://en.wikipedia.org/wiki/Bridge_pattern">bridge pattern</a>. As I found last night, websockets can serve as a realistic alternative to vanilla HTTP for communication. The alternative implementations for communication make the situation well suited for the bridge pattern, which seeks to "bridge" between an abstraction and multiple implementations. <br />
<br />
What I would like to examine tonight is creating the right implementor object. Last night, I made two quick decisions on when to create the <code>Communication</code> implementor. Perhaps I could have done that better.<br />
<br />
The abstraction in this bridge pattern example remains a <code>Messenger</code> class. It could be a mobile app for posting status updates or sending direct messages. It could be a web form that does the same thing. Either way, a messenger needs a reference to a concrete implementation of <code>Communication</code> and it needs to know how to post updates. So the interface that refined <code>Messenger</code> classes will need to extend looks like:<pre class=prettyprint>// Abstraction
abstract class Messenger {
Communication comm;
Messenger(this.comm);
void updateStatus();
}</pre>The refined messenger class that I am using is a <code>WebMessenger</code>. Its constructor stores a text input element from which it can obtain messages to send:<pre class=prettyprint>class WebMessenger extends Messenger {
InputElement _messageElement;
WebMessenger(this._messageElement) :
super(new HttpCommunication());
// ...
}</pre>The bit after the constructor is a redirection to the superclass constructor, which supplies a <code>Communication</code> implementation to the <code>Messenger</code> superclass. Here is where I make my first decision about when to construct a <code>Communication</code> implementation. By default, I opt to create an <code>HttpCommunication</code> implementation of the <code>Communication</code> interface. Since the superclass requires a <code>Communication</code> object in its constructor, I either had to create one right in the constructor as I have done here or I could have required client code to do so. <br />
<br />
The choice of whether the client should provide the implementation or if it should be done in the refined abstraction comes down to the details of the code. To be perfectly honest, I did it this way because it was quickest. It probably was not the correct choice, however. Yesterday's implementation has the client choose when to switch between the websocket and HTTP concrete implementations. If the client code chose when to switch, it probably should determine initial state as well.<br />
<br />
But let's move the choice of implementation from the client and instead put in into the <code>WebMessenger</code>. It makes sense to start with a low-overhead <code>HttpCommunication</code> object. Given that, the redirecting constructor can stay as-is. But, should the client find itself at the mercy of a power user who is updating status more often than 3 times a minute, then the <code>WebMessenger</code> should switch to a websocket.<br />
<br />
So, after each message, I log the message along with a timestamp:<pre class=prettyprint>class WebMessenger extends Messenger {
// ...
List _history = [];
// ...
void updateStatus() {
comm.send(message);
_log(message);
}
void _log(message) {
_history.add([new DateTime.now(), message]);
}
// ...
}</pre>Then, after logging I do a simple calculation of the frequency with which this user is updating. If it is too often or too slow, I switch <code>Communication</code> implementations:<pre class=prettyprint>class WebMessenger extends Messenger {
// ...
void updateStatus() {
comm.send(message);
_log(message);
_maybeChangeCommunication();
}
// ...
_maybeChangeCommunication() {
if (_history.length < 3) return;
var last = _history.length - 1,
dateOld = _history[last-2][0],
dateNew = _history[last][0],
diff = dateNew.difference(dateOld);
if (diff.inSeconds < 60) {
if (comm is! WebSocketCommunication)
comm = new WebSocketCommunication();
}
else {
if (comm is! HttpCommunication)
comm = new HttpCommunication();
}
}
}</pre>
That does the trick. If I send the first 3 message updates out in quick succession, then <code>WebMessenger</code> upgrades the connection to the <code>WebSocketCommunication</code> implementation. The server sees the first three messages come in over HTTP, then the next few over websockets:<pre class=prettyprint>$ ./bin/server.dart
[HTTP] message=asdf+1
[HTTP] message=asdf+2
[HTTP] message=asdf+3
[WebSocket] message=asdf 4
[WebSocket] message=asdf 5
[WebSocket] message=asdf 6
[HTTP] message=asdf+7</pre><p>I then wait a minute between messages 5 and 6, after which I have crossed the lower threshold and am again in the <code>HttpCommunication</code> implementation. </p><p>That seems a nice example of when it make sense for the refined abstraction to have responsibility for choosing the implementation—websockets come through again! I do think that some or all of the choice behavior could move into the abstraction itself. Whether that is a good idea depends on the variance in refined abstractions. If a mobile messenger wanted different thresholds or added a new implementation, then the choose-your-implementation behavior would need to continue to reside in the refined abstractions. But if the web and mobile (and other) refined abstractions could share the same choices, then the subclasses could be wonderfully brief. </p><p><i>Code for the bridge client and the backend server are <a href="https://github.com/eee-c/design-patterns-in-dart/tree/c47bed0962fcf3424abf646e0d969b0a5534dd0a/bridge">on the Design Patterns in Dart public repository</a>.</i></p>
<p><span style="color: #ccc">Day #81</span> </p><p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/01/the-bridge-pattern-with-websockets-and.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/02/factory-bridges-in-dart.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com1tag:blogger.com,1999:blog-581197352358126527.post-4678929335471432432016-01-30T20:50:00.000-08:002016-01-31T20:33:32.677-08:00The Bridge Pattern with Websockets and HTTP<div class=top-chain-links></div><br />
Design patterns don't tell us how to develop systems. Patterns are names applied to how we already develop. Knowing patterns well won't help us to implement them better in the future—we are already doing that very fine, thank you very much. Knowing a pattern is understanding its consequences and puts us in a better position to minimize or take advantage of those consequences. <br />
<br />
That's all fine—if you recognize the pattern. When I first started playing with it, I could not think of an example in which I had used the <a href="https://en.wikipedia.org/wiki/Bridge_pattern">bridge pattern</a>. It took me some brain digging, but I think I finally excavated a real-world example of it.<br />
<br />
Consider, if you will, a browser application that normally communicates with a server over websockets, but has to switch to plain-old HTTP under certain circumstances. The reason for switching might be an older client, a low-memory browser, or simply that this part of the application needs to talk to an HTTP-only server. <br />
<br />
Whatever the reason, the web application should not change when the communication implementation changes. If the application is a simple form, then the web form and backing code should never change when switching between HTTP and websockets:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEil5gMyB_sapDq5T5RmLF0a6NiKBojpf8saIKE7GqfAj5LaiHpbE5TCXLpjYQZjAK1msRrfJxPqHmChXxu7cgi821zAjtTOLfcx5WZMoWCfjIyb4zGCSmTYdQwEfN8RG0H41q3rEF6qPceM/s1600/01-web_form_with_different_implementors.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEil5gMyB_sapDq5T5RmLF0a6NiKBojpf8saIKE7GqfAj5LaiHpbE5TCXLpjYQZjAK1msRrfJxPqHmChXxu7cgi821zAjtTOLfcx5WZMoWCfjIyb4zGCSmTYdQwEfN8RG0H41q3rEF6qPceM/s640/01-web_form_with_different_implementors.png" width=570 /></a><br />
<br />
I need to suss out better names for the actors in this play, but I start by calling the web form a "messenger" and mechanism for talking "communication." They are kind of the same thing, so I need to work on that, but it will do for a start. The <code>Messenger</code> abstraction will require a <code>Communication</code> implementation of some kind and will need to know how to send messages with that communication channel. Expressed in <a href="http://dartlang.org">Dart</a>, that looks like:<pre class=prettyprint>abstract class Messenger {
Communicator comm;
Messenger(this.comm);
void send();
}</pre>The refined abstraction is a web form messenger that gets the message to send from a text element:<pre class=prettyprint>class FormMessenger extends Messenger {
Element _messageElement;
FormMessenger(this._messageElement) : super(new HttpCommunicator());
void send() {
comm.save(message);
}
String get message => _messageElement.value;
}</pre>As can be seen from the <code>send()</code> method, the <code>Communication</code> class needs to support a <code>save()</code> method in order to save the message on the backend:<pre class=prettyprint>abstract class Communicator {
void save(String message);
}</pre>The <code>HttpCommunicator</code> is simple enough, thanks to the <code>HttpRequest.postFormData()</code> method:<pre class=prettyprint>class HttpCommunicator implements Communicator {
void save(message) {
HttpRequest.postFormData('/save', {'message': message});
}
}</pre>The second implementor, the <code>WebsocketCommunicator</code> class, takes a little more setup for websockets, but is still pretty straight forward:<pre class=prettyprint>class WebSocketCommunicator implements Communicator {
WebSocket _socket;
WebSocketCommunicator() { _startSocket(); }
_startSocket() async {
_socket = new WebSocket('ws://localhost:4040/ws');
var _c = new Completer();
_socket.onOpen.listen((_){ _c.complete(); });
await _c.future;
}
void save(message) {
_socket.send(message);
}
}</pre>And that pretty much does it. Aside from some better naming, this feels like a fairly accessible example. <br />
<br />
One of the implications of the bridge pattern is that a code decision needs to be made as to where to assign the implementor. For a fist pass, I listen to the two radio buttons in the form and, based on which is selected, I assign a different <code>Communicator</code>:<pre class=prettyprint><code> queryAll('[name=implementor]').
onChange.
listen((e) {
var input = e.target;
if (!input.checked) return;
if (input.value == 'http')
message.comm = new HttpCommunicator();
else
message.comm = new WebSocketCommunicator();
});</code></pre>With that, I can switch between implementors and send messages to the server however I like:<pre class=prettyprint>$ ./bin/server.dart
[HTTP] message=A+web+form+message%21
[WebSocket] A web form message!
[HTTP] message=A+web+form+message%21
[HTTP] message=A+web+form+message%21
[HTTP] message=A+web+form+message%21</pre>Nice! Now all that is left is to come up with some better names.<br />
<br />
<i>Full code for the frontend and backend is located at: <a href="https://github.com/eee-c/design-patterns-in-dart/tree/master/bridge">https://github.com/eee-c/design-patterns-in-dart/tree/master/bridge</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #80</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/01/handle-body-reference-counting-in.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/01/when-to-choose-your-own-implementation.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0tag:blogger.com,1999:blog-581197352358126527.post-42193571002009596522016-01-29T22:19:00.000-08:002016-01-30T20:52:03.336-08:00Handle Body Reference Counting in Garbage Collected Dart<div class=top-chain-links></div><br />
Oh, what the hell. I finished yesterday hand-waving over a particular implementation. Let's see if I can actually implement a reference counting <a href="http://c2.com/cgi/wiki?HandleBodyPattern">handle body</a> in <a href="http://dartlang.org">Dart</a>. There may be no practical application for this in a garbage collected language like Dart, but we'll see...<br />
<br />
I continue to use <code>Shape</code> as the abstraction in my <a href="https://en.wikipedia.org/wiki/Bridge_pattern">bridge pattern</a> exploration. It will now serve double duty as the handle class, holding references to the body implementation. Well, it already did that (which is rather the point of the pattern), but now it needs to reference, dereference, and delete implementors as well.<br />
<br />
The implementor is <code>DrawingApi</code>, which knows that subclasses will, among other things, know how to draw a circle:<pre class=prettyprint>abstract class DrawingApi {
void drawCircle(double x, double y, double radius);
}
</pre>To maintain reference counts, <code>DrawingApi</code> needs a <code>_refCount</code> instance variable along with <code>ref()</code> and <code>deref()</code> methods to increase and decrease that counter:<pre class=prettyprint>abstract class DrawingApi {
int _refCount = 0;
void ref() {
_refCount++;
print(' $this Increased refcount to $_refCount');
}
void deref() {
_refCount--;
print(' $this Decreased refcount to $_refCount');
}
void drawCircle(double x, double y, double radius);
}
</pre>In client code, I can create an instance of two subclasses of <code>DrawingApi</code>:<pre class=prettyprint>main() {
var api1 = new DrawingApi1(),
api2 = new DrawingApi2();
// ...
}</pre>Then I initially set those as the "drawer" (the thing that draws, not a thing that holds stuff in desks) property for <code>Circle</code> instances:<pre class=prettyprint>main() {
// ...
var circle1 = new Circle(1.0, 2.0, 3.0)..drawer = api1,
circle2 = new Circle(0.0, 6.0, 1.0)..drawer = api1,
circle3 = new Circle(2.0, 2.0, 1.5)..drawer = api2;
// ...
}</pre>The <code>Circle</code> class is a concrete implementor of the <code>Shape</code> abstraction / handle class. So assigning <code>api1</code> to two difference <code>Circle</code> instances needs to update the number of references to <code>api1</code> accordingly.<br />
<br />
I more or less copy the code from the handle / body example from the bridge pattern chapter in the <a href="http://en.wikipedia.org/wiki/Design_Patterns">Gang of Four book</a>. The <code>drawer()</code> setter is responsible for noting the new reference, and noting the derefence for the existing object. If the reference count goes to zero, the handle class needs to delete the reference, which I do by assigning the <code>_drawingApi</code> instance variable to <code>null</code>:<pre class=prettyprint>abstract class Shape {
DrawingApi _drawingApi;
set drawer(DrawingApi other) {
other.ref();
if (_drawingApi != null) {
_drawingApi.deref();
if (_drawingApi._refCount == 0) {
print(' ** Deleting no longer used $_drawingApi **');
_drawingApi = null;
}
}
_drawingApi = other;
}
}</pre>It is here that I finally realize that there is no point to doing any of this—at least not in this example. Even without explicitly setting <code>_drawingApi</code> to <code>null</code>, it gets assigned to a different value on the following line. Once that happens, Dart itself notes that there is one fewer references to the object and, if zero, schedules the object for garbage collection.<br />
<br />
I don't know why I thought this might be necessary in some cases. I do get easily confused in the presence of C++.<br />
<br />
Anyhow, back in my client code, I draw those circles with the mixture of <code>api1</code> and <code>api2</code>, then update the drawers so that everyone is using <code>api2</code>:<pre class=prettyprint>main() {
// ...
circle1.draw();
circle2.draw();
circle3.draw();
circle1.drawer = api2;
circle2.drawer = api2;
api1 = api2 = null;
circle1.draw();
circle2.draw();
circle3.draw();
}</pre>When I run this code, I get what I expect. The first time through a mixture of <code>api1</code> and <code>api2</code> drawers are used, when I switch to all-<code>api2</code>, the deletion of the <code>api2</code> reference is noted, then <code>api2</code> drawing commences:<pre class=prettyprint>./bin/draw.dart
Instance of 'DrawingApi1' Increased refcount to 1
Instance of 'DrawingApi1' Increased refcount to 2
Instance of 'DrawingApi2' Increased refcount to 1
[DrawingApi1] circle at (1.0, 2.0) with radius 3.000
[DrawingApi1] circle at (0.0, 6.0) with radius 1.000
[DrawingApi2] circle at (2.0, 2.0) with radius 1.500
Instance of 'DrawingApi2' Increased refcount to 2
Instance of 'DrawingApi1' Decreased refcount to 1
Instance of 'DrawingApi2' Increased refcount to 3
Instance of 'DrawingApi1' Decreased refcount to 0
** Deleting no longer used Instance of 'DrawingApi1' **
[DrawingApi2] circle at (1.0, 2.0) with radius 3.000
[DrawingApi2] circle at (0.0, 6.0) with radius 1.000
[DrawingApi2] circle at (2.0, 2.0) with radius 1.500</pre>So it works, but Dart already had me covered with garbage collection. The effort is not a complete waste. I did clear up whatever C++ confusion I was suffering. Potentially more important, I have client code that can demonstrate sharing implementors such that garbage collection will reclaim them when they go unused. <br />
<br />
<i>Play with the code on DartPad: <a href="https://dartpad.dartlang.org/43585b1f6e0f1403fc5a">https://dartpad.dartlang.org/43585b1f6e0f1403fc5a</a>.</i><br />
<br />
<br />
<span style="color: #ccc">Day #79</span> <br />
<br />
<p class=bottom-chain-links><a href="http://japhr.blogspot.com/2016/01/sharing-implementors-is-easy-in-bridge.html">‹prev</a> | <a href="http://japhr.blogspot.com/2015/11/design-patterns-in-dart.html">My Chain</a> | <a href="http://japhr.blogspot.com/2016/01/the-bridge-pattern-with-websockets-and.html">next›</a> </p><script>
var b_links = document.getElementsByClassName('bottom-chain-links'),
t_links = document.getElementsByClassName('top-chain-links');
if (b_links.length == 1 && t_links.length == 1) {
t_links[0].innerHTML = b_links[0].innerHTML;
}
</script>Anonymoushttp://www.blogger.com/profile/00135361916531185929noreply@blogger.com0