<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Sergei Golos - Code of Serge]]></title><description><![CDATA[Throw enough spaghetti at the wall, maybe something will stick.]]></description><link>http://codeofserge.com/</link><generator>Ghost 0.5</generator><lastBuildDate>Tue, 05 May 2026 12:04:20 GMT</lastBuildDate><atom:link href="http://codeofserge.com/author/sergei-golos/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[unit testing blogs]]></title><description><![CDATA[<p>The platform that this blog utilizes is <a href="http://ghost.org/">ghost</a>, a really simple an bare-bones blog.  The main reason for this publishing engine over the pletera of choices out there... Markdown.  I get to write everything in markdown, and ghost will go about making it pretty.  Especially if you throw some <a href="http://prismjs.com/">prismjs</a> in for code highlighting. But is pretty code enough???</p>

<p>Rhetorically answering this with a resounding NO... the code also needs to be correct.  And how do we as software engineers make sure code is correct? </p>

<pre><code class=" language-blogunit name-runner">func  
test  
</code></pre>

<p>That's right, unit tests.  Which got me thinking a bit... Given I am already in a javascript runtime, can't I just inline my unit tests right into the blog it self?  This post is a biproduct of the a couple of nights of tinkering with jasmine, iframes and events between different doms.</p>

<p>The two tests hopefully passing tests above are testing out the function in the code block bellow.  The code, a simple add one function, is evaluated with in a iframe runtime.</p>

<pre><code class=" language-javascript name-func">function add1(num) {  
    return num + 1;
}
</code></pre>

<p>Just like the function above, the unit test logic bellow is also identified and evulated with in the iframe runtime.</p>

<pre><code class=" language-javascript name-test">describe("Running a sample code UnitTest", function() {  
  it("adds 1 to a number", function() { 
      expect(add1(1)).toBe(2);
  });

  it("adds 1 to another number", function() {
      expect(add1(0)).toBe(1);
  });
});
</code></pre>

<p>The codebase is effectivly creating new script tags inside the iframe and loading the text of the scripts into them.  With the help of some promises, we can extend the logic to also sideload serverside files into the runtime.  In the example bellow I am loading some scripts from my github repository and displaying the results of the run.</p>

<pre><code class=" language-blogunit name-external">https://raw.githubusercontent.com/SergeiGolos/CodeOfSerge/master/unit_test_blogs/src/Player.js  
https://raw.githubusercontent.com/SergeiGolos/CodeOfSerge/master/unit_test_blogs/src/Song.js  
https://raw.githubusercontent.com/SergeiGolos/CodeOfSerge/master/unit_test_blogs/spec/PlayerSpec.js  
https://raw.githubusercontent.com/SergeiGolos/CodeOfSerge/master/unit_test_blogs/spec/SpecHelper.js  
</code></pre>

<h3 id="source">Source</h3>

<p><a href="https://github.com/SergeiGolos/CodeOfSerge/tree/master/unit_test_blogs">https://github.com/SergeiGolos/CodeOfSerge/tree/master/unit<em>test</em>blogs</a></p>

<p>Be warned, this code is alpha and in some places might require some tweeks to get it to work.  The path to your dependencies for example.  Also, becuse i am creating the html for the iframe on the fly, you might find some strange cross domain exeptions if URLs are not formated correctly.</p>]]></description><link>http://codeofserge.com/ghostunit-test-post/</link><guid isPermaLink="false">8cd95aac-8722-497e-94b1-1dfc27540635</guid><category><![CDATA[unit-testing]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Tue, 10 May 2016 19:56:30 GMT</pubDate></item><item><title><![CDATA[lessons learned]]></title><description><![CDATA[<p>Geeks like to tinker.  And we really like our new toys.  So when my girlfriend asked me to put together simple tool for her grandfathers business, I thought this was a great opportunity to learn something new: <a href="https://www.polymer-project.org/1.0/">Polymer</a>.  The internet seemed full of glee for it; what could go wrong.</p>

<p><img src="http://i.imgur.com/G45tBKZ.gif" alt="kill me gif"></p>

<p>Well... Since my last post was well over <del>three month</del> six months ago, it is clear that this strategy went over about as well as a two front war for Germany. Quoting the project at about 80 hours, with the learning curve I was expecting to spend about 120 hours,  My baptism by fire wasn't to be the concern of my patron.</p>

<p>150+ hours in, and at a second dead end after a full re-write from scratch.  I was beaten, bruised and defeated, and I crawled back to the tried and true <a href="http://getbootstrap.com/">Bootstrap</a>.</p>

<p>Was it all bad?  Not really, but the technology is too green even now that it has gone production with 1.0.  </p>

<p><strong>Layout based on flex-box: amazing</strong></p>

<p><em>In Chrome only</em>. <em>Mostly</em></p>

<p>Front end developers like to pretend that HTML/CSS/JavaScript stack creates clean separations of concerns, but where does the layout fit in this scheme? <br>
 - Is it the task of the html mark up? Not really, but the markup around the data plays a part. <br>
 - Is it the CSS? Largely, but even in combination of CSS and HTML some layouts hunger for more complexity and require JavaScript; resize events for example.
 - JavaScript? Kind of, but the JavaScript really just manipulates the other two.</p>

<p>Flex-box, in principle aggregates the functionality of all 3 and moves them into a declarative markup in the HTML.  Which is a dream, HTML really should be the layout layer.  But even in chrome, some alignments produced unexpected artifacts in line heights and growing containers.  And while some of these issues are resolved in 1.0, you can still see the browser struggling to deal with this new technology.  And phone scrolling seems to trigger some strange elements shifts.  </p>

<p>Then, for the LOLz, there is IE.</p>

<p><img src="http://mimg.ugo.com/201107/6/1/5/202516/cuts/robocop-toxic-waste_786x442.jpg" alt="IE Rendering FlexBox"></p>

<p>But blinded by the shiny new toy, I trudge on.</p>

<blockquote>
  <p>"Well, that's ok.  The project had plans to be consumed on a chromebox, so IE support isn't necessary."</p>
