{"id":1140,"date":"2020-06-02T01:24:46","date_gmt":"2020-06-01T15:24:46","guid":{"rendered":"http:\/\/www.moneystock.net\/wp_e\/?p=1140"},"modified":"2020-06-06T00:15:05","modified_gmt":"2020-06-05T14:15:05","slug":"design-pattern-command","status":"publish","type":"post","link":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/","title":{"rendered":"Design Pattern &#8211; Command"},"content":{"rendered":"\r\n<p>The command pattern is useful to handle direction from args in command line app.\u00a0<\/p>\r\n<p>For example, there was an ugly code as below, which I wrote a while ago. As I simplified the code to focus on if-else statement, it may look not that bad.\u00a0 But, I was struggling with managing the mapping each method with the command from argument especially when adding a new one or modifying the existing one.\u00a0<\/p>\r\n<p>Many said there is code smell when you see a long if-else or case statement. I didn&#8217;t know what was the problem until I fixed it.\u00a0<\/p>\r\n<pre class=\"prettyprint\">if (runOption == \"all\")\r\n                {\r\n                    await _stockPriceManager.ReadStockPriceFromWeb(stocksToRead, _appSettings.DaysToReadFromWeb);\r\n\r\n                    \/\/ Iterate simulation\r\n                    var averageAnnualReturn = await IterateSimulationAsync(investDay, stocksToAnalyze, _tradeOption);\r\n                    \r\n                }\r\n                else if (runOption == \"recalculate\")\r\n                {\r\n                    await _stockPriceManager.ReCalculateCoefficient(stocksToAnalyze);\r\n                }\r\n                else if (runOption == \"simulate\")\r\n                {\r\n                    var averageAnnualReturn = await IterateSimulationAsync(investDay, stocksToAnalyze, _tradeOption);\r\n                }\r\n                else if (runOption.ToLower() == \"readprice\")\r\n                {\r\n                    await _stockPriceManager.ReadStockPriceFromWeb(stocksToRead, _appSettings.DaysToReadFromWeb);\r\n                }<\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>This code refactored as below using the command pattern. After refactoring, the selection condition was deligated to the concrete command object. To add a new action, it&#8217;s possible just to add new command object to the availablecommands array and no need to modify the code below that. Another and actually more important benefit that I didn&#8217;t show from this simple example code is that I could separate responsibility of each command under its own class. As you may imagine, most of those were inside the same class where if-else statement was. Implementing the command pattern naturally led me to implement the single responsibility principle.\u00a0<\/p>\r\n<p>The downside of this approach is that you need to create a new 3 command class and one ICommand interface. When it&#8217;s a simple program like a prototype, we might want to just use a simple if-else style. But, if there is any chance the code become a long-running one, which implies that continuous add\/modification will be followed by, I would use command pattern.\u00a0<\/p>\r\n<pre class=\"prettyprint\">                var availableCommands = new ICommand[]\r\n                {\r\n                    new UpdatePrice(_stockPriceManager, stocksToRead, _appSettings.DaysToReadFromWeb),\r\n                    new UpdateStats(_stockPriceManager, stocksToAnalyze),\r\n                    new SimulateCommand(_stockPriceManager, stocksToAnalyze, _marketWatchRepository, investDay,\r\n                        _tradeOption, _logger, _appSettings)\r\n                };\r\n\r\n                if (runOption == \"all\")\r\n                {\r\n                    availableCommands.Select(async c =&gt; await c.Execute());\r\n                }\r\n                else\r\n                {\r\n                    var command = availableCommands.Single(c =&gt; c.Name == runOption);\r\n                    await command.Execute();\r\n                }<\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>This was possible because each command shares the same interface, ICommand. That looks like below.\u00a0<\/p>\r\n<pre class=\"prettyprint\">    public interface ICommand\r\n    {\r\n        string Name { get; }\r\n\r\n        Task Execute();\r\n    }<\/pre>\r\n<p>&nbsp;<\/p>\r\n<p>One of the implementations of ICommand will look like below.\u00a0<\/p>\r\n<pre class=\"prettyprint\">    public class UpdateStats : ICommand\r\n    {\r\n        public string Name =&gt; \"UpdateStats\";\r\n\r\n        private readonly IStockPriceManager _stockPriceManager;\r\n        private readonly List&lt;string&gt; _stocksToAnalyze;\r\n\r\n        public UpdateStats(IStockPriceManager stockPriceManager, List&lt;string&gt; stocksToAnalyze)\r\n        {\r\n            _stockPriceManager = stockPriceManager;\r\n            _stocksToAnalyze = stocksToAnalyze;\r\n        }\r\n\r\n        public async Task Execute()\r\n        {\r\n            await _stockPriceManager.ReCalculateCoefficient(_stocksToAnalyze);\r\n        }\r\n    }<\/pre>\r\n<p>The key here is that all command object share the member, Name, and method, Execute() so that these commands can be used in a standardized manner.\u00a0<\/p>\r\n<p>To see more about the command pattern, go to https:\/\/www.dofactory.com\/net\/command-design-pattern<br \/><br \/><\/p>\r\n<p><\/p>","protected":false},"excerpt":{"rendered":"<p>The command pattern is useful to handle direction from args in command line app.\u00a0 For example, there was an ugly code as below, which I wrote a while ago. As I simplified the code to focus on if-else statement, it may look not that bad.\u00a0 But, I was struggling with managing the mapping each method&hellip; <a class=\"more-link\" href=\"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/\">Continue reading <span class=\"screen-reader-text\">Design Pattern &#8211; Command<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[548],"tags":[572,571],"class_list":["post-1140","post","type-post","status-publish","format-standard","hentry","category-c","tag-command-pattern","tag-design-pattern","entry"],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 4.9.8 - aioseo.com -->\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"rocker8942\"\/>\n\t<link rel=\"canonical\" href=\"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/\" \/>\n\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 4.9.8\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"Joe&#039;s Happy Life | Be positive, have fun\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"Design Pattern \u2013 Command | Joe&#039;s Happy Life\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2020-06-01T15:24:46+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2020-06-05T14:15:05+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary\" \/>\n\t\t<meta name=\"twitter:title\" content=\"Design Pattern \u2013 Command | Joe&#039;s Happy Life\" \/>\n\t\t<script type=\"application\/ld+json\" class=\"aioseo-schema\">\n\t\t\t{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#article\",\"name\":\"Design Pattern \\u2013 Command | Joe's Happy Life\",\"headline\":\"Design Pattern &#8211; Command\",\"author\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/author\\\/rocker8942\\\/#author\"},\"publisher\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/#organization\"},\"datePublished\":\"2020-06-02T01:24:46+08:00\",\"dateModified\":\"2020-06-06T00:15:05+08:00\",\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#webpage\"},\"isPartOf\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#webpage\"},\"articleSection\":\"C#, command pattern, design pattern, English\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#breadcrumblist\",\"itemListElement\":[{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e#listItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/moneystock.net\\\/wp_e\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/category\\\/c\\\/#listItem\",\"name\":\"C#\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/category\\\/c\\\/#listItem\",\"position\":2,\"name\":\"C#\",\"item\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/category\\\/c\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#listItem\",\"name\":\"Design Pattern &#8211; Command\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e#listItem\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#listItem\",\"position\":3,\"name\":\"Design Pattern &#8211; Command\",\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/category\\\/c\\\/#listItem\",\"name\":\"C#\"}}]},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/#organization\",\"name\":\"Joe's Happy Life\",\"description\":\"Be positive, have fun\",\"url\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/author\\\/rocker8942\\\/#author\",\"url\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/author\\\/rocker8942\\\/\",\"name\":\"rocker8942\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#authorImage\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d00fcc2c7b0eaab40443e28428a4429ab4a95e12086262d902988f448d76b128?s=96&d=mm&r=g\",\"width\":96,\"height\":96,\"caption\":\"rocker8942\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#webpage\",\"url\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/\",\"name\":\"Design Pattern \\u2013 Command | Joe's Happy Life\",\"inLanguage\":\"en-US\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/#website\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/2020\\\/06\\\/02\\\/design-pattern-command\\\/#breadcrumblist\"},\"author\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/author\\\/rocker8942\\\/#author\"},\"creator\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/author\\\/rocker8942\\\/#author\"},\"datePublished\":\"2020-06-02T01:24:46+08:00\",\"dateModified\":\"2020-06-06T00:15:05+08:00\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/#website\",\"url\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/\",\"name\":\"Joe's Happy Life\",\"description\":\"Be positive, have fun\",\"inLanguage\":\"en-US\",\"publisher\":{\"@id\":\"https:\\\/\\\/moneystock.net\\\/wp_e\\\/#organization\"}}]}\n\t\t<\/script>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Design Pattern \u2013 Command | Joe's Happy Life","description":"","canonical_url":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/","robots":"max-image-preview:large","keywords":"","webmasterTools":{"miscellaneous":""},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#article","name":"Design Pattern \u2013 Command | Joe's Happy Life","headline":"Design Pattern &#8211; Command","author":{"@id":"https:\/\/moneystock.net\/wp_e\/author\/rocker8942\/#author"},"publisher":{"@id":"https:\/\/moneystock.net\/wp_e\/#organization"},"datePublished":"2020-06-02T01:24:46+08:00","dateModified":"2020-06-06T00:15:05+08:00","inLanguage":"en-US","mainEntityOfPage":{"@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#webpage"},"isPartOf":{"@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#webpage"},"articleSection":"C#, command pattern, design pattern, English"},{"@type":"BreadcrumbList","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e#listItem","position":1,"name":"Home","item":"https:\/\/moneystock.net\/wp_e","nextItem":{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e\/category\/c\/#listItem","name":"C#"}},{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e\/category\/c\/#listItem","position":2,"name":"C#","item":"https:\/\/moneystock.net\/wp_e\/category\/c\/","nextItem":{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#listItem","name":"Design Pattern &#8211; Command"},"previousItem":{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e#listItem","name":"Home"}},{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#listItem","position":3,"name":"Design Pattern &#8211; Command","previousItem":{"@type":"ListItem","@id":"https:\/\/moneystock.net\/wp_e\/category\/c\/#listItem","name":"C#"}}]},{"@type":"Organization","@id":"https:\/\/moneystock.net\/wp_e\/#organization","name":"Joe's Happy Life","description":"Be positive, have fun","url":"https:\/\/moneystock.net\/wp_e\/"},{"@type":"Person","@id":"https:\/\/moneystock.net\/wp_e\/author\/rocker8942\/#author","url":"https:\/\/moneystock.net\/wp_e\/author\/rocker8942\/","name":"rocker8942","image":{"@type":"ImageObject","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#authorImage","url":"https:\/\/secure.gravatar.com\/avatar\/d00fcc2c7b0eaab40443e28428a4429ab4a95e12086262d902988f448d76b128?s=96&d=mm&r=g","width":96,"height":96,"caption":"rocker8942"}},{"@type":"WebPage","@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#webpage","url":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/","name":"Design Pattern \u2013 Command | Joe's Happy Life","inLanguage":"en-US","isPartOf":{"@id":"https:\/\/moneystock.net\/wp_e\/#website"},"breadcrumb":{"@id":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/#breadcrumblist"},"author":{"@id":"https:\/\/moneystock.net\/wp_e\/author\/rocker8942\/#author"},"creator":{"@id":"https:\/\/moneystock.net\/wp_e\/author\/rocker8942\/#author"},"datePublished":"2020-06-02T01:24:46+08:00","dateModified":"2020-06-06T00:15:05+08:00"},{"@type":"WebSite","@id":"https:\/\/moneystock.net\/wp_e\/#website","url":"https:\/\/moneystock.net\/wp_e\/","name":"Joe's Happy Life","description":"Be positive, have fun","inLanguage":"en-US","publisher":{"@id":"https:\/\/moneystock.net\/wp_e\/#organization"}}]},"og:locale":"en_US","og:site_name":"Joe's Happy Life | Be positive, have fun","og:type":"article","og:title":"Design Pattern \u2013 Command | Joe's Happy Life","og:url":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/","article:published_time":"2020-06-01T15:24:46+00:00","article:modified_time":"2020-06-05T14:15:05+00:00","twitter:card":"summary","twitter:title":"Design Pattern \u2013 Command | Joe's Happy Life"},"aioseo_meta_data":{"post_id":"1140","title":null,"description":null,"keywords":null,"keyphrases":null,"primary_term":null,"canonical_url":null,"og_title":null,"og_description":null,"og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":null,"og_custom_url":null,"og_article_section":null,"og_article_tags":null,"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"Article","isEnabled":true},"graphs":[]},"schema_type":null,"schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":null,"robots_max_videopreview":null,"robots_max_imagepreview":"large","priority":null,"frequency":null,"local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":null,"created":"2021-04-24 04:50:01","updated":"2025-06-03 23:53:29","seo_analyzer_scan_date":null},"aioseo_breadcrumb":"<div class=\"aioseo-breadcrumbs\"><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/moneystock.net\/wp_e\" title=\"Home\">Home<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">&raquo;<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/moneystock.net\/wp_e\/category\/c\/\" title=\"C#\">C#<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">&raquo;<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\tDesign Pattern \u2013 Command\n\t\t<\/span><\/div>","aioseo_breadcrumb_json":[{"label":"Home","link":"https:\/\/moneystock.net\/wp_e"},{"label":"C#","link":"https:\/\/moneystock.net\/wp_e\/category\/c\/"},{"label":"Design Pattern &#8211; Command","link":"https:\/\/moneystock.net\/wp_e\/2020\/06\/02\/design-pattern-command\/"}],"_links":{"self":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1140","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/comments?post=1140"}],"version-history":[{"count":9,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1140\/revisions"}],"predecessor-version":[{"id":1162,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1140\/revisions\/1162"}],"wp:attachment":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/media?parent=1140"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/categories?post=1140"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/tags?post=1140"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}