<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>design-patterns &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/design-patterns/</link>
	<description>Feed of posts on WordPress.com tagged "design-patterns"</description>
	<pubDate>Sun, 20 Jul 2008 07:31:49 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Static Factories vs Public Constructors]]></title>
<link>http://phpimpact.wordpress.com/?p=308</link>
<pubDate>Thu, 17 Jul 2008 23:09:10 +0000</pubDate>
<dc:creator>phpimpact</dc:creator>
<guid>http://phpimpact.wordpress.com/?p=308</guid>
<description><![CDATA[Normally, creating an instance of a class is done by calling new, which calls the constructor.  Stat]]></description>
<content:encoded><![CDATA[<p>Normally, creating an instance of a class is done by calling new, which calls the constructor.  Static factory provides a static method that returns an instance of the class. So, you are using static factory instead of the constructor. Providing a static factory method instead of a public constructor has both advantages and disadvantages.</p>
<p>Advantages of static factories over constructors:</p>
<ul>
<li>Static factory instances have names but constructors do not.</li>
<li>Static factories can have two methods named differently but taking the same number and type of parameters.</li>
<li>Subclassing isn't possible but inheritance isn't always the best way to reuse code.</li>
</ul>
<p>Disadvantages of static factories over constructors:</p>
<ul>
<li>Can't be subclassed.</li>
<li>Poor naming conventions can make it hard to know what's going on.</li>
</ul>
<p>Dagfinn Reiersøl wrote an interesting post about this:</p>
<blockquote><p>I've never considered visibility restrictions important enough to be a major argument against those languages that have lacked them (PHP 4). So why would I be sceptical of public constructors? I got the idea after reading Joshua Kerievsky's book Refactoring to Patterns. One of his refactorings is called Replace Constructors with Creation Methods. In Java, unlike PHP, you can have multiple constructors that are distinguished only by the number and type of arguments. That may be practical sometimes, but as Kerievsky's example shows, it be more readable to have creation methods with different names instead. Which is what you have to anyway in PHP.</p></blockquote>
<p>Read More: <a href="http://www.reiersol.com/blog/1_php_in_action/archive/34_public_constructors_considered_harmful.html" target="_blank">Public constructors considered harmful</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Q-Patterns at SEETest 2008]]></title>
<link>http://debizqablog.wordpress.com/?p=73</link>
<pubDate>Thu, 10 Jul 2008 21:42:50 +0000</pubDate>
<dc:creator>debizyx</dc:creator>
<guid>http://debizqablog.wordpress.com/?p=73</guid>
<description><![CDATA[As I mentioned in my last post, the morning tutorial that I went to was by Vipul Kocher, co-founder]]></description>
<content:encoded><![CDATA[<p>As I mentioned in my last post, the morning tutorial that I went to was by <strong>Vipul Kocher</strong>, co-founder of <a title="PureTesting" href="http://www.puretesting.com/"><span style="color:#36769c;">Puretesting </span></a>and President of the <a title="Indian Testing Board" href="http://india.istqb.org/"><span style="color:#36769c;">Indian Testing Board</span></a>, who spoke about ”Q-Patterns". I went to that tutorial because I had heard the term Q-Patterns before, but didn't know what it actually meant. Since Vipul is the creator of the term, I thought I would go and hear about it "from the horse's mouth", so to speak.</p>
<p>I usually tell myself that if I come away from a conference having learnt one new thing, then it was a successful conference. If I come away having learnt one new thing per day, then it was a really excellent conference.</p>
<p>Well, I must admit that I wasn't expecting to get my 2-days' worth of new stuff at the first tutorial, but I did.</p>
<p>The idea behind Q-patterns (a.k.a. Questioning Patterns) is based on the idea behind <a title="design patterns" href="http://en.wikipedia.org/wiki/Design_Patterns">Design patterns</a>, i.e. <a title="Reuse" href="en.wikipedia.org/wiki/Reuse">REUSE</a>.</p>
<p>In this case, the reuse is of Test Cases. Q-patterns provide:</p>
<ul>
<li>A means to communicate experience</li>
<li>Aid in writing test cases</li>
<li>A mechanism for test case reuse</li>
<li>Aid in reviewing specifications and design</li>
</ul>
<p><strong>How do Q-patterns work?</strong></p>
<p>Q-patterns are a method of <strong>questioning</strong> the <strong>scenario</strong>. They are a set of interrelated questions, grouped together, that relate to some aspect of user or software requirements, and provide various alternatives to arrive at a solution.</p>
<p>Basically, if you can ask a set of questions about a particular topic in context X, you can reuse these questions for the same topic in context Y.</p>
<p><strong>Let's use an example: A combo box.</strong></p>
<p>This small element of software has a number of attributes that are irrespective of the application that the combo box is used in. If a test engineer knows what types of questions to ask about a combo box in one application (in order to get a full understanding of how it works), s/he can reuse those questions with respect to a combo box in another application.</p>
<p>What sort of questions can you ask about a combo box?</p>
<p>Usage: Data Source:</p>
<ul>
<li>is the combo-box populated with values by default?</li>
<li>what are the default values?</li>
<li>where does the combo-box get its values from?</li>
<li>what happens if the data source fails?</li>
</ul>
<p>Usage: Data addition/deletion/modification</p>
<ul>
<li>How are new values added? Deleted?</li>
<li>Can values be modified? How?</li>
<li>Where are newly added values displayed? Beginning, end or based on some type of sort?</li>
<li>Is it a single or multi select? If multiple, how is the select done?</li>
</ul>
<p>User Interace:</p>
<ul>
<li>Is the combo box wide enough to display the widest element? If not, is scrolling possible?</li>
<li>How is selection displayed?</li>
<li>Does the box drop down to reveal all entries? Or only some? How do you scroll vertically?</li>
<li>Can the box drop down and selections be made by using the keyboard? the mouse?</li>
</ul>
<p>Internationalization</p>
<ul>
<li>Does the box accept and display etended ASCII characters?</li>
<li>Does the box accept and display multi-byte characters?</li>
<li>Does the box accept right-to-left scripts (e.g. Hebrew, Arabic)?</li>
</ul>
<p>etc. etc. etc.</p>
<p>You get the picture.</p>
<p>These are a set of generic questions that need to have answers for any implementation of a combo box, and as such, they are reusable, and can be identified as part of the "Combo-box" Q-pattern.</p>
<p><strong>Exploratory Testing and Q-Patterns</strong></p>
<p>According to Vipul, one testing technique that can benefit in particular from Q-patterns is exploratory testing.</p>
<p>How come? Exploratory testing is based on a tester's experience. Using Q-patterns allows a tester to overcome the following challenges:</p>
<ul>
<li>exploratory testing is an individual's exercise
<ul>
<li>difficulty to pass on the knowledge gained</li>
<li>depends on the individual's skills</li>
</ul>
</li>
<li>exploratory testing involves designing tests and executing them at the same time
<ul>
<li>q-patterns can be created as you go along</li>
<li>q-patterns list various ways that things could work, and suggests various alternatives</li>
</ul>
</li>
</ul>
<p><strong>Some of the Problems with Q-Patterns</strong></p>
<p>There are a number of problems with Q-patterns. For example, you can easily end up with a huge set of questions (some of which may not be terribly useful) for a minute widget in the software. The <em><strong>chances</strong></em> are that for a large complex system, the list of questions will be unweildy, and there may be many duplicate questions in various Q-patterns.</p>
<p>Another possible issue is - who is going to write all these Q-patterns? It's all very well to identify a lot of generic bits and pieces, but is it worth writing the Q-patterns for them? A bit like reusable design and code - the first person designing or developing with reuse in mind doesn't actually benefit (and it's often more complicated to have reuse in mind from scratch), it's those who reuse the design, code or tests who benefit.</p>
<p>Vipul would like to have different companies work together to prepare a repository of Q-patterns, for all to reuse. Sort of like a "QWikipedia"  (<em>DebiZ - I just coined that term!</em>), but that just raises more issues: where would this repository reside? And what about each company's IP?</p>
<p>And last, but by no means least, how does one ensure that test engineers working with Q-patterns don't fall into the trap of stilted thinking?</p>
<p><strong>To Summarize</strong></p>
<p>I could go on quite a bit longer, but I don't intend to explain a 4-hour tutorial in a sinlge blog post!</p>
<p>Suffice to say that I came out of the tutorial with an understanding of Q-patterns, and some of their strengths and weaknesses.</p>
<p>If you have any thoughts about Q-patterns, as I've explained them, I'd be interested to hear your comments.</p>
<p><em>If you enjoyed this post, please consider subscribing to my RSS Feed, to keep up with all future updates, like the 2nd new thing I learnt from Vipul during this tutorial ...</em></p>
<p style="text-align:left;"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa100m02.png" alt="" /><a href="http://www.facebook.com/sharer.php?u=http://debizblog.wordpress.com/2008/07/11/q-patterns-at-seetest-2008/" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa101m02.png" alt="Add to Facebook" /></a><a href="http://digg.com/submit?phase=2&#38;url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa102m02.png" alt="Add to Digg" /></a><a href="http://del.icio.us/post?url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa103m02.png" alt="Add to Del.icio.us" /></a><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa104m02.png" alt="Add to Stumbleupon" /></a><a href="http://reddit.com/submit?url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa105m02.png" alt="Add to Reddit" /></a><a href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&#38;Description=&#38;Url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;Title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa106m02.png" alt="Add to Blinklist" /></a><a href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa107m02.png" alt="Add to Ma.gnolia" /></a><a href="http://www.technorati.com/faves?add=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa108m02.png" alt="Add to Technorati" /></a><a href="http://www.furl.net/storeIt.jsp?u=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;t=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa109m02.png" alt="Add to Furl" /></a><a href="http://www.newsvine.com/_wine/save?u=http%3A%2F%2Fdebizblog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;h=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa110m02.png" alt="Add to Newsvine" /></a><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa111m02.png" alt="" /></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Design Patterns for Implementing Application Preferences, Anyone?]]></title>
<link>http://looplabel.wordpress.com/?p=3</link>
<pubDate>Thu, 26 Jun 2008 20:15:37 +0000</pubDate>
<dc:creator>Anders Sandvig</dc:creator>
<guid>http://looplabel.wordpress.com/?p=3</guid>
<description><![CDATA[Configuration, preferences, settings, options, properties&mdash;whatever you call it&mdash;all but t]]></description>
<content:encoded><![CDATA[<p>Configuration, preferences, settings, options, properties&#8212;whatever you call it&#8212;all but the simplest applications allow the user to customize some of their functionality (and often appearance). But how do you implement this? Is there a best practices for programming application preferences in a clean, easily maintainable and well-structured way?</p>
<p>I recently began working on my <a href="http://sourceforge.net/projects/phex3d/">latest hobby project</a>, a desktop application for viewing photographs using (hardware-accelerated) 3D rendering, implemented in <a href="http://www.trolltech.no/">Qt</a> and <a href="http://www.opengl.org/">OpenGL</a>. It's been a while since using Qt, so I started small with a basic skeleton application, adding a menu bar, a toolbar and a status bar. I also implemented menu items to toggle the toolbar, the status bar and a full screen viewing mode.</p>
<p>The application doesn't do anything interesting yet, but even with this simple logic there are already several variables that could (and, in my opinion, should) be stored between sessions:</p>
<ul>
<li>Show/hide the toolbar?</li>
<li>Show/hide the status bar?</li>
<li>Show application in full screen, normal or maximized mode?</li>
<li>Size and position of main window.</li>
</ul>
<h4>The Configuration Object</h4>
<p>Most application frameworks (and some programming languages) provide utility classes for reading and writing persistent variables from and to configuration files or the system registry, like <a href="http://doc.trolltech.com/qsettings.html">QSettings</a>, <a href="http://docs.wxwidgets.org/stable/wx_wxconfigbase.html#wxconfigbase">wxConfig</a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/Properties.html">java.util.Properties</a>. The simplest way of providing persistence for application settings is to use these classes directly whenever needed. However, using them directly will often lead to duplication of code and possibly troublesome maintenance if access is spread across many modules and classes. Because of this&#8212;and other reasons I will mention later&#8212;I prefer to collect all variables and the code to read/write them in a separate configuration object.</p>
<p>For my simple Qt application, the code might look something like this:</p>
<p>[sourcecode language="cpp"]<br />
class Config {<br />
public:<br />
  bool maximized;<br />
  bool fullScreen;<br />
  bool showToolBar;<br />
  bool showStatusBar;<br />
  QString windowPos;</p>
<p>  void read() {<br />
    QSettings settings("phex3d", "phex3d");<br />
    maximized     = settings.value("maximized"     , false).toBool());<br />
    fullScreen    = settings.value("full_screen"   , false).toBool());<br />
    showToolBar   = settings.value("show_toolbar"  , false).toBool());<br />
    showStatusBar = settings.value("show_statusbar", true ).toBool());<br />
    windowPos     = settings.value("window_pos"    , ""   ).toString());<br />
  }</p>
<p>  void write() {<br />
    QSettings settings("phex3d", "phex3d");<br />
    settings.setValue("maximized"     , maximized);<br />
    settings.setValue("full_screen"   , fullScreen);<br />
    settings.setValue("show_toolbar"  , showToolBar);<br />
    settings.setValue("show_statusbar", showStatusBar);<br />
    settings.setValue("window_pos"    , windowPos);<br />
    settings.sync();<br />
  }<br />
};<br />
[/sourcecode]</p>
<p>By making an instance of the configuration object available as a global variable (or a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>, if that makes you sleep better), I can now easily reference persistent settings from anywhere in the application. For example, the event handler for toggling the toolbar could be something like this:</p>
<p>[sourcecode language="cpp"]<br />
void Window::toggleToolbar(void)<br />
{<br />
  bool visible = toolbar->isVisible();<br />
  config.showToolBar = !visible;<br />
  if (visible)<br />
    toolbar->hide();<br />
  else<br />
    toolbar->show();<br />
}<br />
[/sourcecode]</p>
<p>As long as I remember to call <code>Config::read()</code> on startup and <code>Config::write()</code> on exit, the settings will be saved and restored without any extra work needed.</p>
<h4>Centralized Information</h4>
<p>Although simple, the above solution will get somewhat messy if many variables are involved. For every new variable, extra code must be added to <code>read()</code> and <code>write()</code>. If we also think ahead a little, and take into account that these options will need to be exposed in a configuration dialog, allowing the user to change their values, we can recognize the need to associate some more information with each of them:</p>
<ul>
<li>The name of the option, typically used to identify it in a configuration file or the registry.</li>
<li>A short description of what the option means and what part of the application is affected by changing it. This text will typically be used as a label for the check box, edit field or other widget used to change the variable in the configuration dialog.</li>
<li>A more elaborate help text, suitable for use as a tool tip or in a separate help dialog.</li>
<li>The default value, useful if you want to allow the user to reset something to "factory defaults".</li>
<li>The data type of the option.</li>
</ul>
<p>You may wonder why the variable names and data types are relevant in this context&#8212;they could stay hardcoded, like before&#8212;but if you consider more advanced configuration interfaces, like the <a href="http://kb.mozillazine.org/Firefox_:_FAQs_:_About:config_Entries">Firefox about:config feature</a>, they can be very useful.</p>
<p>To collect all information about an option in one place, you might define an <code>Option</code> class looking something like this:</p>
<p>[sourcecode language="cpp"]<br />
class Option {<br />
public:<br />
  enum OptionType { INT, STRING };</p>
<p>private:<br />
  QString name;<br />
  QString desc;<br />
  QString help;<br />
  int defInt;<br />
  QString defString;<br />
  OptionType type;<br />
  void *value;</p>
<p>public:<br />
  Option(int *var, const QString &name, int def, const QString desc = "", const QString &help = "" ) {<br />
    this->type   = INT;<br />
    this->value  = var;<br />
    this->name   = name;<br />
    this->defInt = def;<br />
    this->desc   = desc;<br />
    this->help   = help;<br />
  }</p>
<p>  Option(QString *var, const QString &name, const QString &def, const QString desc = "", const QString &help = "" ) {<br />
    this->type      = STRING;<br />
    this->value     = var;<br />
    this->name      = name;<br />
    this->defString = def;<br />
    this->desc      = desc;<br />
    this->help      = help;<br />
  }</p>
<p>  const QString &getName() { return name; }<br />
  const QString &getDescription() { return desc; }<br />
  const QString &getHelpText() { return help; }</p>
<p>  OptionType getType(void) { return type; }<br />
  int getInt(void) { return *((int *) value); }<br />
  int getDefaultInt(void) { return defInt; }<br />
  const QString &getString(void) { return *((QString *) value); }<br />
  const QString &getDefaultString(void) { return defString; }</p>
<p>  void setInt(int value) { *((int *) this->value) = value; }<br />
  void setString(const QString &value) { *((QString *) this->value) = value; }<br />
};<br />
[/sourcecode]</p>
<p>If you are wondering why the option value is stored as a pointer and not a local variable inside the <code>Option</code> class, I did this because I wanted them to reference the corresponding class variables in the configuration object, thus allowing me to continue accessing hem directly elsewhere in my application. It's kind of a hack, I know, but it works. If you don't like it, you can always use the <code>get*()</code> functions instead. Also, if you know a better solution, or how to solve the type info situation with templates, please share.</p>
<p>Now that we have all the information wee need about each option wrapped in a class, we can add a list of <code>Option</code> instances in our <code>Config</code> class to simplify and generalize the <code>read()</code> and <code>write()</code> implementations. The new <code>Config</code> class might look something like this:</p>
<p>[sourcecode language="cpp"]<br />
class Config {<br />
public:<br />
  int maximized;<br />
  int fullScreen;<br />
  int showToolBar;<br />
  int showStatusBar;<br />
  QString windowPos;<br />
  Option *_maximized;<br />
  Option *_fullScreen;<br />
  Option *_showToolBar;<br />
  Option *_showStatusBar;<br />
  Option *_windowPos;<br />
  QList<Option *> option_list;</p>
<p>  Config() {<br />
    settings = new QSettings("phex3d", "phex3d");</p>
<p>    _maximized     = addOption<int>    ("maximized"     , &maximized    , true );<br />
    _fullScreen    = addOption<int>    ("fullscreen"    , &fullScreen   , false);<br />
    _showToolBar   = addOption<int>    ("show_toolbar"  , &showToolBar  , false);<br />
    _showStatusBar = addOption<int>    ("show_statusbar", &showStatusBar, true );<br />
    _windowPos     = addOption<QString>("window_pos"    , &windowPos    , ""   );<br />
  }</p>
<p>  ~Config() {<br />
    for (QList<Option *>::Iterator i = option_list.begin(); i < option_list.end(); i++)<br />
      delete *i;</p>
<p>    delete settings;<br />
  }</p>
<p>  template <typename T><br />
  Option *addOption(const QString &name, T *var, T value, const QString &desc = "", const QString &help = "" ) {<br />
    Option *option = new Option(var, name, value, desc, help);<br />
    option_list.append(option);<br />
    return option;<br />
  }</p>
<p>  void read() {<br />
    for (QList<Option *>::Iterator i = option_list.begin(); i < option_list.end(); i++) {<br />
      Option *option = *i;<br />
      if (option->getType() == Option::INT) {<br />
        QVariant value = settings->value(option->getName(), option->getDefaultInt());<br />
        option->setInt(value.toInt());<br />
      }<br />
      else {<br />
        QVariant value = settings->value(option->getName(), option->getDefaultString());<br />
        option->setString(value.toString());<br />
      }<br />
    }<br />
  }</p>
<p>  void write() {<br />
    for (QList<Option *>::Iterator i = option_list.begin(); i < option_list.end(); i++) {<br />
      Option *option = *i;<br />
      if (option->getType() == Option::INT)<br />
        settings->setValue(option->getName(), option->getInt());<br />
      else<br />
        settings->setValue(option->getName(), option->getString());<br />
    }<br />
    settings->sync();<br />
  }</p>
<p>private:<br />
  QSettings *settings;<br />
};<br />
[/sourcecode]</p>
<h4>Outstanding Issues</h4>
<p>The above solution works fine for my current needs in the application, but as we all know, needs change over time. I can already think of several outstanding issues that are not covered by this design, which might be needed in the future.</p>
<p>It would be useful to provide a list of valid values for each option. For example, if an integer option can only be between 1 and 100, this information should also be stored in the <code>Option</code> object. The same with text to display in a drop-down list or for auto-completing commonly used values as they are being entered in an edit field. If advanced validation or many different validation algorithms are used, this might be better solved by adding a reference to a <a href="http://doc.trolltech.com/qvalidator.html">validation object</a> responsible for validating values for a given option.</p>
<p>As time passes, code is typically rewritten and programs restructured. This can eventually lead to the need, or simply the desire, to also rename options. For example, if the option <code>window_pos</code> describes the main window position, you may want to rename it to <code>main.window_pos</code> when more windows are added to the application. The issue can also arise when option names are automatically generated from class names (which is quite common for Java properties). When the name of the class changes, so will the option name. For this reason, it could be useful if the <code>Option</code> class was extended to provide a list of name aliases. The <code>read()</code> function could then be updated to use the value from an alias if found, but <code>write()</code> would only save it under the new name.</p>
<p>Another disadvantage of my simple design is that the <code>Config</code> class must know about all the options in the application, and therefore could get a tighter coupling with the various application modules than you might prefer. If your application supports custom extensions via plug-ins, it might be useful to implement functionality to add options to the <code>Config</code> object at run-time. For options that are added this way it will also be useful to provide a lookup function for retrieving the <code>Option</code> object based on name, i.e. by storing the objects in a map keyed by the option name as it was provided when the option was added.</p>
<p>I am likely to discover even more issues once I start implementing the configuration dialogs, but at least now I have an application that remembers where I left the window. </p>
<p>Please share your thoughts on this. Any feedback is appreciated.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The best code is very shy]]></title>
<link>http://phpimpact.wordpress.com/?p=232</link>
<pubDate>Tue, 17 Jun 2008 23:33:25 +0000</pubDate>
<dc:creator>phpimpact</dc:creator>
<guid>http://phpimpact.wordpress.com/?p=232</guid>
<description><![CDATA[The best code is very shy. Like a four-year old hiding behind a mothers skirt, code should not rev]]></description>
<content:encoded><![CDATA[<p>The best code is very shy. Like a four-year old hiding behind a mothers skirt, code should not reveal too much of itself and should not be too nosy into others affairs. But you might find that your shy code grows up too fast, shedding its demure shyness in favor of wild promiscuity. When code isn't shy, you'll get unwanted coupling.</p>
<p><a href="http://pragprog.com/the-pragmatic-programmer" target="_blank">The Pragmatic Programmers</a>, Andy Hunt &#38; Dave Thomas.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[C# Design Pattern: Command]]></title>
<link>http://codeaday.wordpress.com/?p=6</link>
<pubDate>Tue, 17 Jun 2008 14:12:28 +0000</pubDate>
<dc:creator>nonapp</dc:creator>
<guid>http://codeaday.wordpress.com/?p=6</guid>
<description><![CDATA[
 // Command pattern -- Real World example


using System;


using System.Collections;

namespace Co]]></description>
<content:encoded><![CDATA[<div class="sourcecode">
<pre><span style="color:green;"> // Command pattern -- Real World example</span></pre>
</div>
<div class="sourcecode">
<pre><span style="color:blue;">using</span> System;</pre>
</div>
<div class="sourcecode">
<pre><span style="color:blue;">using</span> System.Collections;</pre>
</div>
<pre><span style="color:blue;">namespace</span> CommandPattern
{</pre>
<pre><span style="color:green;"> // MainApp test application </span></pre>
<pre><span style="color:blue;"> class</span> MainApp
 {
<span style="color:blue;">  static</span> <span style="color:blue;">void</span> Main()
  {
<span style="color:green;">   // Create user and let her compute </span>
   User user = <span style="color:blue;">new</span> User();</pre>
<pre>   user.Compute('+', 100);
   user.Compute('-', 50);
   user.Compute('*', 10);
   user.Compute('/', 2);</pre>
<pre><span style="color:green;">   // Undo 4 commands </span>
   user.Undo(4);</pre>
<pre><span style="color:green;">   // Redo 3 commands </span>
   user.Redo(3);</pre>
<pre><span style="color:green;">   // Wait <span style="color:green;">for</span> user </span>
   Console.Read();
  }
 }</pre>
<pre><span style="color:green;"> // "Command" </span></pre>
<pre><span style="color:blue;"> abstract</span> <span style="color:blue;">class</span> Command
 {
<span style="color:blue;">  public</span> <span style="color:blue;">abstract</span> <span style="color:blue;">void</span> Execute();
<span style="color:blue;">  public</span> <span style="color:blue;">abstract</span> <span style="color:blue;">void</span> UnExecute();
 }</pre>
<pre><span style="color:green;"> // "ConcreteCommand" </span></pre>
<pre><span style="color:blue;"> class</span> CalculatorCommand : Command
 {
<span style="color:blue;">  char</span> @operator;
<span style="color:blue;">  int</span> operand;
  Calculator calculator;</pre>
<pre><span style="color:green;">  // Constructor </span>
<span style="color:blue;">  public</span> CalculatorCommand(Calculator calculator,
<span style="color:blue;">  char</span> @operator, <span style="color:blue;">int</span> operand)
  {
<span style="color:blue;">   this</span>.calculator = calculator;
<span style="color:blue;">   this</span>.@operator  = @operator;
<span style="color:blue;">   this</span>.operand    = operand;
  }</pre>
<pre><span style="color:blue;">  public</span> <span style="color:blue;">char</span> Operator
  {
<span style="color:blue;">   set</span>{ @operator = <span style="color:blue;">value</span>; }
  }</pre>
<pre><span style="color:blue;">  public</span> <span style="color:blue;">int</span> Operand
  {
<span style="color:blue;">   set</span>{ operand = <span style="color:blue;">value</span>; }
  }</pre>
<pre><span style="color:blue;">  public</span> <span style="color:blue;">override</span> <span style="color:blue;">void</span> Execute()
  {
   calculator.Operation(@operator, operand);
  }</pre>
<pre><span style="color:blue;">  public</span> <span style="color:blue;">override</span> <span style="color:blue;">void</span> UnExecute()
  {
   calculator.Operation(Undo(@operator), operand);
  }</pre>
<pre><span style="color:green;">  // Private helper function </span>
<span style="color:blue;">  private</span> <span style="color:blue;">char</span> Undo(<span style="color:blue;">char</span> @operator)
  {
<span style="color:blue;">   char</span> undo;
<span style="color:blue;">   switch</span>(@operator)
   {
<span style="color:blue;">    case</span> '+': undo = '-'; <span style="color:blue;">break</span>;
<span style="color:blue;">    case</span> '-': undo = '+'; <span style="color:blue;">break</span>;
<span style="color:blue;">    case</span> '*': undo = '/'; <span style="color:blue;">break</span>;
<span style="color:blue;">    case</span> '/': undo = '*'; <span style="color:blue;">break</span>;
<span style="color:blue;">    default</span> : undo = ' '; <span style="color:blue;">break</span>;
   }
<span style="color:blue;">  return</span> undo;
  }
 }</pre>
<pre><span style="color:green;"> // "Receiver" </span></pre>
<pre><span style="color:blue;"> class</span> Calculator
 {
<span style="color:blue;"> private</span> <span style="color:blue;">int</span> curr = 0;</pre>
<pre><span style="color:blue;"> public</span> <span style="color:blue;">void</span> Operation(<span style="color:blue;">char</span> @operator, <span style="color:blue;">int</span> operand)
 {
<span style="color:blue;"> switch</span>(@operator)
 {
<span style="color:blue;"> case</span> '+': curr += operand; <span style="color:blue;">break</span>;
<span style="color:blue;"> case</span> '-': curr -= operand; <span style="color:blue;">break</span>;
<span style="color:blue;"> case</span> '*': curr *= operand; <span style="color:blue;">break</span>;
<span style="color:blue;"> case</span> '/': curr /= operand; <span style="color:blue;">break</span>;
 }
 Console.WriteLine(
 "Current value = {0,3} (following {1} {2})",
 curr, @operator, operand);
 }
 }</pre>
<pre><span style="color:green;"> // "Invoker" </span></pre>
<pre><span style="color:blue;"> class</span> User
 {
<span style="color:green;"> // Initializers </span>
<span style="color:blue;"> private</span> Calculator calculator = <span style="color:blue;">new</span> Calculator();
<span style="color:blue;"> private</span> ArrayList commands = <span style="color:blue;">new</span> ArrayList();</pre>
<pre><span style="color:blue;"> private</span> <span style="color:blue;">int</span> current = 0;</pre>
<pre><span style="color:blue;"> public</span> <span style="color:blue;">void</span> Redo(<span style="color:blue;">int</span> levels)
 {
 Console.WriteLine("\n---- Redo {0} levels ", levels);
<span style="color:green;"> // Perform redo operations </span>
<span style="color:blue;"> for</span> (<span style="color:blue;">int</span> i = 0; i &#60; levels; i++)
 {
<span style="color:blue;"> if</span> (current &#60; commands.Count - 1)
 {
 Command command = commands[current++] <span style="color:blue;">as</span> Command;
 command.Execute();
 }
 }
 }</pre>
<pre><span style="color:blue;"> public</span> <span style="color:blue;">void</span> Undo(<span style="color:blue;">int</span> levels)
 {
 Console.WriteLine("\n---- Undo {0} levels ", levels);
<span style="color:green;"> // Perform undo operations </span>
<span style="color:blue;"> for</span> (<span style="color:blue;">int</span> i = 0; i &#60; levels; i++)
 {
<span style="color:blue;"> if</span> (current &#62; 0)
 {
 Command command = commands[--current] <span style="color:blue;">as</span> Command;
 command.UnExecute();
 }
 }
 }</pre>
<pre><span style="color:blue;"> public</span> <span style="color:blue;">void</span> Compute(<span style="color:blue;">char</span> @operator, <span style="color:blue;">int</span> operand)
 {
<span style="color:green;"> // Create command operation and execute it </span>
 Command command = <span style="color:blue;">new</span> CalculatorCommand(
 calculator, @operator, operand);
 command.Execute();</pre>
<pre><span style="color:green;"> // Add command to undo list </span>
 commands.Add(command);
 current++;
 }
 }
}</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Padrões de Projeto]]></title>
<link>http://wanc.wordpress.com/?p=57</link>
<pubDate>Thu, 17 Jul 2008 15:15:08 +0000</pubDate>
<dc:creator>wanc</dc:creator>
<guid>http://wanc.wordpress.com/?p=57</guid>
<description><![CDATA[O que é, o que é: usamos  sem saber,  apanhamos pra aprender e sofremos por esquecer? É isto aí:]]></description>
<content:encoded><![CDATA[<p><a href="http://wanc.wordpress.com/files/2008/07/atlantikdesigner.png"><img class="alignleft size-medium wp-image-66" src="http://wanc.wordpress.com/files/2008/07/atlantikdesigner.png?w=128" alt="" width="108" height="108" /></a>O que é, o que é: usamos  sem saber,  apanhamos pra aprender e sofremos por esquecer? É isto aí: padrões de projeto!</p>
<p>Olhando meus códigos, quantas vezes usei os padrões singleton, command e interpreter sem ter a mínima idéia do que eram. O conhecimento deles teria me poupado muito tempo. Quem me despertou pra esta realidade foi o excelente livro <strong>Php Profissional</strong> dos autores Alexandre Altair e Maurício Nascimento.</p>
<p>Mas o motivo desta  rapidinha é a descoberta de um  site muito bom sobre este assunto, o   <a title="Design Patterns" href="http://sourcemaking.com/design_patterns/">Design Patterns</a> .  O site , em inglês,  agrupa por tipo  e descreve cada  padrão de forma sucinta e didática. Os exemplos fornecidos  em diversas linguagens, incluindo o Object Pascal e PHP, são práticos e úteis.</p>
<p>Faça uma visita e aproveite sua dose de padrões de projeto. Apenas cuidado pra não pegar a febre e sair aplicando padrões num programa Alô Mundo. Até a próxima!</p>
<p><a href="http://sourcemaking.com/design_patterns/"><strong>Design Patterns</strong></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[W obronie singletonu]]></title>
<link>http://sakowicz.wordpress.com/?p=348</link>
<pubDate>Wed, 16 Jul 2008 09:32:02 +0000</pubDate>
<dc:creator>sakowicz</dc:creator>
<guid>http://sakowicz.wordpress.com/?p=348</guid>
<description><![CDATA[Singleton jest jednym ze wzorców projektowych. Jego zadaniem jest zapewnienie istnienia tylko jedne]]></description>
<content:encoded><![CDATA[<p>Singleton jest jednym ze wzorców projektowych. Jego zadaniem jest zapewnienie istnienia tylko jednej instancji danej klasy i umożliwienie globalnego dostępu do niej. W C# przykładowo może wyglądać to tak:</p>
<div style="border:1px solid gray;overflow:auto;font-size:8pt;width:97.5%;cursor:text;max-height:200px;line-height:12pt;font-family:consolas,'Courier New',courier,monospace;background-color:#f4f4f4;margin:20px 0 10px;padding:4px;">
<pre style="overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;font-family:consolas,'Courier New',courier,monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">sealed</span> SingletonClass
{
  <span style="color:#0000ff;">private</span> SingletonClass() {}

  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">readonly</span> SingletonClass Instance = <span style="color:#0000ff;">new</span> SingletonClass();
}</pre>
</div>
<p>Wiele osób uważa, że stosowanie singletonów jest przejawem złej architektury gdyż wprowadzają one ścisłe powiązania między poszczególnymi klasami, co z kolei utrudnia pisanie testów. W zupełności się z tym zgadzam, jednak, jeśli mam wybierać pomiędzy zmiennymi globalnymi to z dwojga złego wolę wykorzystać singleton. Przynajmniej pomoże pogrupować 'zmienne' w jakąś logiczną strukturę.</p>
<p>Poza tym nie tak naprawdę singleton'ów, nie da się całkowicie uniknąć, z dwóch powodów:</p>
<ul>
<li>Pomimo tego, co niektórzy twierdzą, istnieją sytuacje wymagające ich zastosowania jak na przykład interakcja z hardwarem.</li>
<li>Wydajność - i nie chodzi mi tu o aplikacje serwerowe itp. - ale te mniejsze pracujące przykładowo na urządzeniach przenośnych.</li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Layer SuperType]]></title>
<link>http://silentintellect.wordpress.com/?p=9</link>
<pubDate>Mon, 14 Jul 2008 15:28:49 +0000</pubDate>
<dc:creator>Asif Shahzad</dc:creator>
<guid>http://silentintellect.wordpress.com/?p=9</guid>
<description><![CDATA[Layer SuperType Design Pattern eliminates code redundancy. and provide better to access to common fu]]></description>
<content:encoded><![CDATA[<p>Layer SuperType Design Pattern eliminates code redundancy. and provide better to access to common functionality.</p>
<p>Some time we produce too redundant code. For example implementing Data Access Objects and writing the basic functionality code in each DAO (when using different DAO for each entity). By using Layer SuperType we can eliminate such problem.</p>
<p>For example in one of my (Hibernate and Struts based) project, I am using the Layer SuperType. I have written a class named AbstractDAO (which is basically super layer of Layer SuperType) as follow:</p>
<pre><span style="color:#993300;">public class AbstractDao {

protected static Session session;
protected static Transaction tx;

 public AbstractDao() {
     HibernateSessionFactory.buildIfNeeded();</span><span style="color:#993300;">
}

protected void save(Object obj) {
 try {

     startOperation();
     session.save(obj);
     tx.commit();

     } catch (HibernateException e) {
       handleException(e);

     } finally {
       HibernateSessionFactory.closeSession();
     }</span><span style="color:#993300;">
} 

public void saveOrUpdate(Object obj) {
 try {

     startOperation();</span><span style="color:#993300;">
     session.saveOrUpdate(obj);
     tx.commit();

     } catch (HibernateException e) {
       handleException(e);

     } finally {
       HibernateSessionFactory.closeSession();
     }
}</span></pre>
<p>and other methods that need to be come under Super Layer.</p>
<p>Now code of DAOs for each entity is extrememly minimized, and you dont need to make explicit type casts while calling DAO's methods. And the most important thing is, you don't need to write the exception handing logic in DAOs which is very time/space taking activity.</p>
<p>Now I show you one DAO which uses the Layer SuperType.</p>
<pre><span style="color:#993300;">public class WidgetDAO  extends AbstractDao{

public WidgetDAO() {
     super(); </span><span style="color:#993300;">
}

public Widget getWidget(Integer id){

 Widget widget = new Widget();
 widget = (Widget)super.objQuery("from Widget w where w.id=" + id);
 return widget;

}

public void addorUpdateWidget(Widget widget){

  super.saveOrUpdate(widget);</span></pre>
<pre><span style="color:#993300;">}
}

</span></pre>
<p>Now i can get a widget using:</p>
<pre><span style="color:#993300;">Widget wgt = new WidgetDAO().getWidget(1); // here 1 is Widget ID

</span></pre>
<p>You see how Layer SuperTypes makes the application code simple, clean, and minimized.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[More PureMVC Links]]></title>
<link>http://algorithmist.wordpress.com/?p=144</link>
<pubDate>Mon, 14 Jul 2008 12:02:33 +0000</pubDate>
<dc:creator>algorithmist</dc:creator>
<guid>http://algorithmist.wordpress.com/?p=144</guid>
<description><![CDATA[As a follow-on to my previous post listing some PureMVC links, here are some more I&#8217;ve come ac]]></description>
<content:encoded><![CDATA[<p>As a follow-on to <a href="http://algorithmist.wordpress.com/2008/01/22/puremvc-links/" target="_blank">my previous post</a> listing some PureMVC links, here are some more I've come across that may be of interest to PureMVC users.  Enjoy.</p>
<p><a href="http://www.theflexshow.com/blog/index.cfm/2008/1/30/The-Flex-Show--Episode-33-PureMVC-Framework" target="_blank">Interview with Cliff Hall</a>, creator of PureMVC.</p>
<p><a href="http://puremvc.org/component/option,com_wrapper/Itemid,160/" target="_blank">The Manifold Project</a>.</p>
<p><a href="http://www.techper.net/2008/06/09/patterns-of-gui-architecture-in-cairngorm-and-puremvc/" target="_blank">Discussion of Cairngorm and PureMVC</a> as patterns of GUI architecture.</p>
<p><a href="http://blog.log2e.com/2008/05/19/getting-started-with-the-puremvc-startup-manager-introduction/" target="_blank">PureMVC Startup Manager</a>.</p>
<p><a href="http://revisual.co.uk/?p=38" target="_blank">PureMVC Asset Loader example</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Observer Design Pattern]]></title>
<link>http://mhashem.wordpress.com/?p=29</link>
<pubDate>Sun, 13 Jul 2008 14:32:41 +0000</pubDate>
<dc:creator>mhashem</dc:creator>
<guid>http://mhashem.wordpress.com/?p=29</guid>
<description><![CDATA[I&#8217;ll talk now a little about the observer design pattern, or i can call it the listener design]]></description>
<content:encoded><![CDATA[<p>I'll talk now a little about the observer design pattern, or i can call it the listener design pattern.</p>
<p>the Observer design pattern define a one-to-many relationship between objects that when an object status changes the other dependent objects be notified.</p>
<p>the idea is : there is an object that has a peace of information, many other objects interested in knowing when its state changes.</p>
<p>the way to handle this is creating a way to allow dependent objects to register to be notified when the status changes. here is an imagination of how you can model this situation:</p>
[caption id="attachment_32" align="alignnone" width="300" caption="Class Diagram"]<a href="http://mhashem.files.wordpress.com/2008/07/observerpattern.png"><img class="size-medium wp-image-32" src="http://mhashem.wordpress.com/files/2008/07/observerpattern.png?w=300" alt="Class Diagram" width="300" height="216" /></a>[/caption]
<p>From the diagram you can see that we created to interfaces one for the subject object which will contains the information or status other objects needed to be aware about. the Subject interface has 3 methods registerObserver, deregisterObserver and notifyObservers.</p>
<p>registerObserver(): takes an Observer object as a argument and add this object to an internal arraylist or whatever you choose to keep all registered observers on it.</p>
<p>deregisterObserver(): takes an Observer object as a argument and and remove this object from the observers arraylist.</p>
<p>notifyObservers(): call the update() method on all observers exists on the observers arraylist and send the new status(s) as arguments.</p>
<p>The Observer Interface contains one method update()</p>
<p>update(): this method takes the status or information it interested in as argument(s).</p>
<p>so in pref. an subject object has information some observer objects interested in, so the observer objects register themselves on the subject object by calling the register method.</p>
<p>when the data in the subject object changed the notifyObservers method call and it send the new information by calling update method in all registered observers.</p>
<p>when an observer object decided to stop receiving updates it deregister himself from the subject object by calling deregister method() on the subject object.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Why are open source frameworks important - (Part 2)?]]></title>
<link>http://mmwaikar.wordpress.com/?p=106</link>
<pubDate>Fri, 11 Jul 2008 22:30:15 +0000</pubDate>
<dc:creator>mmwaikar</dc:creator>
<guid>http://mmwaikar.wordpress.com/?p=106</guid>
<description><![CDATA[Those who&#8217;ve read my earlier post on the above topic, know that it was a second hand experienc]]></description>
<content:encoded><![CDATA[<p>Those who've read my <a title="Why are open source frameworks important?" href="http://mmwaikar.wordpress.com/2008/04/11/why-are-open-source-frameworks-important/" target="_blank">earlier post</a> on the above topic, know that it was a second hand experience.</p>
<p>However, after finishing my lsat project at Pitney Bowes, I now have first hand experience of how sweet your code becomes when you follow principles like IoC, AOP, Transaction Management (using attributes and AOP). Also this is the first time, I've used interfaces so heavily.</p>
<p>Have a lookat this <a href="http://mmwaikar.files.wordpress.com/2008/07/dppconnector.ppt">DPPConnector</a> presentation and decide for yourself if this code is sweet or not.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Q-Patterns at SEETest 2008]]></title>
<link>http://debizqablog.wordpress.com/?p=73</link>
<pubDate>Thu, 10 Jul 2008 21:42:50 +0000</pubDate>
<dc:creator>debizyx</dc:creator>
<guid>http://debizqablog.wordpress.com/?p=73</guid>
<description><![CDATA[As I mentioned in my last post, the morning tutorial that I went to was by Vipul Kocher, co-founder]]></description>
<content:encoded><![CDATA[<p>As I mentioned in my last post, the morning tutorial that I went to was by <strong>Vipul Kocher</strong>, co-founder of <a title="PureTesting" href="http://www.puretesting.com/"><span style="color:#36769c;">Puretesting </span></a>and President of the <a title="Indian Testing Board" href="http://india.istqb.org/"><span style="color:#36769c;">Indian Testing Board</span></a>, who spoke about ”Q-Patterns". I went to that tutorial because I had heard the term Q-Patterns before, but didn't know what it actually meant. Since Vipul is the creator of the term, I thought I would go and hear about it "from the horse's mouth", so to speak.</p>
<p>I usually tell myself that if I come away from a conference having learnt one new thing, then it was a successful conference. If I come away having learnt one new thing per day, then it was a really excellent conference.</p>
<p>Well, I must admit that I wasn't expecting to get my 2-days' worth of new stuff at the first tutorial, but I did.</p>
<p>The idea behind Q-patterns (a.k.a. Questioning Patterns) is based on the idea behind <a title="design patterns" href="http://en.wikipedia.org/wiki/Design_Patterns">Design patterns</a>, i.e. <a title="Reuse" href="en.wikipedia.org/wiki/Reuse">REUSE</a>.</p>
<p>In this case, the reuse is of Test Cases. Q-patterns provide:</p>
<ul>
<li>A means to communicate experience</li>
<li>Aid in writing test cases</li>
<li>A mechanism for test case reuse</li>
<li>Aid in reviewing specifications and design</li>
</ul>
<p><strong>How do Q-patterns work?</strong></p>
<p>Q-patterns are a method of <strong>questioning</strong> the <strong>scenario</strong>. They are a set of interrelated questions, grouped together, that relate to some aspect of user or software requirements, and provide various alternatives to arrive at a solution.</p>
<p>Basically, if you can ask a set of questions about a particular topic in context X, you can reuse these questions for the same topic in context Y.</p>
<p><strong>Let's use an example: A combo box.</strong></p>
<p>This small element of software has a number of attributes that are irrespective of the application that the combo box is used in. If a test engineer knows what types of questions to ask about a combo box in one application (in order to get a full understanding of how it works), s/he can reuse those questions with respect to a combo box in another application.</p>
<p>What sort of questions can you ask about a combo box?</p>
<p>Usage: Data Source:</p>
<ul>
<li>is the combo-box populated with values by default?</li>
<li>what are the default values?</li>
<li>where does the combo-box get its values from?</li>
<li>what happens if the data source fails?</li>
</ul>
<p>Usage: Data addition/deletion/modification</p>
<ul>
<li>How are new values added? Deleted?</li>
<li>Can values be modified? How?</li>
<li>Where are newly added values displayed? Beginning, end or based on some type of sort?</li>
<li>Is it a single or multi select? If multiple, how is the select done?</li>
</ul>
<p>User Interace:</p>
<ul>
<li>Is the combo box wide enough to display the widest element? If not, is scrolling possible?</li>
<li>How is selection displayed?</li>
<li>Does the box drop down to reveal all entries? Or only some? How do you scroll vertically?</li>
<li>Can the box drop down and selections be made by using the keyboard? the mouse?</li>
</ul>
<p>Internationalization</p>
<ul>
<li>Does the box accept and display etended ASCII characters?</li>
<li>Does the box accept and display multi-byte characters?</li>
<li>Does the box accept right-to-left scripts (e.g. Hebrew, Arabic)?</li>
</ul>
<p>etc. etc. etc.</p>
<p>You get the picture.</p>
<p>These are a set of generic questions that need to have answers for any implementation of a combo box, and as such, they are reusable, and can be identified as part of the "Combo-box" Q-pattern.</p>
<p><strong>Exploratory Testing and Q-Patterns</strong></p>
<p>According to Vipul, one testing technique that can benefit in particular from Q-patterns is exploratory testing.</p>
<p>How come? Exploratory testing is based on a tester's experience. Using Q-patterns allows a tester to overcome the following challenges:</p>
<ul>
<li>exploratory testing is an individual's exercise
<ul>
<li>difficulty to pass on the knowledge gained</li>
<li>depends on the individual's skills</li>
</ul>
</li>
<li>exploratory testing involves designing tests and executing them at the same time
<ul>
<li>q-patterns can be created as you go along</li>
<li>q-patterns list various ways that things could work, and suggests various alternatives</li>
</ul>
</li>
</ul>
<p><strong>Some of the Problems with Q-Patterns</strong></p>
<p>There are a number of problems with Q-patterns. For example, you can easily end up with a huge set of questions (some of which may not be terribly useful) for a minute widget in the software. The <em><strong>chances</strong></em> are that for a large complex system, the list of questions will be unweildy, and there may be many duplicate questions in various Q-patterns.</p>
<p>Another possible issue is - who is going to write all these Q-patterns? It's all very well to identify a lot of generic bits and pieces, but is it worth writing the Q-patterns for them? A bit like reusable design and code - the first person designing or developing with reuse in mind doesn't actually benefit (and it's often more complicated to have reuse in mind from scratch), it's those who reuse the design, code or tests who benefit.</p>
<p>Vipul would like to have different companies work together to prepare a repository of Q-patterns, for all to reuse. Sort of like a "QWikipedia"  (<em>DebiZ - I just coined that term!</em>), but that just raises more issues: where would this repository reside? And what about each company's IP?</p>
<p>And last, but by no means least, how does one ensure that test engineers working with Q-patterns don't fall into the trap of stilted thinking?</p>
<p><strong>To Summarize</strong></p>
<p>I could go on quite a bit longer, but I don't intend to explain a 4-hour tutorial in a sinlge blog post!</p>
<p>Suffice to say that I came out of the tutorial with an understanding of Q-patterns, and some of their strengths and weaknesses.</p>
<p>If you have any thoughts about Q-patterns, as I've explained them, I'd be interested to hear your comments.</p>
<p><em>If you enjoyed this post, please consider subscribing to my RSS Feed, to keep up with all future updates, like the 2nd new thing I learnt from Vipul during this tutorial ...</em></p>
<p>Bookmark me at: <img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa200m04.png" alt="" /><a href="http://www.facebook.com/sharer.php?u=http://debizqablog.wordpress.com/2008/07/11/q-patterns-at-seetest-2008/" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa201m04.png" alt="Add to Facebook" /></a><a href="http://digg.com/submit?phase=2&#38;url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa202m04.png" alt="Add to Digg" /></a><a href="http://del.icio.us/post?url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa203m04.png" alt="Add to Del.icio.us" /></a><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa204m04.png" alt="Add to Stumbleupon" /></a><a href="http://reddit.com/submit?url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa205m04.png" alt="Add to Reddit" /></a><a href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&#38;Description=&#38;Url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;Title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa206m04.png" alt="Add to Blinklist" /></a><a href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;title=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa207m04.png" alt="Add to Ma.gnolia" /></a><a href="http://www.technorati.com/faves?add=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa208m04.png" alt="Add to Technorati" /></a><a href="http://www.furl.net/storeIt.jsp?u=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;t=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa209m04.png" alt="Add to Furl" /></a><a href="http://www.newsvine.com/_wine/save?u=http%3A%2F%2Fdebizqablog.wordpress.com%2F2008%2F07%2F11%2Fq-patterns-at-seetest-2008%2F&#38;h=Q-Patterns%20at%20SEETest%202008" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa210m04.png" alt="Add to Newsvine" /></a><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsa211m04.png" alt="" /></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Palavras mais buscadas quando o assunto é design:]]></title>
<link>http://desiginer.wordpress.com/?p=3</link>
<pubDate>Thu, 10 Jul 2008 16:25:02 +0000</pubDate>
<dc:creator>blogymodas</dc:creator>
<guid>http://desiginer.wordpress.com/?p=3</guid>
<description><![CDATA[100 design, 20 20 design, 2020 design, 3d designer, 3d home architect design, a design, abc design, ]]></description>
<content:encoded><![CDATA[<p>100 design, 20 20 design, 2020 design, 3d designer, 3d home architect design, a design, abc design, adobe creative suite 3 design premium, adobe cs3 design premium, adobe design, adobe designer, adobe in design, alligator flash designer, altium designer, arc design, art design, audio design, best design, blog design, business card designer, business card designer plus, by design, cad design, cake design, cake designer, car design, character design, cover design, cover designer, creative design, cs3 design premium, curso de design, curso design, cybermotion 3d designer, database design, database designer, db design, db designer, design, design 3d, design center, design com, design de interiores, design digital, design gallery, design games, design grafico, design gráfico, design hotels, design magazine, design on, design pattern, design patterns, design pdf, design photoshop, design portfolio, design powerpoint, design school, design sites, design studio, designer, designer com, designer grafico, designer gráfico, designer sound fx, designer whey, designer whey protein, designers, designers guild, digital designer, eco design, expression design, expression web designer, fashion design, fashion designer, fashion designers, flash design, flash designer, food design, foose design, form designer, forum design, free design, furniture design, game design, game designer, graphic design, graphic designer, hair design, home design, home design 3d, home designer, hotel design, house design, if design, in design, industrial design, interface design, interior design, interior designer, italian design, landscape design, lego digital designer, light design, lighting design, lighting designer, logo design, logo design studio, logo designer, m design, microsoft expression web designer, motion design, n design, nero cover designer, network design, new design, no design, office sharepoint designer 2007, oz design, pe design, php design, php designer, php designer 2007, php designer 2007 professional, porsche design, power design, power designer, power point design, product design, qt designer, r design, report designer, rio design, sharepoint designer, sharepoint designer 2007, site design, site designer, software design, sound design, tattoo design, top design, urban design, visual design, web design, web designer, web designers, website design, www design, www designer, yacht design</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Java Pattern Oriented Framework]]></title>
<link>http://sandaruwan.wordpress.com/?p=4</link>
<pubDate>Tue, 08 Jul 2008 16:21:03 +0000</pubDate>
<dc:creator>sandaruwan</dc:creator>
<guid>http://sandaruwan.wordpress.com/?p=4</guid>
<description><![CDATA[Jt2.6 has been released. Jt is a pattern oriented framework for the rapid implementation of Java app]]></description>
<content:encoded><![CDATA[<p>Jt2.6 has been released. Jt is a pattern oriented framework for the rapid implementation of Java applications. Jt has been utilized in several large mission critical systems. Jt implements many well-known patterns including Data Access Objects (DAO), GoF design patterns and J2EE patterns.</p>
<p>source : <a href="http://jt.dev.java.net/" target="_blank">http://jt.dev.java.net</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Patron de diseño Comando]]></title>
<link>http://juanobligado.wordpress.com/?p=6</link>
<pubDate>Mon, 07 Jul 2008 17:16:21 +0000</pubDate>
<dc:creator>juanobligado</dc:creator>
<guid>http://juanobligado.wordpress.com/?p=6</guid>
<description><![CDATA[Introducción
El patrón comando encapsula una llamada como un objeto,por lo que nos permite paramet]]></description>
<content:encoded><![CDATA[<h2>Introducción</h2>
<p>El patrón comando encapsula una llamada como un objeto,por lo que nos permite parametrizar distintos objetos con diferentes llamadas. Este patrón nos sirve de utilidad cuando necesitamos desacoplar el objeto que hace un determinado requerimiento de los objetos que saben como realizar los dichos requerimientos</p>
<h2>Descripcion</h2>
<p> </p>
[wp_caption id="attachment_15" align="aligncenter" width="300" caption="Diagrama de Clases del Patrón Comando"]<a href="http://juanobligado.files.wordpress.com/2008/07/diagramadeclases.png"><img class="size-medium wp-image-15 " src="http://juanobligado.wordpress.com/files/2008/07/diagramadeclases.png?w=300" alt="Diagrama de Clases del Patrón Comando" width="300" height="124" /></a>[/wp_caption]
<ul>
<li><strong>Cliente :</strong> Es el responsable de Crear un comando concreto (de hacer el new) y de establecer su Receptor.</li>
<li><strong>Receptor :</strong> El receptor es el que sabe que trabajo debe realizarse para que el requerimiento pueda ser realizado satisfactoriamente.</li>
<li><strong>Interface de Comando :</strong> Define la Interface comun para todos los comandos homegeneizando la forma de invocar los distintos comandos que puede haber un sistema</li>
<li><strong>Comando Concreto :</strong> Define el lazo entre las acciones que debe realizar el receptor para lograr un determinado requerimiento y el solicitante que pide que un determinado sea ejecutado mediante la interface de Comando</li>
<li><strong>Solicitante :</strong> El solicitante tiene acceso a un determinado comando y hace el requerimiento para que este sea realizado llamando al metodo Ejecutar() del mismo</li>
</ul>
<h2>Ejemplo</h2>
<h2>Algunas Máximas de Programación Orientada a Patrones</h2>
<ul>
<li>Dependa de Clases Abstractas no de Clases Concretas</li>
<li>Programe Orientado a Funcionalidades (Interfaces) no a implementaciones</li>
<li>Encapsule lo que varia</li>
<li>Las Clases deberían estar Abiertas a Extension pero cerradas a modificaciones</li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Concurrency &amp; Coordination With Futures in C#]]></title>
<link>http://dvanderboom.wordpress.com/2008/07/03/concurrency-with-futures/</link>
<pubDate>Fri, 04 Jul 2008 01:14:32 +0000</pubDate>
<dc:creator>Dan Vanderboom</dc:creator>
<guid>http://dvanderboom.wordpress.com/2008/07/03/concurrency-with-futures/</guid>
<description><![CDATA[A future is a proxy or placeholder for a value that may not yet be known, usually because the calcul]]></description>
<content:encoded><![CDATA[<p>A future is a proxy or placeholder for a value that may not yet be known, usually because the calculation is time consuming.&#160; It is used as a synchronization construct, and it is an effective way to define dependencies among computations that will execute when all of their factors have been calculated, or in other words, to construct an expression tree with each node potentially computing in parallel.&#160; According to the <a href="http://en.wikipedia.org/wiki/Futures_and_promises" target="_blank">Wikipedia article</a> on futures and promises, using them can dramatically reduce latency in distributed systems.</p>
<p>Damon pointed out that the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&#38;displaylang=en" target="_blank">Parallel Extensions library</a> contains a Future&#60;T&#62; class, so I started looking around for examples and explanations of how they work, what the syntax is like, and I ran across <a href="http://blogs.msdn.com/pfxteam/archive/2008/02/29/7960146.aspx" target="_blank">a frightening example</a> implementing the asynchronous programming model with Future&#60;T&#62;, as well as going in the other direction, <a href="http://blogs.msdn.com/pfxteam/archive/2008/03/16/8272833.aspx" target="_blank">wrapping an APM implementation with Future&#60;T&#62;</a>.&#160; Other articles give pretty good <a href="http://www.liensberger.it/web/blog/?p=162" target="_blank">explanations</a> but trivial examples.&#160; From what I gathered briefly, the ContinueWith method for specifying the next step of calculation to process doesn’t seem to provide an intuitive way to indicate that several calculations may be depending upon the current one (unless it can be called multiple times?).&#160; Using ContinueWith, you’re always specifying <strong>forward</strong> the calculation task that depends on the current future object.&#160; It also surprised me a little that Future inherits from Task, because my understanding of a future is that it’s primarily defined as a value-holding object.&#160; But considering that a future really holds an expression that needs to be calculated, making Future a Task doesn’t seem so odd.</p>
<p>So I decided to implement my own Future&#60;T&#62; class before looking at the parallel extensions library too deeply.&#160; I didn’t want to prejudice my solution, because I wanted to make an exercise of it and see what I would naturally come up with.</p>
</p>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Though I tried avoiding prejudice, I still wound up characterizing it in my head as an task, and thought that a future would simply be a pair of Action and Reaction methods (both of the Action delegate type).&#160; The Action would execute and could do whatever it liked, including evaluate some expression and store it in a variable.&#160; If the Action completed, the Reaction method (a continuation) would run, and these could be specified using lambdas.&#160; Because I was storing the results in a local variable (result), swallowed up and made accessible with a closure, I didn’t see a need for a Value property in the future and therefore no need to make the type generic.&#160; Ultimately I thought it silly to have a Reaction method, since anything you needed to happen sequentially after a successful Action, you could simply store at the end of the Action method itself.</p>
<pre><font size="2"><span style="color:#2b91af;">FutureTask </span>task = <span style="color:blue;">new </span><span style="color:#2b91af;">FutureTask</span>(
    () =&#62; result = CalculatePi(10),
    () =&#62; <span style="color:blue;">new </span><span style="color:#2b91af;">FutureTask</span>(
        () =&#62; result += <span style="color:#a31515;">&#34;...&#34;</span>,
        () =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(result),
        ex2 =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;ex2: &#34; </span>+ ex2.Message)),
    ex1 =&#62; <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;ex1: &#34; </span>+ ex1.Message));</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>The syntax is what I was most concerned with, and as I started playing around with nesting of futures to compose my calculation, I started to feel like I was onto something.&#160; After all, it was almost starting to resemble some of the F# code I’ve been looking at, and I took that style of functional composition to be a good sign.&#160; As you can see from the code above, I also include a constructor parameter of type Action&#60;Exception&#62; for compensation logic to run in the event that the original action fails.&#160; (The result variable is a string, CalculatePi returns a string, and so the concatenation of the ellipsis really does make sense here.)</p>
<p>The problem that started nagging me was the thought that a composite computation of future objects might not be able to be defined all in one statement like this, not building the dependency tree from the bottom up.&#160; You can really only define the most basic factors (the leaf nodes of a dependency tree) at the beginning this way, and then the expressions that depend directly upon those leaf nodes, etc.&#160; What if you have 50 different starting future values, and you can only proceed with the next step in the calculation once 5 of those specific futures have completed evaluation?&#160; How would you express those dependencies with this approach?</p>
<p>That’s when I started to think about futures as top-down hierarchical data container objects, instead of tasks that have pointers to some next task in a sequence.&#160; I created a Future&#60;T&#62; class whose constructor takes an optional name (to aid debugging), a method of type Func&#60;T&#62; (which is a simple expression, supplied as a lambda in my examples), and finally an optional params list of other Future&#60;T&#62; objects on which that future value depends.</p>
<p>The first two futures in the code below start calculating pi (3.1415926535) and omega (which I made up to be a string of 9s).&#160; They have no dependencies, so they can start calculating right away.&#160; The paren future has two dependencies, supplied as two parameters at the end of the argument list: pi and omega.&#160; You can see that the values pi.Value and omega.Value are used in the expression, which will simply surround the concatenated string value with parentheses and spaces.</p>
<pre><font size="2"><span style="color:blue;">var </span>pi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10));
<span style="color:blue;">var </span>omega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega());

<span style="color:blue;">var </span>paren = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>, () =&#62; Parenthesize(pi.Value + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ omega.Value), pi, omega);

<span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>, () =&#62; Bracket(paren.Value), paren);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Finally, the result future has a dependency on the paren future.&#160; This surrounds the result of paren.Value with brackets and spaces.&#160; Because the operations here are trivial, I’ve added Thread.Sleep statements to all of these methods to simulate more computationally expensive work.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2008/07/image1.png"><img style="border-width:0;" height="219" alt="Dependencies Among Futures" src="http://dvanderboom.files.wordpress.com/2008/07/image-thumb1.png" width="240" border="0" /></a> </p>
<p>The program starts calculating pi and omega concurrently, and then immediately builds the paren future, which because of its dependencies waits for completion of the pi and omega futures.&#160; But it doesn’t block the thread.&#160; Execution continues immediately to build the result future, and then moves on to the next part of the program.&#160; When each part of the expression, each future, completes, it will set a Complete boolean property to true and invoke a Completed event.&#160; Any attempt to access the Value property of one of these futures <strong>will</strong> block the thread until it (and all of the futures it depends on) have completed evaluation.</p>
<p>Furthermore, if an exception occurs, all of the futures that depend on it will no longer attempt to evaluate, and the exceptions will be thrown as part of an AggregateException when accessing the Value property.&#160; This AggregateException contains all of the individual exceptions that were thrown as part of evaluating each future expression.&#160; If both pi and omega fail, result should be able to hand me a list of all Exceptions below it in the tree structure that automatically gets formed.</p>
<p>There are two bits of code I added as icing on this cake.&#160; The first is the use of the implicit operator to convert a variable of type Future&#60;T&#62; to type T.&#160; In other words, if you have a Future&#60;string&#62; called result, you can now pass result into methods where a string parameter is expected, etc.&#160; In the code listing at the end of the article, you’ll notice that I reference pi and omega instead of pi.Value and omega.Value (as in the code snippet above).</p>
<pre><font size="2"><span style="color:blue;">public static implicit operator </span>T(<span style="color:#2b91af;">Future</span>&#60;T&#62; Future)
{
    <span style="color:blue;">return </span>Future.Value;
}</font></pre>
<p>The other helpful bit is an override of ToString, which allows you to hover over a future variable in debug mode and see its name (if you named it), whether it’s Complete or Incomplete, and any errors encountered during evaluation.</p>
<pre><font size="2"><span style="color:blue;">public override string </span>ToString()
{
    <span style="color:blue;">return </span>Name + <span style="color:#a31515;">&#34;, &#34; </span>+ (Complete ? <span style="color:#a31515;">&#34;Complete&#34; </span>: <span style="color:#a31515;">&#34;Incomplete&#34;</span>) + (Error != <span style="color:blue;">null </span>? <span style="color:#a31515;">&#34;Error=&#34; </span>+ Error.Message : <span style="color:blue;">string</span>.Empty);
}</font></pre>
<p><a href="http://dvanderboom.files.wordpress.com/2008/07/image.png"><img style="border-width:0;" height="76" alt="Debug Experience of Future" src="http://dvanderboom.files.wordpress.com/2008/07/image-thumb.png" width="476" border="0" /></a> </p>
<p>What I’d really like to do is have the ability to construct this composite expression in a hierarchical form in the language, with a functionally composed syntax, replacing any parameter T with a Future&#60;T&#62;, something like this:</p>
<pre><font size="2"><span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>, () =&#62; Bracket(
    <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>, () =&#62; Parenthesize(
        <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10))
        + <span style="color:#a31515;">&#34; &#60; &#34; </span>+
        <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega())
    ))
));</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The Bracket and Parenthesize methods both require a string, but I give them an object that will at some point (“in the future”) evaluate to a string.&#160; Another term used for <strong>future</strong> is <strong>promise</strong>, although there is a distinction in some languages that support both, but you can think in terms of giving those methods the promise that they’ll get a string later, at which time they can proceed with their own evaluation.&#160; This effectively creates lazy evaluation, sometimes referred to as normal-order evaluation.</p>
<p>There are a few problems with this code, however.&#160; First of all, though it’s composed functionally from the top down and returns the correct answer, it takes too long to do it: about 8 seconds instead of 4.&#160; That means it’s processing all of the steps sequentially.&#160; This happens because the future objects we’re handing to the Parenthesize and Bracket methods have to be converted from Future&#60;string&#62; to string before they can be evaluated in the expression, and doing that activates the implicit operator, which executes the Value property getter.&#160; This completely destroys the asynchronous behavior we’re going for, by insisting on resolving it immediately with the wait built-into the Value property.&#160; The string concatenation expression evaluates sequentially one piece at a time, and when that’s done, the next level up evaluates, and so on.</p>
<p>The solution is to declare our futures as factors we depend on at each level, which start them executing right away due to C#’s order of evaluation, and declare the operations we want to perform in terms of those predefined futures.&#160; After a few hours of rearranging definitions, declaration order, and experimenting with many other details (including a brief foray into being more indirect with Func&#60;Future&#60;T&#62;&#62;), this is the working code I came up with:</p>
<pre><font size="2"><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62; FuturePi = <span style="color:blue;">null</span>, FutureOmega = <span style="color:blue;">null</span>, FutureConcat = <span style="color:blue;">null</span>, FutureParen = <span style="color:blue;">null</span>;

<span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(
    () =&#62; Bracket(FutureParen),
    (FutureParen = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(
        () =&#62; Parenthesize(FutureConcat),
        (FutureConcat = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:#2b91af;">String</span>&#62;(
            () =&#62; FuturePi + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ FutureOmega,
            (FuturePi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(() =&#62; CalculatePi(10))),
            (FutureOmega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(() =&#62; CalculateOmega()))
        ))
    ))
);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>In F# and other more functional languages, I imagine we could use let statements to define and assign these variables as part of the overall expression, instead of having to define the variables in a separate statement as shown here.</p>
<p>The Future&#60;T&#62; class I wrote works fairly well for exploration and study of futures and the possible syntax to define them and access their values, and I’ll share it so that you can experiment with it if you like, but understand that this is (even more so than usual) not production ready code.&#160; I’m making some very naive assumptions, not taking advantage of any task managers or thread pools, there is no intelligent scheduling going on, and I haven’t tested this in any real world applications.&#160; With that disclaimer out of the way, here it is, complete with the consuming test code.</p>
<pre><font size="2"><span style="color:blue;">using </span>System;
<span style="color:blue;">using </span>System.Collections.Generic;
<span style="color:blue;">using </span>System.Threading;
<span style="color:blue;">using </span>System.Linq;

<span style="color:blue;">namespace </span>FutureExpressionExample
{
    <span style="color:blue;">class </span></font><font size="2"><span style="color:#2b91af;">Program
    </span>{
        <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
        {
            <span style="color:#2b91af;">DateTime </span>StartTime = <span style="color:#2b91af;">DateTime</span>.Now;

            <span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62; FuturePi = <span style="color:blue;">null</span>, FutureOmega = <span style="color:blue;">null</span>, FutureConcat = <span style="color:blue;">null</span>, FutureParen = <span style="color:blue;">null</span>;

            <span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;bracket&#34;</span>,
                () =&#62; Bracket(FutureParen),
                (FutureParen = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;parenthesize&#34;</span>,
                    () =&#62; Parenthesize(FutureConcat),
                    (FutureConcat = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:#2b91af;">String</span>&#62;(<span style="color:#a31515;">&#34;concat&#34;</span>,
                        () =&#62; FuturePi + <span style="color:#a31515;">&#34; &#60; &#34; </span>+ FutureOmega,
                        (FuturePi = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;pi&#34;</span>, () =&#62; CalculatePi(10))),
                        (FutureOmega = <span style="color:blue;">new </span><span style="color:#2b91af;">Future</span>&#60;<span style="color:blue;">string</span>&#62;(<span style="color:#a31515;">&#34;omega&#34;</span>, () =&#62; CalculateOmega()))
                    ))
                ))
            );

            </font><font size="2"><span style="color:green;">/* Alternative

            // first group of expressions evaluating in parallel
            var pi = new Future&#60;string&#62;(&#34;pi&#34;, () =&#62; CalculatePi(10));
            var omega = new Future&#60;string&#62;(&#34;omega&#34;, () =&#62; CalculateOmega());

            // a single future expression dependent on all of the futures in the first group
            var paren = new Future&#60;string&#62;(&#34;parenthesize&#34;, () =&#62; Parenthesize(pi + &#34; &#60; &#34; + omega), pi, omega);

            // another single future expression dependent on the paren future
            var result = new Future&#60;string&#62;(&#34;bracket&#34;, () =&#62; Bracket(paren), paren);

            */

            </span><span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;Do other stuff while calculation occurs...&#34;</span>);

            </font><font size="2"><span style="color:blue;">try
            </span>{
                <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ result);
            }
            <span style="color:blue;">catch </span>(<span style="color:#2b91af;">AggregateException </span>ex)
            {
                <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ ex.Message);
            }

            <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
            <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&#34;\n&#34; </span>+ ts.TotalSeconds.ToString() + <span style="color:#a31515;">&#34; seconds&#34;</span>);

            <span style="color:#2b91af;">Console</span>.ReadKey();
        }

        <span style="color:blue;">static string </span>CalculatePi(<span style="color:blue;">int </span>NumberDigits)
        {
            </font><font size="2"><span style="color:green;">//throw new ApplicationException(&#34;Failed to calculate Pi&#34;);
            </span><span style="color:#2b91af;">Thread</span>.Sleep(3000);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;3.1415926535&#34;</span>;
        }

        <span style="color:blue;">static string </span>CalculateOmega()
        {
            </font><font size="2"><span style="color:green;">//throw new ApplicationException(&#34;Failed to calculate Omega&#34;);
            </span><span style="color:#2b91af;">Thread</span>.Sleep(3000);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;999999999999999&#34;</span>;
        }

        <span style="color:blue;">static string </span>Parenthesize(<span style="color:blue;">string </span>Text)
        {
            <span style="color:#2b91af;">Thread</span>.Sleep(500);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;( &#34; </span>+ Text + <span style="color:#a31515;">&#34; )&#34;</span>;
        }

        <span style="color:blue;">static string </span>Bracket(<span style="color:blue;">string </span>Text)
        {
            <span style="color:#2b91af;">Thread</span>.Sleep(500);
            <span style="color:blue;">return </span><span style="color:#a31515;">&#34;[ &#34; </span>+ Text + <span style="color:#a31515;">&#34; ]&#34;</span>;
        }
    }

    <span style="color:blue;">public class </span><span style="color:#2b91af;">Future</span>&#60;T&#62; : </font><font size="2"><span style="color:#2b91af;">IDisposable
    </span>{
        <span style="color:blue;">public string </span>Name { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
        <span style="color:blue;">public bool </span>Complete { <span style="color:blue;">get</span>; <span style="color:blue;">protected set</span>; }
        <span style="color:blue;">public </span><span style="color:#2b91af;">Exception </span>Error { <span style="color:blue;">get</span>; <span style="color:blue;">protected set</span>; }

        <span style="color:blue;">protected </span><span style="color:#2b91af;">Func</span>&#60;T&#62; Expression { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; Factors;
        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; FactorsCompleted;
        <span style="color:blue;">protected </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; FactorsFailed;

        <span style="color:blue;">public event </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62; Completed;
        <span style="color:blue;">protected void </span>OnCompleted()
        {
            Complete = <span style="color:blue;">true</span>;

            <span style="color:blue;">if </span>(Completed != <span style="color:blue;">null</span>)
                Completed(<span style="color:blue;">this</span>);
        }

        <span style="color:blue;">private </span>T _Value;
        <span style="color:blue;">public </span>T Value
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                </font><font size="2"><span style="color:green;">// block until complete
                </span><span style="color:blue;">while </span>(!Complete)
                {
                    <span style="color:#2b91af;">Thread</span>.Sleep(1);
                }

                <span style="color:blue;">if </span>(Exceptions.Count &#62; 0)
                    <span style="color:blue;">throw new </span><span style="color:#2b91af;">AggregateException</span>(Exceptions);

                <span style="color:blue;">return </span>_Value;
            }
            <span style="color:blue;">private set </span>{ _Value = <span style="color:blue;">value</span>; }
        }

        <span style="color:blue;">public </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                <span style="color:blue;">var </span>list = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62;();

                <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in </span>Factors)
                {
                    list.AddRange(Factor.Exceptions);
                }

                <span style="color:blue;">if </span>(Error != <span style="color:blue;">null</span>)
                    list.Add(Error);

                <span style="color:blue;">return </span>list;
            }
        }

        <span style="color:blue;">public static implicit operator </span>T(<span style="color:#2b91af;">Future</span>&#60;T&#62; Future)
        {
            <span style="color:blue;">return </span>Future.Value;
        }

        </font><font size="2"><span style="color:green;">// naming a Future is optional
        </span><span style="color:blue;">public </span>Future(<span style="color:#2b91af;">Func</span>&#60;T&#62; Expression, <span style="color:blue;">params </span><span style="color:#2b91af;">Future</span>&#60;T&#62;[] Factors) : <span style="color:blue;">this</span>(<span style="color:#a31515;">&#34;&#60;not named&#62;&#34;</span>, Expression, Factors) { }

        <span style="color:blue;">public </span>Future(<span style="color:blue;">string </span>Name, <span style="color:#2b91af;">Func</span>&#60;T&#62; Expression, <span style="color:blue;">params </span><span style="color:#2b91af;">Future</span>&#60;T&#62;[] Factors)
        {
            <span style="color:blue;">this</span>.Name = Name;
            <span style="color:blue;">this</span>.Expression = Expression;
            <span style="color:blue;">this</span>.Factors = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factors);

            FactorsCompleted = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;();
            FactorsFailed = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;();

            <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in this</span>.Factors)
            {
                <span style="color:blue;">if </span>(Factor.Complete)
                    FactorsCompleted.Add(Factor);
                </font><font size="2"><span style="color:blue;">else
                    </span>Factor.Completed += <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);
            }

            </font><font size="2"><span style="color:green;">// there may not be any factors, or they may all be complete
            </span><span style="color:blue;">if </span>(FactorsCompleted.Count == <span style="color:blue;">this</span>.Factors.Count)
                Expression.BeginInvoke(ReceiveCallback, <span style="color:blue;">null</span>);
        }

        <span style="color:blue;">private void </span>Factor_Completed(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor)
        {
            <span style="color:blue;">if </span>(!FactorsCompleted.Contains(Factor))
                FactorsCompleted.Add(Factor);

            <span style="color:blue;">if </span>(Factor.Error != <span style="color:blue;">null </span>&#38;&#38; !FactorsFailed.Contains(Factor))
                FactorsFailed.Add(Factor);

            Factor.Completed -= <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);

            <span style="color:blue;">if </span>(Exceptions.Count &#62; 0)
            {
                Dispose();
                OnCompleted();
                <span style="color:blue;">return</span>;
            }

            <span style="color:blue;">if </span>(FactorsCompleted.Count == Factors.Count)
                Expression.BeginInvoke(ReceiveCallback, <span style="color:blue;">null</span>);
        }

        <span style="color:blue;">private void </span>ReceiveCallback(<span style="color:#2b91af;">IAsyncResult </span>AsyncResult)
        {
            </font><font size="2"><span style="color:blue;">try
            </span>{
                Value = Expression.EndInvoke(AsyncResult);
            }
            <span style="color:blue;">catch </span>(<span style="color:#2b91af;">Exception </span>ex)
            {
                Error = ex;
            }

            Dispose();

            </font><font size="2"><span style="color:green;">// computation is completed, regardless of whether it succeeded or failed
            </span>OnCompleted();
        }

        <span style="color:blue;">public void </span>Dispose()
        {
            <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Future</span>&#60;T&#62; Factor <span style="color:blue;">in </span>Factors)
            {
                Factor.Completed -= <span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>&#60;<span style="color:#2b91af;">Future</span>&#60;T&#62;&#62;(Factor_Completed);
            }
        }

        </font><font size="2"><span style="color:green;">// helpful for debugging
        </span><span style="color:blue;">public override string </span>ToString()
        {
            <span style="color:blue;">return </span>Name + <span style="color:#a31515;">&#34;, &#34; </span>+ (Complete ? <span style="color:#a31515;">&#34;Complete&#34; </span>: <span style="color:#a31515;">&#34;Incomplete&#34;</span>) + (Error != <span style="color:blue;">null </span>? <span style="color:#a31515;">&#34;, Error=&#34; </span>+ Error.Message : <span style="color:blue;">string</span>.Empty);
        }
    }

    <span style="color:blue;">public class </span><span style="color:#2b91af;">AggregateException </span>: </font><font size="2"><span style="color:#2b91af;">Exception
    </span>{
        <span style="color:blue;">public </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions;

        <span style="color:blue;">public </span>AggregateException(<span style="color:#2b91af;">IEnumerable</span>&#60;<span style="color:#2b91af;">Exception</span>&#62; Exceptions)
        {
            <span style="color:blue;">this</span>.Exceptions = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:#2b91af;">Exception</span>&#62;(Exceptions);
        }

        <span style="color:blue;">public override string </span>Message
        {
            </font><font size="2"><span style="color:blue;">get
            </span>{
                <span style="color:blue;">string </span>message = <span style="color:blue;">string</span>.Empty;
                <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">Exception </span>ex <span style="color:blue;">in </span>Exceptions)
                {
                    message += ex.Message + <span style="color:#a31515;">&#34;\n&#34;</span>;
                }
                <span style="color:blue;">return </span>message;
            }
        }
    }
}</font></pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Pluggable Dependencies demo part 1]]></title>
<link>http://craigcav.wordpress.com/2008/07/02/pluggable-dependencies-demo-part-1/</link>
<pubDate>Wed, 02 Jul 2008 22:57:48 +0000</pubDate>
<dc:creator>craigcav</dc:creator>
<guid>http://craigcav.wordpress.com/2008/07/02/pluggable-dependencies-demo-part-1/</guid>
<description><![CDATA[I’ve been itching to build a “modern” application using an Agile approach with TDD since being]]></description>
<content:encoded><![CDATA[<p>I’ve been itching to build a “modern” application using an <a href="http://en.wikipedia.org/wiki/Agile_software_development" target="_blank">Agile</a> approach with <a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank">TDD</a> since being inspired by <a href="http://blog.wekeroad.com/mvc-storefront/" target="_blank">Rob Conery’s MVC Storefront application</a>, so&#160; I figured the small example I discussed in my <a href="http://craigcav.wordpress.com/2008/07/02/program-against-an-abstraction-not-an-implementation/" target="_blank">last post</a> would be a good starting point for me to take my first baby steps. </p>
<p>To briefly re-cap and pad out the initial requirement, the idea is to build a small app where a person (and their address details) can be stored. There will be a minimum requirement that a person must have a full name (forename and surname) and an address for that person to be “published” to a list of people on the system. Draft person records can be created with incomplete details, and stored until such a time when they can be completed and published.</p>
<p>Please keep in mind as you read this that this will be this first time I’ve *attempted to* use TDD in anger, so please feel free to confront me about any questionable decisions I make, and I’ll try and make time to adjust the app/discuss the issues further!</p>
</p>
</p>
</p>
</p>
</p>
</p>
<p>Right, without further ado I’ll begin!</p>
<h2></h2>
</p>
</p>
<h5>The first unit test</h5>
<p>In attempting to follow the TDD mantra, the first step is to code out my first test. I figure I’d start with trying to return a list of people (or Persons) and since I know <a href="http://craigcav.wordpress.com/2008/07/02/program-against-an-abstraction-not-an-implementation/" target="_blank">from my last post</a> I want program against an abstraction, I know this list will be of type IPerson. Since I also know I wish to filter this list, I want my return type to be IQueryable. So this leaves me with:</p>
<pre>[<span style="color:#2b91af;">TestMethod</span>]
<span style="color:blue;">public void </span>Repository_ShouldReturn_Persons_AsQueryable()
{
    IDataContext rep = <span style="color:blue;">new </span>InMemoryRepository();
    <span style="color:blue;">var </span>query = <span style="color:blue;">from </span>persons <span style="color:blue;">in </span>rep.Repository&#60;IPerson&#62;()
                <span style="color:blue;">select </span>persons;

    <span style="color:#2b91af;">Assert</span>.IsInstanceOfType(query, <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IQueryable</span>&#60;IPerson&#62;));
    <span style="color:#2b91af;">Assert</span>.IsTrue(query.Count() &#62; 0);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
</p>
<p>Of course since the none of these objects exist yet, the code will not build. With a little help from <a href="http://www.jetbrains.com/resharper/" target="_blank">Resharper</a> it’s easy to create some empty interfaces for IDataContext and IPerson and a basic implementation of InMemoryRepository to enable this code to build. These interfaces and classes now sit in the test project, within the InMemoryRepositoryTests code file and are marked as internal. At this point, this doesn’t matter. There’ll be a time to sort this out later in the process.</p>
<p>Now at this point, I run my first test, and of course, it fails – my repository method throws a NotImplementedException. At this point I really want to cheat a little since I already have an <a href="http://www.iridescence.no/Posts/Linq-to-Sql-Programming-Against-an-Interface-and-the-Repository-Pattern.aspx" target="_blank">implementation I can use</a> for this method that I’d like to use, but I know I would probably be burnt at the stake for such a blatant abuse of TDD, so I grit my teeth and continue. The TDD process tells me I should be adding the simplest implementation possible to make the test pass, so I write:</p>
<pre><span style="color:blue;">public </span><span style="color:#2b91af;">IQueryable</span>&#60;T&#62; Repository&#60;T&#62;()
{
    <span style="color:#2b91af;">IList</span>&#60;T&#62; items = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;T&#62;();

    <span style="color:blue;">return </span>items.AsQueryable();
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>…and it fails again. This time with the message &#34;Assert.IsTrue failed.&#34; – of course, there is no data being returned. Duh! This is easy to fix, I know I need to return a list of IQueryable&#60;Person&#62; so I add the following lines just above the return statement:</p>
<pre><span style="color:#2b91af;">IPerson </span>person = <span style="color:blue;">new </span><span style="color:#2b91af;">Person</span>();
items.Add((T)person);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This time, I run my test, and watch it pass! </p>
<p>Now I’m allowed to refactor. This is once again where <a href="http://www.jetbrains.com/resharper/" target="_blank">Resharper</a> comes in really handy; a few Alt+Enters and I’ve separated my objects and interfaces into separate files. I can then move IPerson and Person into a separate project called business objects (for want of a better name) and move IDataContext and InMemoryRepository into their own project (aptly named DataAccess). A few more tweaks are needed (like changing the protection level of the classes from internal to public, and altering namespaces) and I hit my next point requiring consideration – since I am making reference to the person object in the InMemoryRepository class, there is a one-way project dependency from my DataAccess project, to my BusinessObjects project and it appears that the dependency is avoidable. Since I want to avoid this dependency, I refactor the implementation to allow items to be inserted to an internally maintained list of objects:</p>
<pre><span style="color:blue;">private readonly </span><span style="color:#2b91af;">List</span>&#60;<span style="color:blue;">object</span>&#62; _inMemoryDataStore = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&#60;<span style="color:blue;">object</span>&#62;();

<span style="color:blue;">public </span><span style="color:#2b91af;">IQueryable</span>&#60;T&#62; Repository&#60;T&#62;()
{
    <span style="color:blue;">var </span>query = <span style="color:blue;">from </span>objects <span style="color:blue;">in </span>_inMemoryDataStore
                <span style="color:blue;">where typeof</span>(T).IsAssignableFrom(objects.GetType())
                <span style="color:blue;">select </span>objects; 

    <span style="color:blue;">return </span>query.Select(o =&#62; (T)o).AsQueryable();
}

<span style="color:blue;">public void </span>Insert&#60;T&#62;(T item)
{
    _inMemoryDataStore.Add(item);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
</p>
</p>
</p>
</p>
<p>I then add the Insert definition to my IDataContext so I can initialise the test with some data. Now my code builds again, I can now run my test again watch it pass!</p>
<h5></h5>
<h6></h6>
</p>
</p>
</p>
<p>Phew! That’s all I’m going to cover in this post. In later posts I will try to cover off returning Address details related to a person, implementing repositories that persist data to a database, implementing a “draft” repository, and switching between the pluggable dependencies.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Program against an abstraction, not an implementation]]></title>
<link>http://craigcav.wordpress.com/?p=11</link>
<pubDate>Wed, 02 Jul 2008 20:09:33 +0000</pubDate>
<dc:creator>craigcav</dc:creator>
<guid>http://craigcav.wordpress.com/?p=11</guid>
<description><![CDATA[I was asked by another developer today how I would go about enabling an application to record “tem]]></description>
<content:encoded><![CDATA[<p>I was asked by another developer today how I would go about enabling an application to record “temporary” incomplete data for a particular object (lets say, a person) where usually that object would require particular attributes to contain values, and perhaps pass some other validation (lets say, the person must have address details). Now my first thought was that I’d require different objects for the temporary person record, and the final, published person record, and that each could have different levels of validation applied. At this point, my mind wandered to a blog post I’d read somewhere before...</p>
<p>In the end, I answered his question by pointing him to the <a href="http://www.iridescence.no/Posts/Linq-to-Sql-Programming-Against-an-Interface-and-the-Repository-Pattern.aspx" target="_blank">blog</a> that I had read. This <a href="http://www.iridescence.no/Posts/Linq-to-Sql-Programming-Against-an-Interface-and-the-Repository-Pattern.aspx" target="_blank">blog</a> discusses the <a href="http://www.martinfowler.com/eaaCatalog/repository.html" target="_blank">Repository Pattern</a> and goes on to propose a super-flexible repository interface that allows different implementations of the repository to be swapped out – the primary goal being the ability to run unit tests in isolation (without hitting the database). The blog also emphasises that the power of an abstraction is it’s transparent plugability; the ability to swap in a “draft repository” is now made possible and changes made in draft can be persisted to a different storage location than the live data.</p>
<p>It’s not a big leap from here to see how different implementations of an IPerson interface could have differing validation logic depending on the context (draft or published). By programming against the abstraction of the repository interface, and against abstractions of the returned types, we can (with minimal effort) swap out different implementations to provide the required functionality. I’d quite like to have a go at implementing this technique myself to see what I can come up with. Perhaps in future posts I’ll explore this technique further.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Control Invoke Pattern Using Lambdas]]></title>
<link>http://dvanderboom.wordpress.com/2008/07/01/control-invoke-pattern-using-lambdas/</link>
<pubDate>Tue, 01 Jul 2008 21:40:11 +0000</pubDate>
<dc:creator>Dan Vanderboom</dc:creator>
<guid>http://dvanderboom.wordpress.com/2008/07/01/control-invoke-pattern-using-lambdas/</guid>
<description><![CDATA[In Windows Forms development, there are often times when you need to update the user interface in re]]></description>
<content:encoded><![CDATA[<p>In Windows Forms development, there are often times when you need to update the user interface in response to something happening on another thread.&#160; This could be a timer firing every second, some service running in the background and notifying the client of updated status on its own (background) thread, etc.&#160; If you've been working with Windows Forms for any length of time, you've doubtless run into exceptions that kindly inform you that you can't update controls on a thread other than the one that created those controls. We'll consider the simple issue of a timer firing every second, and the display of elapsed time in a label, for our example here, and introduce a new pattern to make this cleaner and more intuitive.</p>
<p>First we'll set up our start time and the thread.&#160; I use the System.Threading.Timer to ensure that we're using a non-UI thread.</p>
<pre><font size="2">StartTime = <span style="color:#2b91af;">DateTime</span>.Now;

Timer = <span style="color:blue;">new </span>System.Threading.<span style="color:#2b91af;">Timer</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">TimerCallback</span>(Timer_Tick));
Timer.Change(0, 1000);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Here's the event handler that calculates the elapsed time and calls Invoke, as well as the method we're invoking, which will run on the UI thread, where it can safely update the lblElapsedTime label control.</p>
<pre><font size="2"><span style="color:blue;">private void </span>Timer_Tick(<span style="color:blue;">object </span>state)
{
    <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
    Invoke(<span style="color:blue;">new </span><span style="color:#2b91af;">StringDelegate</span>(DisplayText), ts.TotalSeconds.ToString());
}

<span style="color:blue;">private void </span>DisplayText(<span style="color:blue;">string </span>Text)
{
    lblElapsedTime.Text = Text;
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In order to make this work, we need the event handler, a separate method to run in the UI thread, and also a delegate that matches the invoked method.</p>
<pre><font size="2"><span style="color:blue;">public delegate void </span><span style="color:#2b91af;">StringDelegate</span>(<span style="color:blue;">string </span>Text);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a>This is a lot of moving parts for such a small piece of functionality.&#160; To make matters worse, you may need to repeat this pattern many times, depending on the controls (or combinations thereof) that you need to update.&#160; In a modern multi-threaded application, your class can become littered with these invocations, handlers, and delegates.</p>
<p>What I'd really like to do is call Invoke and pass in an anonymous method (in lambda form).&#160; Unfortunately, Invoke takes a Delegate parameter, which is an abstract type.&#160; This forces you to instantiate a concrete delegate type.&#160; So while we eliminate our need for a separate method, we're still dependent on our delegate type.</p>
<pre><font size="2"><span style="color:blue;">private void </span>Timer_Tick(<span style="color:blue;">object </span>state)
{
    <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
    Invoke(<span style="color:blue;">new </span><span style="color:#2b91af;">StringDelegate</span>(s =&#62; lblElapsedTime.Text = s), ts.TotalSeconds.ToString());
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Or are we?&#160; By using the Action (or MethodInvoker) delegate for all of these invocations, and relying on C# and its support for closures, we can make a reference to the TimeSpan variable from within the anonymous method body, like this:</p>
<pre><font size="2"><span style="color:blue;">private void </span>Timer_Tick(<span style="color:blue;">object </span>state)
{
    <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
    Invoke(<span style="color:blue;">new </span><span style="color:#2b91af;">Action</span>(() =&#62; lblElapsedTime.Text = ts.TotalSeconds.ToString()));
}</font></pre>
<p>Here it's contained within a single method, and no additional delegates will be necessary to make this work.&#160; That's pretty nice!&#160; (A similar approach is taken <a href="http://blog.guymahieu.com/2006/11/15/systemdelegate-is-not-a-delegate-type/" target="_blank">here</a>.)&#160; But it's still not quite as slick and intuitive as I'd like.&#160; By creating an extension method, adding another overload of Invoke to the Control class, we can allow Invoke to assume a concrete Action delegate class, and write code like this:</p>
<pre><font size="2"><span style="color:blue;">private void </span>Timer_Tick(<span style="color:blue;">object </span>state)
{
    <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
    <span style="color:blue;">this</span>.Invoke(() =&#62; lblElapsedTime.Text = ts.TotalSeconds.ToString());
}</font></pre>
<p>Now that's clean.&#160; Just call Invoke, and pass in the lambda to execute.&#160; Or several statements in a code block if you like.&#160; It's very succinct.&#160; The only part that bothers me is the <strong>this</strong> keyword that's required.&#160; Extension methods don't register in Intellisense, nor do they compile successfully, if they're used without a variable, this, base, or something else with a dot after them.&#160; If we're really going to push the illusion of extending a class, I think we need to go <strong>all the way</strong> and make it work without having to explicitly type <strong>this</strong>.&#160; But it is what it is for now; hopefully this will be fixed in the next version of C# (along with adding support for extension properties, events, and operators).</p>
<p>That being said, here is the extension method to make this work:</p>
<pre><font size="2"><span style="color:blue;">public static void </span>Invoke(<span style="color:blue;">this </span><span style="color:#2b91af;">Control </span>Control, <span style="color:#2b91af;">Action </span>Action)
{
    Control.Invoke(Action);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a>It couldn't be simpler (thanks to a little help from <a href="http://blogs.msdn.com/madst/" target="_blank">Mads Torgersen</a>)!&#160; I'll include the finished program for those of you who want to run it to see and experiment; you'll just need to create the Program.cs with the startup code yourself.&#160; Create a new Windows Forms app and use what's there, renaming the form listed in Application.Run to match this one.</p>
<pre><font size="2"><span style="color:blue;">using </span>System;
<span style="color:blue;">using </span>System.Drawing;
<span style="color:blue;">using </span>System.Windows.Forms;
<span style="color:blue;">using </span>System.Threading;

<span style="color:blue;">namespace </span>ControlInvokeLambda
{
    <span style="color:blue;">public partial class </span><span style="color:#2b91af;">frmTestInvokeLambda </span>: </font><font size="2"><span style="color:#2b91af;">Form
    </span>{
        <span style="color:blue;">private </span><span style="color:#2b91af;">Button </span>btnExit;
        <span style="color:blue;">private </span><span style="color:#2b91af;">Label </span>lblElapsedTime;

        </font><font size="2"><span style="color:green;">// make sure we're using the Threading Timer for our example, which runs on a non-UI thread
        </span><span style="color:blue;">private </span>System.Threading.<span style="color:#2b91af;">Timer </span>Timer;

        <span style="color:blue;">private </span><span style="color:#2b91af;">DateTime </span>StartTime;

        <span style="color:blue;">public </span>frmTestInvokeLambda()
        {
            </font><font size="2"><span style="color:green;">// initialize controls

            </span>btnExit = <span style="color:blue;">new </span><span style="color:#2b91af;">Button</span>();
            btnExit.Location = <span style="color:blue;">new </span><span style="color:#2b91af;">Point</span>(88, 80);
            btnExit.Name = <span style="color:#a31515;">&#34;btnExit&#34;</span>;
            btnExit.Size = <span style="color:blue;">new </span><span style="color:#2b91af;">Size</span>(118, 26);
            btnExit.TabIndex = 0;
            btnExit.Text = <span style="color:#a31515;">&#34;Exit&#34;</span>;
            btnExit.UseVisualStyleBackColor = <span style="color:blue;">true</span>;
            btnExit.Click += <span style="color:blue;">new </span><span style="color:#2b91af;">EventHandler</span>(<span style="color:blue;">this</span>.btnExit_Click);

            lblElapsedTime = <span style="color:blue;">new </span><span style="color:#2b91af;">Label</span>();
            lblElapsedTime.AutoSize = <span style="color:blue;">true</span>;
            lblElapsedTime.Location = <span style="color:blue;">new </span><span style="color:#2b91af;">Point</span>(140, 36);
            lblElapsedTime.Name = <span style="color:#a31515;">&#34;lblElapsedTime&#34;</span>;
            lblElapsedTime.Size = <span style="color:blue;">new </span><span style="color:#2b91af;">Size</span>(13, 13);
            lblElapsedTime.TabIndex = 1;
            lblElapsedTime.Text = <span style="color:#a31515;">&#34;0&#34;</span>;

            AutoScaleDimensions = <span style="color:blue;">new </span><span style="color:#2b91af;">SizeF</span>(6F, 13F);
            AutoScaleMode = <span style="color:#2b91af;">AutoScaleMode</span>.Font;
            ClientSize = <span style="color:blue;">new </span><span style="color:#2b91af;">Size</span>(292, 136);
            Controls.Add(lblElapsedTime);
            Controls.Add(btnExit);
            Name = <span style="color:#a31515;">&#34;frmTestInvokeLambda&#34;</span>;
            Text = <span style="color:#a31515;">&#34;Invoke Lambda&#34;</span>;
            PerformLayout();

            </font><font size="2"><span style="color:green;">// remember start time and startup timer

            </span>StartTime = <span style="color:#2b91af;">DateTime</span>.Now;

            Timer = <span style="color:blue;">new </span>System.Threading.<span style="color:#2b91af;">Timer</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">TimerCallback</span>(Timer_Tick));
            Timer.Change(0, 1000);
        }

        <span style="color:blue;">private void </span>btnExit_Click(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">EventArgs </span>e)
        {
            Timer.Change(<span style="color:#2b91af;">Timeout</span>.Infinite, <span style="color:#2b91af;">Timeout</span>.Infinite);
            <span style="color:#2b91af;">Application</span>.Exit();
        }

        <span style="color:blue;">private void </span>Timer_Tick(<span style="color:blue;">object </span>state)
        {
            <span style="color:#2b91af;">TimeSpan </span>ts = <span style="color:#2b91af;">DateTime</span>.Now - StartTime;
            <span style="color:blue;">this</span>.Invoke(() =&#62; lblElapsedTime.Text = ts.TotalSeconds.ToString());
        }
    }

    <span style="color:blue;">public static class </span></font><font size="2"><span style="color:#2b91af;">ControlExtensions
    </span>{
        <span style="color:blue;">public static void </span>Invoke(<span style="color:blue;">this </span><span style="color:#2b91af;">Control </span>Control, <span style="color:#2b91af;">Action </span>Action)
        {
            Control.Invoke(Action);
        }
    }
}</font></pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[New Staff Intranet Release]]></title>
<link>http://journalofasoftwaredev.wordpress.com/?p=59</link>
<pubDate>Fri, 27 Jun 2008 22:17:58 +0000</pubDate>
<dc:creator>Michael Cromwell</dc:creator>
<guid>http://journalofasoftwaredev.wordpress.com/?p=59</guid>
<description><![CDATA[I have found enough spare time to put up a new release of the staff intranet project, for those who ]]></description>
<content:encoded><![CDATA[<p>I have found enough spare time to put up a new release of the <a href="http://www.codeplex.com/staffintranet" target="_blank">staff intranet project</a>, for those who are not aware of this project it is a demonstration of using best practices, principles &#38; patterns in a real world web application so if your looking for pointers or some code to use for your own applications go give it a look on <a href="http://www.codeplex.com/staffintranet" target="_blank">codeplex</a>.</p>
<p>In this newest version I have added AOP support to cut down on cross cutting code and also the ability to delete staff members from the GridView, most of the time spent was fighting against the asp.net controls (suprise, surprise) such as the GridView and the ObjectDataSource, I'm not sure what the guy(s) who created the ObjectDataSource object was smoking at the time but it must have been stronger than just tobacco :-)</p>
<p>My next release I want to demonstrate adding some service support showing how we can re-use existing code so they become little more than a remote facade (in theory!).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[New Spin on Spawning Threads]]></title>
<link>http://dvanderboom.wordpress.com/2008/06/23/new-spin-on-spawning-threads/</link>
<pubDate>Mon, 23 Jun 2008 17:18:29 +0000</pubDate>
<dc:creator>Dan Vanderboom</dc:creator>
<guid>http://dvanderboom.wordpress.com/2008/06/23/new-spin-on-spawning-threads/</guid>
<description><![CDATA[There are several good libraries (PFX, PLinq, CCR, etc.) available and coming out soon that help to ]]></description>
<content:encoded><![CDATA[<p>There are several good libraries (PFX, PLinq, CCR, etc.) available and coming out soon that help to write concurrent logic, providing various abstractions and control patterns.&#160; Until I can incorporate these into my Compact Framework applications, however, I find myself spinning up threads in the usual way, and sometimes what I need to run concurrently doesn't require any fancy coordination.</p>
<p>Here is the thread-spawning pattern I've used, and have seen used, countless times:</p>
<pre><font size="2"><span style="color:blue;">protected override void </span>OnStart()
{
    <span style="color:#2b91af;">Thread </span>t = <span style="color:blue;">new </span><span style="color:#2b91af;">Thread</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">ThreadStart</span>(Go));
    t.Name = <span style="color:#a31515;">"PrefetchLookupData"</span>;
    t.IsBackground = <span style="color:blue;">true</span>;
    t.Priority = <span style="color:#2b91af;">ThreadPriority</span>.AboveNormal;
    t.Start();
}

<span style="color:blue;">private void </span>Go()
{
    <span style="color:blue;">var </span>c1 = <span style="color:#2b91af;">LookupListDA</span>.CustomerTypes;
    <span style="color:blue;">var </span>c2 = <span style="color:#2b91af;">LookupListDA</span>.SalesOrderStates;
    <span style="color:blue;">var </span>c3 = <span style="color:#2b91af;">LookupListDA</span>.VendorTypes;
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The data layer shown in the example caches each lookup list internally the first time its property getter is accessed, so we can assign them to variables that are never used here and effectively "pre-fetch" our lookup list data while the user is waiting in the main menu, for example.</p>
<p>Using a lambda statement (anonymous method), we can consolidate this into a single named method, and avoid cluttering our class with a potential plethora of methods that may perform some ad hoc background thread processing.</p>
<pre><font size="2"><span style="color:blue;">protected override void </span>OnStart()
{
    <span style="color:#2b91af;">Thread </span>t = <span style="color:blue;">new </span><span style="color:#2b91af;">Thread</span>(<span style="color:blue;">new </span><span style="color:#2b91af;">ThreadStart</span>(() =&#62;
    {
        <span style="color:blue;">var </span>c1 = <span style="color:#2b91af;">LookupListDA</span>.CustomerTypes;
        <span style="color:blue;">var </span>c2 = <span style="color:#2b91af;">LookupListDA</span>.SalesOrderStates;
        <span style="color:blue;">var </span>c3 = <span style="color:#2b91af;">LookupListDA</span>.VendorTypes;
    }));

    t.Name = <span style="color:#a31515;">"PrefetchLookupData"</span>;
    t.IsBackground = <span style="color:blue;">true</span>;
    t.Priority = <span style="color:#2b91af;">ThreadPriority</span>.AboveNormal;
    t.Start();
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>After a little reflection, I came up with a similar pattern that further encapsulates the details, and in doing so, created an abstraction called LogicStream.&#160; Other names that work are ExecutionStream or CodeStream, with the central concept being that you're specifying a sequential set (stream) of instructions that runs parallel to the stream that defines it.</p>
<pre><font size="2"><span style="color:blue;">protected override void </span>OnStart()
{</font></pre>
<pre><font size="2">    <span style="color:blue;">new </span><span style="color:#2b91af;">LogicStream</span>(<span style="color:#a31515;">"PrefetchLookupData"</span>, s =&#62;
        {
            <span style="color:blue;">var </span>c1 = <span style="color:#2b91af;">LookupListDA</span>.CustomerTypes;
            <span style="color:blue;">var </span>c2 = <span style="color:#2b91af;">LookupListDA</span>.SalesOrderStates;
            <span style="color:blue;">var </span>c3 = <span style="color:#2b91af;">LookupListDA</span>.VendorTypes;
        });
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Like the second example, this approach doesn't require a separate method, but it's also completely self-contained: there is no thread manipulation code outside of this code block; any setup we need to do can either be done via parameters ("PrefetchLookupData" names the thread) or by specifying an additional code block for thread configuration (an example is shown below).&#160; Finally, the LogicStream constructor immediately invokes the thread, which is a background thread by default, so nothing additional needs to be done.</p>
<p>Here's a slightly more complicated example, showing how you can configure the thread and pass in multiple parameters.</p>
<pre><font size="2"><span style="color:blue;">using </span>System;
<span style="color:blue;">using </span>System.Threading;

<span style="color:blue;">namespace </span>Demo
{
    <span style="color:blue;">class </span></font><font size="2"><span style="color:#2b91af;">Program
    </span>{
        <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
        {
            <span style="color:#2b91af;">Thread</span>.CurrentThread.Name = <span style="color:#a31515;">"Main"</span>;

            <span style="color:blue;">new </span><span style="color:#2b91af;">LogicStream</span>(<span style="color:#a31515;">"ThreadX"</span>, s =&#62;
            {
                </font><font size="2"><span style="color:green;">// rename parameters passed into thread
                </span><span style="color:blue;">string </span>ExtraInfo = s.Get&#60;<span style="color:blue;">string</span>&#62;(0);
                <span style="color:blue;">int </span>StartIndex = s.Get&#60;<span style="color:blue;">int</span>&#62;(1);
                <span style="color:blue;">int </span>EndIndex = s.Get&#60;<span style="color:blue;">int</span>&#62;(2);

                </font><font size="2"><span style="color:green;">// do work
                </span><span style="color:blue;">for </span>(<span style="color:blue;">int </span>x = StartIndex; x &#60;= EndIndex; x++)
                {
                    <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"x = " </span>+ x.ToString().PadRight(10) + s.Name);
                    <span style="color:#2b91af;">Thread</span>.Sleep(50);

                    </font><font size="2"><span style="color:green;">// this code has access to the Thread object via the LogicStream
                    </span><span style="color:blue;">if </span>(x &#62; 90)
                        s.Thread.Abort();
                }
            }, <span style="color:#a31515;">"Width Data"</span>, 0, 100); </font><font size="2"><span style="color:green;">// optional parameters passed into the LogicStream

            </span><span style="color:blue;">new </span><span style="color:#2b91af;">LogicStream</span>(t =&#62;
                {