</blockquote>

<p><strong>Paper looks amazing on the phone.  Bulky on desktop.</strong></p>

<p><em>Personal BIAS alert.</em> I like paper and with a team of designers, paper can look very professional. But even google projects start to degrade on larger screens; example is <a href="https://inbox.google.com/">Inbox</a>, the new face-lift for Gmail.  It is an amazing tool for the phone which has replaced my e-mail client on my android.  But when I jump on my desktop with a large screen, the interface feels wasted; whole areas of my screen have no utilization and the larger bubblier look and feel requires more scrolling to cover less information.</p>

<p>Naturally, this is another area where I ran into problems; even with the background of some 8 years of art classes as a child, I am a coder first and a graphics designer <em>never</em>.  So while application looked pretty good on my android phone, it didn't scale well to the large display; something was greatly problematic with a TV dashboard feature of the product.</p>

<p><strong>Web components</strong></p>

<p>No review of polymer can be complete without some thoughts on meat and potatoes of Polymer, <a href="http://webcomponents.org/">web components</a>; the new technology fore-casted to drive the future of Internet application.  </p>

<p>At its heart, Polymer, is an implementation of web components, with a full abstraction layer for much easier web components creation.  Web components, allow the grouping of HTML, CSS and JavaScript as one deliverable package.  A package which when imported into the browser runs as any native HTML control. This brings great performance, but again the browser support currently is lacking and polyfils cancel this benefit.</p>

<p>But the theory behind web components, that developers can pick and choose 3rd party components to quickly develop applications makes me question if the Internet has learned anything from Microsoft's ASP.NET WebForms.  It isn't completely fair to compare web components to ASP.NET WebForms, as many of the design flaws of WebForms don't effect the domain of front end development. But WebForms created a generation of developers who worked in a medium they didn't understand.  The web was not a desktop application, and the abstraction shielded developers from having to understand the web applications workflow. More over, the overcomplicated abstraction made developers fear of what is under the hood.  To this day I see this in Enterprise development.  So will it be good for developers to drag and drop some web components onto an HTML page?  Yes, they will be able to hit the ground running and create solutions but also, no, because it will shield green developers from having to understand the underlaying mechanisms of the medium they are developing on.</p>

<p><strong>Conclusion</strong></p>

<p>There is a lot of promise and room for growth for these combined technologies.  But with out better browser support, the usefulness is diminished.</p>

<p>It takes 300ms of waiting before the user starts to get frustrated.  Achieving quick load times is a task that is hard enough to do without the bloat-ware of multiple poly-fills.  But even after bootstrapping the full poly-fill runtime, the response of loaded elements feel sluggish.  </p>

<p>And what about mobile?  My dev box is an I7 with 4 hyper-threaded cores with a 750W power supply and more memory then <a href="http://www.computerworld.com/article/2534312/operating-systems/the--640k--quote-won-t-go-away----but-did-gates-really-say-it-.html">Bill Gates</a> ever expected, but my phone has only a 3200mAh battery and a flimsy ARM processor.  So what is the trade-off between visual feedback and battery life? If my computer stutters, my phone must in some real pain.</p>

<p>While for now, I am sticking with bootstrap for any contracted project, but I will continue to play with Polymor and other web component implementations until they mature enough for production.</p>]]></description><link>http://codeofserge.com/lessons-learned/</link><guid isPermaLink="false">f9bf36e1-9bcc-4e54-a99d-a873aebd0717</guid><category><![CDATA[Theory]]></category><category><![CDATA[Polymer]]></category><category><![CDATA[Web Components]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Wed, 19 Aug 2015 00:23:37 GMT</pubDate></item><item><title><![CDATA[language fluency]]></title><description><![CDATA[<p>I have heard it said that learning a second language is pretty hard, but learning subsequent languages gets progressively easier. Already an ESL (English as a Second Language) student in high school, I was forced to attempt a 3rd language, Spanish courses that were mandated for graduation. I merely muddled through it.  </p>

<blockquote>
  <p>"That galaxy is signaling in binary. I should signal back, but I only know enough binary to ask where the bathroom is."
  - <a href="http://www.imdb.com/title/tt0756880/quotes">Bender</a> ( <a href="http://www.imdb.com/title/tt0756880/?ref_=ttqt_qt_tt">Futurama - S4E8 - Godfellas</a> )</p>
</blockquote>

<p>My excuse for my limited Spanish acquisition is that perhaps I'd been diverting my learning toward computer programing languages instead.</p>

<blockquote>
  <p>"I dedicate this performance to the lovin' memory of Microsoft QBasic. Keepin' it real."
   - <a href="http://futuristicsexrobotz.net/mp3s/15%20Checking%20Out.mp3">Futuristic Sex Robotz</a></p>
</blockquote>

<p>But the excuse is only an afterthought. I only started thinking about the correlation between spoken languages and programing languages after stumbling onto the topic of <a href="http://en.wikipedia.org/wiki/Literate_programming">literate programming</a>.</p>

<blockquote>
  <p>Literate programming is an approach to programming, introduced by Donald Knuth, in which a program is given as an explanation of the program logic in a natural language, such as English, interspersed with snippets of macros and traditional source code, from which a compilable source code can be generated.</p>
</blockquote>

<p>...</p>

<blockquote>
  <p>According to Knuth, literate programming provides higher-quality programs, since it forces programmers to <strong>explicitly state the thoughts behind the program</strong>, making poorly thought-out design decisions more obvious.</p>
</blockquote>

<p>Google dictionary defines literacy as "the ability to read and write." Well, ideally all developers can read and write code in their chosen language(s). Wouldn't all programing be literate? Depends on where you set the bar. A first grader is technically literate because he can cobble together some words by sounding out the syllables. But this isn't a rant about <a href="http://www.cnet.com/news/bill-gates-says-microsoft-bob-will-make-a-comeback/">MS Bob</a>, this is a rant about learning languages. So a bit about my experience as an ESL.</p>

<hr>

<p>In 1993 my family and I moved to America, and it was pretty obvious to those around me that I was an immigrant. Thinking back, here is the basic list of the tells:</p>

