{"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":[],"_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}]}}