<p><em>Sentence Structure</em></p>

<ul>
<li><em>Description</em>: Coming from Russian, a language with no forced sentence order, one hurdle to learning English was sentence structure.  As a result, my sentences would sometimes become overly complicated and difficult to understand.  </li>
<li><em>Solution</em>: Translation at first, seeing the languages side by side and trying to understand the differences and similarities. Oh, and reading the language.</li>
<li><em>Years Later</em>: I learned to organize my thoughts in the paradigms of the English language.</li>
</ul>

<p><em>Lack of Vocabulary</em></p>

<ul>
<li><em>Description</em>: Without an extensive vocabulary it is almost impossible to communicate complicated ideas. The "big floating hotel boat" or "cruse ship" convey the same idea, but the correct terminology makes the communication efficient.</li>
<li><em>Solution</em>: Watching television. No, really! What a great way to learn a language. The pictures and words sync up for a better inferred meaning. Thank you, "Family Matters" and "Married with Children." Also, reading helped alot. A pattern emerges.</li>
<li><em>Years Later</em>: My vocabulary expanded, allowing me to more precisely craft my thoughts with elegant variation.</li>
</ul>

<p><em>Getting Lost in the Process of Translating</em></p>

<ul>
<li><em>Description</em>: I would often know what I wanted to express, but would get bogged down in the details of "how" to phrase my idea.</li>
<li><em>Solution</em>: Can't really stress enough the importance of reading.</li>
<li><em>Years Later</em>: Most appropriately the point of fluency in a language.</li>
</ul>

<p><em>Accent</em></p>

<ul>
<li><em>Description</em>: The Hunt for Red October's <a href="http://images7.alphacoders.com/342/342533.jpg">Sean Connery</a>.</li>
<li><em>Solution</em>: Just practicing speaking the language</li>
<li><em>Years Later</em>: Can't even fake a <a href="http://cdn.moviestillsdb.com/sm/b8ebcfdcc5be30e267b7044d1ed970e0/the-hunt-for-red-october.jpg">bad Russian accent</a> now.</li>
</ul>

<p>Well as a PSL (programing as a second language), we each have to take a very similar path when learning new programing languages. Lets take a look at the same tells in the field of programing:</p>

<p><em>Sentence Structure</em></p>

<ul>
<li><em>Description</em>: When a language learner translates a sentence into a new language, the complexity of both languages cloud the meaning of the sentence. The new programmer often brings much of the complexity of spoken language into the code they are writing.</li>
<li><em>Solution</em>: Read Code! Read books about code and code structure. Oh, the same pattern works here! Read code in open source projects. Programing languages are best learned by watching variations of language expression.</li>
<li><em>Years Later</em>: You learn to think in the constructs of the language and general computer logic.</li>
</ul>

<p><em>Lack of Vocabulary</em></p>

<ul>
<li><em>Description</em>: This is a real damper on the effectiveness of a green developer. This often leads to duplication of effort, the proverbial reinventing of the wheel. It also frequently diminishes the view of possible solutions, leading developers to work harder and not smarter.</li>
<li><em>Solution</em>: Read quality code. I feel like a broken record. But it was reading and listening to spoken English that helped me learn English, and it is reading quality code that helped me "learn" programing languages.</li>
<li><em>Years Later</em>: Obviously, I re-invent fewer wheels. But the benefits don't stop there. DSLs (<a href="http://en.wikipedia.org/wiki/Domain-specific_language">domain specific languages</a>), for example, open a whole new can of worms with syntax (vocabulary)</li>
</ul>

<p><em>Getting Lost in the Process of Translating</em></p>

<ul>
<li><em>Description</em>: Instead of thinking about the business logic surrounding some iteration of a list, a green developer thinks about the for loop and the variables involved to handle it.</li>
<li><em>Solution</em>: Read Code. Definitely a broken record. But read more code!</li>
<li><em>Years Later</em>: The logical abstractions come quicker, as many of the same abstractions are noticeable in many open source projects.</li>
</ul>

<p>Here are a couple of books that have helped get me here over the years:</p>

<ul>
<li><a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_2?s=books&amp;ie=UTF8&amp;qid=1425845120&amp;sr=1-2&amp;keywords=code+complete+3rd+edition">Clean Code</a></li>
<li><a href="http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/ref=sr_1_3?s=books&amp;ie=UTF8&amp;qid=1425845120&amp;sr=1-3&amp;keywords=code+complete+3rd+edition">Programit Programmer</a></li>
<li><a href="http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1425845120&amp;sr=1-1&amp;keywords=code+complete+3rd+edition">Code Complete 2</a></li>
</ul>

<hr>

<p>So the moral of that story is to read code. And by "reading code" I am talking about the "Common Core" style <a href="http://www.carsondellosa.com/products/104613__Differentiated-Reading-for-Comprehension-Resource-Book-104613#/?book%20media%20type=f389e45b92884d48844baaf09d49e3c5">reading for comprehension</a>. Introspect on the code and really try to understand the meaning and intent.  </p>

<p>So, crazy special <a href="http://vasc.ri.cmu.edu/old_help/Programming/Literate/literate.html#tools">IDE's/tools</a> aside, litarate programing simply asks you to translate your code into English. It is almost like double checking your long devision with multiplication. I am not really suggesting that you write a novel alongside your application code, or go full <a href="http://en.wikipedia.org/wiki/Donald_Knuth">Knuth</a> with a special IDE's; it's a cool idea, but just try getting everyone on your team on that same page. :)  </p>

<p>What I am suggesting is that thinking about the intent of our code should be a habit in the same way that unit testing should be a habit. The unit tests verify the integrity of you code, while the comments verify the sanity of those same lines. This is going to be a big goal in my personal improvement plan. Better fluency and code "sentence" structure will be the rewards, along with an assurance that the code solves the right problem.</p>]]></description><link>http://codeofserge.com/language-fluency/</link><guid isPermaLink="false">bb06a64e-a8ab-4027-b093-9a2500ac04e9</guid><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Mon, 09 Mar 2015 00:41:00 GMT</pubDate></item><item><title><![CDATA[unit testing controller resolvers]]></title><description><![CDATA[<p>We all know the secret to responsive <a href="https://docs.angularjs.org/api/ngRoute/directive/ngView">ng-view</a>s, right?  Well, it isn't really a secret.  I am talking about routeProvder.when <a href="https://docs.angularjs.org/api/ngRoute/provider/$routeProvider">resolvers</a> for pre-loading asynchronous server data. You really don't want your view sitting empty.</p>

<blockquote>
  <p>resolve - {Object.&lt; string, function >=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
  - key – {string}: a name of a dependency to be injected into the controller.
  - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.</p>
</blockquote>

<p>Ok, great: we have a factory function for getting some stuff from the server. On a route call to /Home, the resolver function returns some data. <em>(This data can be a promise, in which case the promise will first be resolved before the controller is instantiated.)</em></p>

<pre><code class="language-javascript">(function(angular) {
    'use strict';

    var app = angular.module('app', ['ngRoute']).config([
        '$routeProvider',
        function($routeProvider) {
            $routeProvider.when('/Home/:message?', {
                templateUrl: 'Home.html',
                controller: 'home',
                resolve: {
                    data: ['$route', function ($route) {
                        return "Test String Data" + $route.current.params.message;
                    }]
                }
            }).otherwise({redirectTo: '/Home'});
        }
    ]);

    app.controller('home', [
        "$scope",
        "data",
        function($scope, data) {
            $scope.message = data;
        }
    ]);
})(window.angular);
</code></pre>

<p>But now I have business logic in my configurations. Routing files, in my mind, are a configuration item and should not actually contain code. Keep in mind that your resolver factory function is also injectable, as the example injects $route. As a result, it can actually contain some pretty complicated business logic for looking up records. Let's take a look at an example that pulls from the server, and join the server information with some request message.</p>

<pre><code class="language-javascript">resolve : {  
  data : ['$route', '$http', '$q', function($route, $http, $q) {
      var deffer = $q.defer();
      $http.get('/Data').then(function(result){
          deffer.resolve([result.data.Value, $route.current.params.message].join(' '));
      });

      return deffer.promise;
  }]
}
</code></pre>

<p>It is easy to see that, even with such a small function, we now might want to look into doing some type of unit testing. But right now, the resolver is just an anonymous function--unless you bootstrap the whole angular stack and your http, which is doable, but does make the first <strong>"it"</strong> more difficult. So can we handle this in a slightly simpler manner? Just move the resolver factory function to where it can be unit tested.</p>

<pre><code class="language-javascript">app.provider('data', function () {  
        return {
            $get: function () {
                return {
                    home: [
                        '$route',
                        '$http',
                        '$q',
                        function ($route, $http, $q) {
                            var deffer = $q.defer();
                            $http.get('/Data').then(function (result) {
                                deffer.resolve([result.data.value, $route.current.params.message].join(' '));
                            });

                            return deffer.promise;
                        }
                    ]
                }
            }
        }
    });
</code></pre>

<p>And now that the resolver function exists as an artifact of a provider, we can expose it inside the config function.</p>

<pre><code class="language-javascript">var app = angular.module('app', ['ngRoute']).config([  
    '$routeProvider',
    'dataProvider',
    function ($routeProvider, dataProvider) {
        var data = dataProvider.$get();
        $routeProvider.when('/Home/:message?', {
            templateUrl: 'Home.html',
            controller: 'home',
            resolve: {
                data: data.home
            }
        }).otherwise({ redirectTo: '/Home' });
    }
]);
</code></pre>

<p><strong>To The Unit Test</strong></p>

<p>So far, we have made the resolver factory named instead of anonymous. But the holy grail here is really the unit test of the resolver function. The full source code can be found <a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/angular-unit-tesing-controller-resolvers/Content/test/app.test.js">here</a>  but the meat and potatoes is outlined in the test here. Variables prefixed with _ are, in this case, different mocks.</p>

<pre><code class="language-javascript">it('The the promise resolves to a combination of the get results and route messages', function() {  
    var result = fn(_route, _http, _q);
    expect(angular.isFunction(result.then)).toBe(true);
    result.then(function(data) {
        expect(data).toBe('test test');
    });

    _timeout.flush();
});
</code></pre>

<p>The result of <em>"test test"</em> matches the mock data being returned form the _http and _route mock objects. Naturally, this example is simplified. However, I have also done some work in which complicated async logic was executed in these functions.</p>

<p><strong>Conclution</strong></p>

<p>It isn't a big change to wrap the resolver function inside a provider, and the benefit of being able to test a pretty vital part of the applications is significant. We also gain the ability to re-use this resolver code since multiple resolvers can be used for a single route.</p>]]></description><link>http://codeofserge.com/unit-testing-controller-resolvers/</link><guid isPermaLink="false">755e964a-6f10-4c71-b509-249f549e7d47</guid><category><![CDATA[angular]]></category><category><![CDATA[unit testing]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Sat, 28 Feb 2015 22:12:32 GMT</pubDate></item><item><title><![CDATA[daydream: future of medical technology]]></title><description><![CDATA[<p>Every now and again, my boss asks my team and me to sharpen our minds by writing fiction. These brainstorming assignments are designed for team building and to unleash creative thought. The topic of this daydream is:</p>

<p><strong>What do you think is going to be the role of medical technology in 2030?</strong></p>

<hr>

<p>It started as "Folding At Home," a crowd-sourced project to map protein folding. For just a few watt hours a month, a home computer would think about the problem of protein folding while idle--a very ambitious project at a time in which the rate of technological change was still expected to follow Moore's law.</p>

<blockquote>
  <p>"Moore's law" is the observation that, over the history of computing hardware, the number of transistors in a dense integrated circuit doubles approximately every two years. The observation is named after Gordon E. Moore, co-founder of the Intel Corporation, who described the trend in his 1965 paper.</p>
</blockquote>

<p>Hindsight, they say, is 20/20, but it took less then forty years for Moore's law to crumble under the weight of its shortsightedness; nothing humans do is linear.</p>

<p>By the early 20th century, the two year estimate had shrunk to a year and a half; and by 2020, real competition for Intel finally emerged to drive innovation at breakneck speeds. Looking back on it, I am sure that Intel, AMD and Apple could never have imagined the world-changing computations that their ever-faster x86 chips were to unlock. But--as with any big conspiracy that starts in a small, smoky room--someone at AMD brainstormed a cheap benchmarking solution with a human-friendly spin. Not only do you trample the competition, but you do it while solving the problems of humanity. This all came at the tail end of a professor from Carnegie Mellon's eradication of AIDS through a retro-virus designed on crowd-sourced protein data--a great payoff on the Watt hour investment the early adopters contributed to the world. </p>

<p>Business only jumps on the wagon after viable profitability is displayed, but once it jumps, it sure adds some major momentum.  Even accounting for the multi-exponential revision to Moore's law, the years following the adaptation of benchmark saw a boom in technological leaps that made people's heads spin. The Intel "8086" event, iconic of the time, witnessed the release of a CPU with more cores then the 8086 had transistors. The news and consumers gave it little notice; it was reviewed as a "meta" on the 17th page of The Guardian. The news did, however, take notice when, in 2025, the last unique human protein fold was analyzed.  "While groundbreaking in the field of biology, we are now faced with finding a new benchmarking problem," an Intel employee was quoted saying. "For now, we will focus on the rest of the mammalian branch of life."</p>

<p>The real importance of news recognition came in the political and social support of human protein programing outside life threatening ailments. Much like the increasing speeds of computers, our understanding of natural processes of amino acids ballooned into new fields of research, bio-programing. The last year of "chemical-pills" was this year, 2027; nothing humans do is linear.</p>]]></description><link>http://codeofserge.com/daydream-future-of-medicise/</link><guid isPermaLink="false">4a3b810c-cb8a-41e6-8036-f33dfa894d73</guid><category><![CDATA[Daydream]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Sat, 28 Feb 2015 22:10:28 GMT</pubDate></item><item><title><![CDATA[polymorphism, not just for interviews]]></title><description><![CDATA[<p>If you have never watched/read anything by/about Richard Feynman you need to stop reading this post right now! There is a <a href="https://www.youtube.com/results?lclk=playlist&amp;filters=playlist&amp;search_query=richard+feynman">marathon</a> to be done.  He was a brilliant man with an amazing ability to de-construct complicated concepts into laymen-friendly terms.  In this <a href="http://youtu.be/zgJPjG4KJYQ?t=4m19s">video</a>, he talks about the difference between knowing something and knowing the name of something.  But he also points out the importance of having a common language.</p>

<blockquote>
  <p>5:14 - what he forgot to tell me was that the knowing the names are things is useful if you want to talk to somebody else.</p>
</blockquote>

<p>So it isn't surprising that a lot of people, including yours truly, do the following <a href="http://bit.ly/1g0Qh5j">google search</a> before going on job interviews.  Ideally, this is simply a lexical refresher for the abstractions and concepts you already use in your everyday work.  On the other hand, this could be real cramming.</p>

<blockquote>
  <p>In education, cramming ("mugging or swotting, from swot, akin to 'sweat', meaning 'to study with determination'") is the practice of working intensively to absorb large volumes of informational material in short amounts of time.</p>
</blockquote>

<p>In which case the person doing the search is trying to pull the wool over your eyes and make themselves appear more equitable then they are.  The reason for the interview.  This is why you should never ask those "interview questions" at your interviews. (<em>But this isn't an interview / interviewee / interviewer bashing post.</em>)</p>

<p>While the post is inspired by a real work interaction, the code in the examples are all faked, and no names will be used.  The villain of our clean code story will be <a href="http://en.wikipedia.org/wiki/Microsoft_Bob">Microsoft Bob</a> a diligent employee but sometimes misunderstood.</p>

<p><img src="http://upload.wikimedia.org/wikipedia/en/1/14/Microsoft_Bob.PNG" alt="BOB"></p>

<p><strong>Interview</strong></p>

<p>Since 'C++' we have all gone OO happy with our general language choices.  As a result polymorphism comes up in pretty much any interview for software engineering. And it better. This is something you really need to know as a software developer.  One of those, makes your life easier bits of knowledge.</p>

<p>But at an interview, generally the person is asked what it is? MS Bob is ready with a good replay.</p>

<blockquote>
  <p>In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. - Google Define.</p>
</blockquote>

<p>MS Bob even went into detailed examples of how it has been used in the past on project he has worked on.  </p>

<blockquote>
  <p>Creating custom data access layer to work with different DBMS.</p>
</blockquote>

<p>And so MS Bob gets hired.  But do we really know if MS Bob understands polymorphism.  For example, here Bob only worked on the project, another engineer may have created the structure which Bob was diligent enough to follow.</p>

<p><strong>Work</strong></p>

<p>Well the day to shine comes eventually to every developer where they create their own project from scratch.  To the developer this is the moment of truth.  MS Bob's moment came in the form of a calculator application.  And our imaginary MS Bob wrote:  <a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/polymorphism-not-just-for-interviews/bob_code.linq">full LinqPad example</a></p>

<pre><code class="CSharp">void Main()  
{
  var m = new Math();
  m.process("add", 1, 2).Dump();
}

public class Math {

  public int process(string type, int n1, int n2) {
    int result;
    switch (type) {
      case "add":
      result = n1 + n2;
      break;

      ...

      case "div" :
      result = n1 / n2;
      break;

      default :
      result = 0;
      break;
    }
    return result;
  }
}
</code></pre>

<p>Needless to say, this solution lacks a level of elegance OO allows us.  As result this solution <br>
 - hard to expand on.  Adding a new operation for example will require a full round of testing for all the other features. <br>
 - doesn't embody the concept of separation of concerns
 - hard to unit test because each test ends up testing multiple concerns.
 - not to mention the needless increase in cyclomatic complexity.</p>

<p>MS Bob's switch case had to go.</p>

<p><strong>Polymorphic Solution</strong></p>

<p>The process function in the math class is doing multiple things.  It is figuring out what the operation is, and then it is preforming it.  <a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/polymorphism-not-just-for-interviews/poly_code.linq">full LinqPad example</a></p>

<pre><code class="CSharp">void Main()  
{
  (new Add()).process(1, 2).Dump();
  (new Sub()).process(1, 2).Dump();
}

public interface Math  
{
  int process(int n1, int n2);
}

public class Add : Math  
{
  public int process(int n1, int n2)
  {
    return n1 + n2;
  }
}

...

public class Div : Math  
{
  public int process(int n1, int n2)
  {
    return n1 / n2;
  }
}
</code></pre>

<p>Ok, so lets see how this code holds up to the scrutiny we placed on Bobs code.</p>

<ul>
<li><strong>hard to expand on</strong> Not at all, i can create a new project import this assembly and create any number of math operations that take two integers and result in an integer.  Endless possibilities for growth.</li>
<li><strong>doesn't embody the concept of separation of concerns</strong> Each operation is implemented in it's own class.  Addition knows nothing about subtraction and vice versa.  Also there is no conditional logic required.</li>
<li><strong>hard to unit test</strong> Not at all.  Since each class is only responsible for one thing, each class only really needs to be tested against it's primary function.  The are no conditional branches so failed tests are easy to trouble shoot.</li>
<li><strong>needless increase in cyclomatic complexity</strong> As pointed out above, there are no branching conditionals in this code.</li>
</ul>

<p><strong>Conclusion</strong></p>

<p>So MS Bob is made up, but switch statements are littered through out much of the code I end up reading.  It is a lazy solution in a scenario where clean code polymorphic solution is just as easy to create.  But this is the difference between knowing the name of something and knowing something as Richard Feynman so cleverly explained in the video.</p>

<p>While I am not saying that you should never use a switch, the polymorphic solution fits much better into the modern day tool kit.  Dependency injection containers for example are a great tool for application composition. And this type of polymorphic programing fits like a glove with convention/interface based dependency resolution.</p>

<p>Also, MS Bob will make future appearances, and while todays instance of MS Bob relates to a specific interaction I had at work, I too was once MS Bob on this subject.  The concepts aren't hard to get, but even with out practice knowing the name isn't enough.</p>]]></description><link>http://codeofserge.com/polymorphism-not-just-for-interviews/</link><guid isPermaLink="false">12453dbe-e4cc-4b86-85e9-cc8d4cd01f37</guid><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Mon, 26 Jan 2015 21:40:50 GMT</pubDate></item><item><title><![CDATA[@script, annotation and angular 1.x]]></title><description><![CDATA[<p><code>Note, this post has been edited on 12/11/2014 and 01/12/2015.  These changes were made to keep the code base changes to handle routing and directives.</code></p>

<p>A previous <a href="http://codeofserge.azurewebsites.net/script-annotation-for-the-win/">post</a> talked about a general idea behind data annotation and the ability to mark up classes. But the example was far from being real world or useful.  Today we are going to explore the way that data annotation can be used to decouple business logic with angular bindings.  We are in search of a simpler solution to ES6 modules or RequireJS and Angular modules.</p>

<p><strong>Module Pattern and Angular</strong></p>

<p>ES6 brings us modules and the "import" keyword for better composition management, which basically means that this code:</p>

<pre><code class="language-javascript">import {ngBase} from './ngBase';  
</code></pre>

<p>transforms into RequireJS code that creates a dependency and on './ngBase</p>

<pre><code class="language-javascript">define(['./ngBase'], function($__0) {  
  "use strict";
  if (!$__0 || !$__0.__esModule)
  $__0 = {default: $__0};
  var ngBase = $__0.ngBase;
});
</code></pre>

<p>Nicely enough, ngBase becomes the variable into which the import is piped, scoped to the wrapper function. So how does this play with something like Angular which has its module system. A quick look online brings about a general consensus that the module pattern is good for business logic, but the angular bootstrapping should take place once the require js modules are loaded.</p>

<ul>
<li><a href="http://www.sitepoint.com/using-requirejs-angularjs-applications/">http://www.sitepoint.com/using-requirejs-angularjs-applications/</a></li>
<li><a href="http://solutionoptimist.com/2013/09/30/requirejs-angularjs-dependency-injection/">http://solutionoptimist.com/2013/09/30/requirejs-angularjs-dependency-injection/</a></li>
<li><a href="http://marcoslin.github.io/angularAMD/#/home">http://marcoslin.github.io/angularAMD/#/home</a></li>
<li><a href="http://stackoverflow.com/questions/12529083/does-it-make-sense-to-use-require-js-with-angular-js">http://stackoverflow.com/questions/12529083/does-it-make-sense-to-use-require-js-with-angular-js</a></li>
</ul>

<p>Each of these post talks about creating non-angular aware modules that are later bootstrapped in another bootstrapping file. In my mind, this is a bit messy.  When anything changes, you must change the bootstrapping file and the implementation file logic. But data annotation solves this problem. We can defer bootstrapping by marking our classes with all required data annotations to complete the late bootstrapping.</p>

<p><strong>Annotate it All</strong></p>

<p>So data annotation lets us create classes that understand their own purpose. Ideally, anything in Angular can be broken down into a class constructor function with annotation that defines the class function.</p>

<p>We annotate the controller/factory/directive name and dependency list into the ngController/ngFactory/ngDirective and ngInject annotation.</p>

<p><strong>Annotation Classes</strong></p>

<p>The magic behind this type of annotation is a collection of annotation classes that can register the class it annotates against an angular module.</p>

<p><a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/script-annotation-and-angular-1x/src/lib/ngBase.ats">ngBase</a> class is an abstract that all Angular-based annotations derive from. We do have a useful <em>wrap</em> function, which allows us to wrap the Angular array notation for dependency injection. The ngBase class is common ground for all Angular annotations from Angular registering functions (ngController/ngFactory/ngDirective).</p>

<p><a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/script-annotation-and-angular-1x/src/lib/ngController.ats">ngController</a> class is an actual annotation class. It describes controllers to angular modules. The register function, which is aware of annotation on the class, can work in combination with other annotations like route and inject. The controller annotation simply takes the name.</p>

<pre><code class="language-javascript">@ngController('main')
@ngInject(['$scope', 'data'])
@ngRoute('/Home', { templateUrl : 'home.html' });

export class main {  
  constructor($scope, data) {
    $scope.data = data();
  }
}
</code></pre>

<p><a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/script-annotation-and-angular-1x/src/lib/ngFactory.ats">ngFactory</a> annotation class for creating factories, the Angular version of a singleton.  Like ngController, it also works in combination with</p>

<pre><code class="language-javascript">@ngFactory('data')

export class data {  
  constructor() {
    return () =&gt; "test";
  }
}
</code></pre>

<p><a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/script-annotation-and-angular-1x/src/lib/ngDirective.ats">ngDirective</a> annotation class for creating directives has some additional logic. Like the other ngBase classes the name of the directive is the first argument of the annotation constructor and the directive property object as the second argument. The constructor of the annotated class automatically becomes the link function on the directive object.</p>

<pre><code class="language-javascript">@ngDirective('hello', {
  scope : true,
  template : '&lt;div&gt; hello {{data}}&lt;/div&gt;',
  restrict : 'AE'
})
@ngInject(['data'])
export class hello {  
  constructor(data) {
    return (scope, element, attr) =&gt; {
      scope.data = data();
    }
  }
}
</code></pre>

<p><strong>The Bootstrapper</strong></p>

<p>Annotations can bind behavior to a class, and we can process the behavior by looking at injectable dependencies. The <a href="https://github.com/SergeiGolos/CodeOfSerge/blob/master/script-annotation-and-angular-1x/src/lib/ngBootstrap.ats">ngBootstrap</a> class processes a list of imports. In our bootstrapping process, this is denoted by arguments based on how Tracuer transpiles this code.</p>

<pre><code class="language-javascript">import {ngBootstrap} from './lib/ngBootstrap';  
import {data} from './data';  
import {main} from './main';  
import {hello} from './hello';

var app = ngBootstrap(document, angular.module('test', []), arguments);  
</code></pre>

<p>Transpiled, we get this code, which explains the argument's object.</p>

<pre><code class="language-javascript">define(['./lib/ngBootstrap', './data', './main', './main2', './hello'], function($__0,$__2,$__4,$__6,$__8) {  
  "use strict";
  if (!$__0 || !$__0.__esModule)
  $__0 = {default: $__0};
  if (!$__2 || !$__2.__esModule)
  $__2 = {default: $__2};
  if (!$__4 || !$__4.__esModule)
  $__4 = {default: $__4};
  if (!$__6 || !$__6.__esModule)
  $__6 = {default: $__6};
  if (!$__8 || !$__8.__esModule)
  $__8 = {default: $__8};
  var ngBootstrap = $__0.ngBootstrap;
  var data = $__2.data;
  var main = $__4.main;
  var main2 = $__6.main2;
  var hello = $__8.hello;
  var app = angular.module('test', ['ngRoute']);
  ngBootstrap(document, app, arguments);
  return {};
});
</code></pre>

<p><strong>Conclusion</strong></p>

<p>You can find running code examples <a href="https://github.com/SergeiGolos/CodeOfSerge/tree/master/script-annotation-and-angular-1x">here</a></p>

<p>This post gave a real world example of the usefulness of data annotation. But there is a lot more. There are benefits to decoupling the application from Angular. The annotation can be quickly re-writen to bind a different framework to your current classes. There are benefits to unit testing a directive without needing to bind to angular.</p>

<p>Overall, data annotation is a tool for the tool box, and more posts will come on how this tool is useful.</p>]]></description><link>http://codeofserge.com/script-annotation-and-angular-1x/</link><guid isPermaLink="false">3d028ba6-63c5-41b8-a56f-10123a34b34e</guid><category><![CDATA[@script]]></category><category><![CDATA[annotation]]></category><category><![CDATA[angular]]></category><category><![CDATA[requirejs]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Tue, 13 Jan 2015 03:20:00 GMT</pubDate></item><item><title><![CDATA[y combinator]]></title><description><![CDATA[<p>Every now and again you hear developers at some programming event talking about this fabled myth of a function, the understanding of which will transcend you to a new plane of programming.   Well, challenge accepted.  Spoiler, I am still among us mortals.</p>

<p><strong>Thinking About the Problem</strong></p>

<p>The first place you go: <a href="http://en.wikipedia.org/wiki/Fixed-point_combinator#Derivation_of_the_Y_combinator">wiki</a>.  If you are anything like me,  lambda calculus hurts your head and only paints a fuzzy picture.  Heavy math aside, what problem does it solve? It lets us have recursion of anonymous functions.</p>

<p><strong>Factorial function to the rescue</strong></p>

<pre><code class="language-javascript">function factorial(num) {  
  return num === 0 ? 1 : num * factorial(num -1);  
}  
</code></pre>

<p>To define recursion you must first define recursion.  </p>

<p>But seriously, in order to be able to make this function anonymous, we need to get rid of our dependency on "<em>factorial</em>"  I agree, crazy.  But lets give it a try.  Some closure?  Maybe we can  wrap it in a function? We no longer call the function by its name, does that help? Maybe if we can somehow call the wrapper function with the result of itself.</p>

<pre><code class="language-javascript">function(factorial) {  
  return function(num) {   
    return num === 0 ? 1 : num * factorial(num -1);  
  };
}
</code></pre>

<p>And queue the entrance of the Y Combinator!</p>

<pre><code class="language-javascript">function Y(bindFn) {  
  return function () {  
    return bindFn(Y(bindFn)).apply(null, arguments);  
  };  
}  
</code></pre>

<p><strong>Untwisting the Pretzel</strong></p>

<p>Right, that's what I thought, that a bit crazy. The factorial wrapper gets passed into it self, is that even possible?  Seems so, here is a trace: (<a href="http://jsbin.com/rakica/edit?js,console">jsbin</a>)  </p>

<p>There is a beauty to this almost mechanical algorithm, reminiscent of the sewing machine or the RNA copy mechanism.  </p>

<ul>
<li>Wrap the anonymous function.</li>
<li>Send in the wrapped anonymous function into the Y combinator function.</li>
<li>Unpack the anonymous function and execute it, by passing the Y combinator result of the wrapped function into the wrapped function.</li>
</ul>

<p><img src="http://materialmama.files.wordpress.com/2007/01/ani_lockstitch2.gif?w=371&amp;h=387" alt="sewing machine"></p>]]></description><link>http://codeofserge.com/y-combinator/</link><guid isPermaLink="false">4544635e-53b9-49e7-8fab-723e1d85ed79</guid><category><![CDATA[Theory]]></category><category><![CDATA[Functional]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Fri, 09 Jan 2015 16:59:20 GMT</pubDate></item><item><title><![CDATA[@script, annotation for the win]]></title><description><![CDATA[<p>While everyone is fawning over Angular 2.0, it isn't something we can really use for a while. But Tracuer and @script are here, and--as long as you support IE9 and up--they are here for you today.</p>

<p>The Angular team published a playground for @script: <a href="https://github.com/angular/atscript-playground">https://github.com/angular/atscript-playground</a></p>

<hr>

<p><strong>So why is annotation-oriented programing so much win?</strong></p>

<p>The quick answer is meta programing. <em>Buzz word alert</em>: The basic idea is that you can mark up some object in your code with additional meta-information. And the cool part: parse that mark up at runtime to give your application additional intelligence.</p>

<p>But lets take a quick look:  </p>

<pre><code class="language-javascript">// An annotation class that defines an animal
class animal {  
  constructor(sound) {
    this.sound = sound;
  }
  speak() {
    console.log(this.sound);
  }
}
</code></pre>

<p>An annotation is really just the instantiation of some class that can be bound to an 'annotations' property on the target class.  The above code created an annotation class called "animal."  When instantiating a class, we can create animal with a custom sound.  As the example bellow shows, the @script annotation syntax allows us to attach the annotation class of "animal" to any classes we create like "cow" or "dog" targets.</p>

<pre><code class="language-javascript">// Create a cow class an annotate it with a cow sound.
@animal('Mooo')
class cow {  
}

// Create a dog class and annotate it with a dog sound.
@animal('Woof')
class dog {  
}
</code></pre>

<p>This is @script transpilation; the @animal('Woof') actually translates to the following JavaScript.</p>

<pre><code class="language-javascript">var dog = function dog() {};  
($traceurRuntime.createClass)(dog, {}, {});
Object.defineProperty(dog, "annotations", {get: function() {  
  return [new animal('Woof')];
}});
</code></pre>

<p>After the classes are marked up with annotation, a new property, 'annotations,' becomes available on the class object. It is an array, allowing for multiple annotations to be applied to a class.</p>

<pre><code class="language-javascript">cow.annotations[0].speak() //=&gt; Mooo  
dog.annotations[0].speak() //=&gt; Woof  
</code></pre>

<p>This is nothing revolutionary, but it does create a great convention, allowing us to write code that describes itself to itself.  Lets take a look at a way that this can be consumed. In the code example,  <a href="https://lodash.com/">lo-dash</a>, it is used for writing functional code, I am a lambda whore.</p>

<pre><code class="language-javascript">_.each([cat, dog, table], c =&gt; {  
  var noop =  { speak : () =&gt; {}};
  (c.annotations || [ noop ])[0].speak();
  });
</code></pre>

<p>Each loop can process the individual classes for the annotation property. In more complicated workflows, this can take into account the different annotation classes.  </p>

<p><strong>Conclusion</strong></p>

<p>You can find running code examples <a href="https://github.com/SergeiGolos/CodeOfSerge/tree/master/script-annotation-for-the-win">here</a>.</p>

<p>The code example above is not very useful, since any number of polymorphic practices can resolve this problem in much cleaner ways. But it does show how annotations can create behaviors on classes that you may not have the rights to change.  Annotation also get out of the way of the implementation, allowing you to attack cross cutting concerns without affecting the annotated class.</p>]]></description><link>http://codeofserge.com/script-annotation-for-the-win/</link><guid isPermaLink="false">eaf7c335-db02-4a7e-84b3-d0f72e59ee67</guid><category><![CDATA[@script]]></category><category><![CDATA[annotation]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Wed, 03 Dec 2014 00:27:13 GMT</pubDate></item><item><title><![CDATA[it begins]]></title><description><![CDATA[<p>Why do I code?</p>

<ul>
<li>I get paid for it.</li>
<li>I like the creativity it unleashes.</li>
<li><em>I seek to communicate</em> (with computers).</li>
<li>I played with legos as a kid, and programing is damn close.</li>
</ul>

<p>Originally I started coding because I wanted to be like my dad.  This is shortly after I wanted to be a fireman and cosmonaut.  One day, Dad showed up with a computer from work, and that night we "pair programmed" a times table program.  A life long love was born.</p>

<p>My hope is that, as a reader, you are here because you too share a fanatical dedication to your craft.</p>

<p><strong>Conventions</strong></p>

<ul>
<li><strong>MS Bob</strong> When dealing with programing concepts, every now and again the bad ideas need to be highlighted.  What better scapegoat then <a href="http://en.wikipedia.org/wiki/Microsoft_Bob">MS Bob</a>.</li>
</ul>]]></description><link>http://codeofserge.com/it-begins/</link><guid isPermaLink="false">90f4a428-9c04-4fc2-b8f3-c2abd2c2991a</guid><category><![CDATA[babble]]></category><category><![CDATA[bio]]></category><dc:creator><![CDATA[Sergei Golos]]></dc:creator><pubDate>Mon, 01 Dec 2014 02:35:55 GMT</pubDate></item></channel></rss>