<?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" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Code and Beyond]]></title><description><![CDATA[Blog by Bart Sokol]]></description><link>https://bart-sokol.info/</link><image><url>https://bart-sokol.info/favicon.png</url><title>Code and Beyond</title><link>https://bart-sokol.info/</link></image><generator>Ghost 3.12</generator><lastBuildDate>Tue, 01 Apr 2025 22:56:33 GMT</lastBuildDate><atom:link href="https://bart-sokol.info/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[An Introvert's Perspective on The Software Industry]]></title><description><![CDATA[<h3 id="the-world-of-software-development-is-quite-a-specific-environment-the-fast-pace-of-technological-advances-puts-developers-on-the-front-of-constant-changes-environment-requirements-technologies-people-companies-everything-is-in-everlasting-flux-being-a-software-developer-has-some-upsides-it-usually-pays-well-can-give-quite-a-lot-of-satisfaction-and-allows-people-to-do-things-that-were-often-impossible-before-but-nothing-comes-without-its-downsides-especially-when-you-re-an-introvert-">The world of software development is quite a specific environment. The fast pace of technological advances puts developers on the front of constant changes — environment, requirements, technologies, people, companies — everything is in everlasting flux. Being a software developer has some upsides — it usually pays well, can give quite a lot</h3>]]></description><link>https://bart-sokol.info/2018/09/28/an-introverts-perspective-on-the-software-industry/</link><guid isPermaLink="false">5badf546d9713030b841070c</guid><category><![CDATA[thoughts]]></category><category><![CDATA[software]]></category><category><![CDATA[introvert]]></category><category><![CDATA[office]]></category><category><![CDATA[english]]></category><category><![CDATA[remote]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Fri, 28 Sep 2018 12:00:00 GMT</pubDate><media:content url="https://bart-sokol.info/content/images/2018/11/cory-schadt-127740-unsplash--1-.jpg" medium="image"/><content:encoded><![CDATA[<h3 id="the-world-of-software-development-is-quite-a-specific-environment-the-fast-pace-of-technological-advances-puts-developers-on-the-front-of-constant-changes-environment-requirements-technologies-people-companies-everything-is-in-everlasting-flux-being-a-software-developer-has-some-upsides-it-usually-pays-well-can-give-quite-a-lot-of-satisfaction-and-allows-people-to-do-things-that-were-often-impossible-before-but-nothing-comes-without-its-downsides-especially-when-you-re-an-introvert-">The world of software development is quite a specific environment. The fast pace of technological advances puts developers on the front of constant changes — environment, requirements, technologies, people, companies — everything is in everlasting flux. Being a software developer has some upsides — it usually pays well, can give quite a lot of satisfaction and allows people to do things that were often impossible before. But nothing comes without its downsides—especially when you’re an introvert.</h3><h2 id="culture">Culture</h2><img src="https://bart-sokol.info/content/images/2018/11/cory-schadt-127740-unsplash--1-.jpg" alt="An Introvert's Perspective on The Software Industry"><p>It has been written a lot about the specifics of the culture in the world of technology. More, faster, better, growth, competition, race, winner takes it all… The polarization of ideas is visible here as much as it’s seen lately on the political scene. You’re either the one that wins or you’re out of the game. This can be observed both on the market level — where companies engage in often deadly fights — as well on the personal level, where being average often means you’re below expectations.</p><p>Money is a crucial aspect in many cases. It’s what pays for expensive cars, big houses, exotic trips, newest and shiniest toys, an inflated lifestyle that is often associated with being a successful developer. But it doesn’t end there. It has to pay for all the parties, alcohol, drugs, whatever comes in the bundle. Work hard, party hard — the motto I’ve heard much too often. Even if there is some surface of understanding of other people’s needs, it’s often a convenient topic for gossips and laughter. You don’t want to stand out, you don’t want to be different — you know what would be the cost.</p><p>But people are different. People do have different needs and preferences. There is no “one-size-fits-all” solution. Yet there is an expectation that you will fit into someone’s vision. If you don’t, you’re often referred to as “not made to be a developer”. You are considered to be a problem. That’s even harder if you’re an introvert — you won’t shout and fight to get your needs fulfilled. Especially in the corporate environments, people with a high capability for small talk, political plays, socializing, fighting for their needs will quickly advance their careers and make introverts feel like some worse kind of person and willing to escape.</p><h2 id="work-environment">Work environment</h2><p>Open space. Meetings. Calls. Nights out. All the team building and socializing activities. While there are some benefits of all of them, they all come at the cost. Things can go very quickly very badly, especially if you’re an introvert. The noise, constant distractions, all the small talks and gossips, long periods without time alone — all of this takes a big toll. Even seemingly small things like improper lighting can cause a constant drain if you’re a highly sensitive person.</p><p>Creating a really people-friendly office comes at a cost. Creating an introvert-friendly office is even more expensive. That’s why I prefer to work from home. It’s not a perfect solution — introverts still need some level of human contact, maybe other people’s opinion, even a bit of small talk — but at least it gives a time and space to focus enough to do some work without feeling like a wreck afterwards. Finding the right balance in the office is usually very hard, and again the ones that are the loudest and most willing to fight for their needs are there to win.</p><h2 id="deeper-meaning">Deeper meaning</h2><p>We all need some reasons to do our work. For some, it’s the financial motivation. For others, it may be some interest in what they are doing. There are also people who look for some deeper sense in what they do — like serving humanity, fighting diseases, making people’s life easier, saving the planet, name your own. It’s definitely possible to do meaningful work as a software developer. The problem is that the vast majority of software jobs are all about making money. Usually making more money, for people who already have a lot of money. That’s why this job pays so well — not because it’s so meaningful, but because it’s so financially valuable.</p><p>The right software could help with solving a lot of issues humanity is dealing with. It can help to bring the right people together, help them to collaborate, process important information. The problem is that it is now very expensive, due to inflation caused by the high wages of corporate developers. Spending big amounts of money by the charity or some NGOs on developing custom software or hiring well-paid developers can be a challenge. Many of those organizations rely on free, open-source software, but as with anything in the world — that also doesn’t come for free. It’s also very hard to handle the specific needs of those organizations with the generic software.</p><p>While the problem is not specific to introverts, it’s very common for an introvert to seek for a deeper meaning in work. That’s definitely true for me, and it’s a real struggle. Money is important in our society, even if only to live without unnecessary stress of survival. If you want to take an advantage of human development in virtually any area, you need money. Yet finding the right job, that would give a deeper sense of meaning while paying enough to not stress about money is pretty hard.</p><h2 id="conclusions">Conclusions</h2><p>I feel like I barely scratched the surface of the problem here. There are many things that are far from perfect in the software industry, and taking care of people is one of the most overlooked. It’s probably not specific to the software field — but definitely highly visible here. Being an introvert, apart from having its upsides, can be a challenge in many areas of life in the extrovert world. As with any other somehow discriminated groups, there should be more awareness of the issue and will to adjust to make the software development industry more open and kind for all humans. Diversity brings richness which cannot be exchanged for anything else.</p><hr><p><em>What are your thoughts and observations? Are you an introvert or an HSP? Did you experience quiet people quit without telling the reasons? Is your work environment respectful of people’s needs? I’d love to hear from you!</em></p><p><em>Photo by <a href="https://unsplash.com/photos/Hhcn6yy3Uo8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Cory Schadt</a> on <a href="https://unsplash.com/search/photos/busy-city?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</em></p>]]></content:encoded></item><item><title><![CDATA[Say Hi to Monacs: a colection of monads for C#]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>A bit over a year ago we started a rewrite of one of the core functionalities of our system. I was really tempted to use F# for that, but the other team members were not so sure. We've agreed upon sticking with C# but use more functional and <a href="https://fsharpforfunandprofit.com/rop/">railway-oriented programming</a></p>]]></description><link>https://bart-sokol.info/2018/02/02/say-hi-to-monacs-a-colection-of-monads-for-c/</link><guid isPermaLink="false">5a748938c44b993146fdc710</guid><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Fri, 02 Feb 2018 16:44:06 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>A bit over a year ago we started a rewrite of one of the core functionalities of our system. I was really tempted to use F# for that, but the other team members were not so sure. We've agreed upon sticking with C# but use more functional and <a href="https://fsharpforfunandprofit.com/rop/">railway-oriented programming</a> inspired approach. This forced us to come up with a way to do it. We could stick with some of the existing libraries available (like <a href="https://github.com/louthy/language-ext/">language-ext</a>, which one of our teams was already using) or try to implement it by ourselves. As you may guess, we have taken the latter path and it led us to the successful delivery of multiple projects using this approach.</p>
<p>As the code we shared between the projects was pretty simple yet very useful, we wanted to share it with other developers outside of our organization. It wasn't so easy as it seems to be, unfortunately, but finally, after many hours spent on recreating things from scratch, I made it <a href="https://github.com/MonacsLib/Monacs/">available publicly on GitHub</a>.</p>
<h2 id="whatismonacs">What is Monacs?</h2>
<p>It's intended to be a simple and lightweight way to introduce some bits of functional and railway-oriented programming to the C# projects. Currently, you'll find two core monads inside the library: <code>Option</code> and <code>Result</code>. Both of the types are complimented by a set of extension methods, including constructors, <code>Bind</code> and <code>Map</code>. It allows you to write code in more railway-oriented style, as in this example:</p>
<pre><code class="language-csharp">public async Task&lt;Result&lt;Cart&gt;&gt; GetCart(CartRequest request) =&gt;
    await Validator.Validate(request)
        .Map(RequestMapper.ToDomain)
        .BindAsync(_getCartContext.Create)
        .BindAsync(BusinessValidator.Validate)
        .MapAsync(_operation.Execute)
        .BindAsync(cart =&gt; _storage.Persist(cart))
        .DoWhenErrorAsync(_logger.Error);
</code></pre>
<p>I've done a few presentations about this approach (<a href="https://www.youtube.com/watch?v=BmTJaYkjWAg">here is recording in Polish</a>) and also <a href="https://bart-sokol.info/2017/02/05/an-alternative-take-on-application-architecture/">wrote about it earlier</a>. It basically allows you to reduce the noise and helps to flatten the structure of class dependencies, leading to easier reasoning about the code and its goal. Head to <a href="https://github.com/MonacsLib/Monacs/blob/master/docs/Index.md">the docs</a> for some more details.</p>
<h2 id="whatsthestatus">What's the status?</h2>
<p>The current library version is 0.1, which means it's still in development and APIs are subject to change. The core functionality shouldn't change much though and I expect to only add functionalities in the upcoming releases, so the risk of using it shouldn't be that high ;). It's also covered by quite a few unit tests so hopefully, the quality shouldn't disappoint. Documentation is in progress, I hope to get nice documentation of the API for next release with <a href="https://github.com/MonacsLib/Monacs/issues/4">the help of contributors</a>.</p>
<h2 id="howcaniuseit">How can I use it?</h2>
<p>Grab it straight <a href="https://www.nuget.org/packages/Monacs.Core/">from NuGet</a> using your favourite package manager. Go through the <a href="https://github.com/MonacsLib/Monacs/blob/master/docs/QuickStart.md">Quick Start tutorial</a> if you need some examples how you can use it.</p>
<h2 id="thefuture">The future?</h2>
<p>The plans for the future development include:</p>
<ul>
<li><code>Unit</code> type and related methods to make your code more consistent;</li>
<li>documentation updates mentioned earlier;</li>
<li>sample project to demonstrate the capabilities;</li>
<li>more extension methods, e.g. to integrate nicely with <code>IEnumerable&lt;T&gt;</code> and <code>Task&lt;T&gt;</code>;</li>
<li>possibly some other monads (<code>Either</code>?) - I'm open for proposals here.</li>
</ul>
<h2 id="howcanihelp">How can I help?</h2>
<p>Start using it and give me some feedback! I also accept contributions like pull requests, documentation updates, bug reports and so on. <a href="https://github.com/MonacsLib/Monacs/">GitHub page of the Monacs library</a> will be always happy to see you :).</p>
<h2 id="lastwords">Last words</h2>
<p>If you have any questions or comments, feel free to ask here, on <a href="https://twitter.com/bartsokol">Twitter</a> or using <a href="https://github.com/MonacsLib/Monacs/issues/">GitHub issues</a>. I hope this library will help some of the developers <a href="https://bart-sokol.info/2018/01/26/what-makes-a-good-software/">create better software</a>. Thanks for coming in, and enjoy!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Stop the tyranny of office hours]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>There are two basic schemes for compensation - goal-based and time-based.</p>
<p>The former one is known to humanity for ages, since the beginnings of commodity exchange. We get something and give something else in exchange. In software development, the well-known (and, surprisingly, much-hated) example would be fixed-price projects. You get</p>]]></description><link>https://bart-sokol.info/2018/01/29/stop-the-tyrany-of-office-hours/</link><guid isPermaLink="false">5a6eef0cc44b993146fdc705</guid><category><![CDATA[productivity]]></category><category><![CDATA[thoughts]]></category><category><![CDATA[office]]></category><category><![CDATA[trust]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Mon, 29 Jan 2018 17:52:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>There are two basic schemes for compensation - goal-based and time-based.</p>
<p>The former one is known to humanity for ages, since the beginnings of commodity exchange. We get something and give something else in exchange. In software development, the well-known (and, surprisingly, much-hated) example would be fixed-price projects. You get paid for what you deliver, no matter how much is it going to cost you.</p>
<p>The latter one became very popular during the industrial revolution when someone needed to spend a given amount of time on the production line to be able to output a given amount of artefacts. Of course, it was possible to measure the effects and give compensation based on the effects, but it was very often used in other ways, often as a tool of oppression. If you won't make enough of X, you won't get paid or will be punished in some other way.</p>
<p>As a software consultant I'm being paid for the hours I spend working. This is a double-edged sword. From one side, it allows me to get money for the actual time I spend working, or at least it seems so. From the other side, it gives me a pressure to work (at least) a given number of hours, whether it makes sense or not. That's the time I need to spend most often staring at the screen, no matter if it actually helps to achieve the desired result or not. &quot;That's what they pay for&quot;, one may think.</p>
<p>The problem is that not all work that needs to be done is actually being done while sitting at the desk, or even while being in the office. And the time being &quot;present&quot; doesn't really equal time spent on work. There is a lot of work being done outside of that time and lots of mental energy is being used to solve the issues, even when one's not in the office nor in front of their computer or smartphone. And it's very often the most valuable work, as it's the result of much deeper thinking that one is able to forcibly attempt.</p>
<p>Who's actually working more? A person leaving work early and then sitting in their car in the traffic jam, thinking about possible solutions for the problem they've faced today at work? Or a person that sits long hours in the office scrolling through the facebook wall? In any creative trade, there is a time spent on producing the actual output and a time spent on figuring out what should be that output. Of course, there are things that require one's presence in given place at given time. There are also tasks that are mechanical and require very little thinking. If it's all that one does then it's OK - they get paid for the time spent on doing just that. But if one's work requires any kind of creativity and time spent not directly on producing artefacts, it should be counted as the work hours as well. No matter what else are they doing in a meanwhile.</p>
<p>As there are no ways to effectively measure the time one spends on the creative work-related tasks, we should stop trying to measure it at all. You cannot measure person's attitude, you cannot count one's thoughts, there aren't even any reliable ways to measure the task progress. The continuous urge to find the way to do it is having a negative impact on everyone involved.</p>
<p>When building any kind of relationship, the trust is one of the key factors required for success. Unfortunately, when money is on the table, the trust is being put away in favour of control. The relationship becomes the dictatorship. And you cannot build a sustainable business from tyranny. Instead of focusing on control, put your attention on providing all the inputs others may need to effectively solve the problem they're ought to solve. Don't count the hours, examine the attitude and the output instead. Let people decide how much time is actually needed to solve the problem, and you'll get the best possible output.</p>
<p>Build your business around the trust: have a good faith in people's intentions from one side, and show that you're trustworthy from the other. Being paid for every hour made me value time even more - not only mine but also other's. And the value is not only in money - it is in all other things that one may be doing at the same time. Let people do what they think is the most important at any given moment and you'll get their best.</p>
<p>Whenever you'll enforce the rules, there will be an urge to break them. Trust is much stronger obligation than control. Value people's time and they will value yours. The value of one's creative work is not in the number of hours worked but in the quality of that time. Let's finish with the industrial revolution approach in the creative fields. Let's stop the office hours tyranny.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[What makes a good software?]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Writing a piece of software is a damn hard task. Writing a piece of good software is Sisyphus work - once you think you've nailed it, everything falls down into pieces. So is there a way to actually create something that could be awarded a &quot;good software badge&quot;</p>]]></description><link>https://bart-sokol.info/2018/01/26/what-makes-a-good-software/</link><guid isPermaLink="false">5a6776ddc44b993146fdc6fa</guid><category><![CDATA[programming]]></category><category><![CDATA[architecture]]></category><category><![CDATA[software]]></category><category><![CDATA[design]]></category><category><![CDATA[naming]]></category><category><![CDATA[error handling]]></category><category><![CDATA[exceptions]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Fri, 26 Jan 2018 18:18:46 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Writing a piece of software is a damn hard task. Writing a piece of good software is Sisyphus work - once you think you've nailed it, everything falls down into pieces. So is there a way to actually create something that could be awarded a &quot;good software badge&quot;? I don't know if you can ever guarantee it, but I think there are some ways to make it a little bit more likely. But before we will get to those, let's see what this badge actually means.</p>
<h2 id="sevenqualitiesofthegoodsoftware">Seven qualities of the good software</h2>
<p>Just like a teacher can assess whether a child is behaving well at school, we can assess whether we are dealing with a good software or not. Unlike the child though, misbehaving software isn't really a sign that we may be dealing with a genius or future revolutionist - we want the software to work exactly as we think it should, side effects excluded. So how it should look and behave like? Here are (some of) the points that I consider characteristics of a good software:</p>
<ol>
<li>It does what it's supposed to do and nothing else. The purpose of the code should be clear enough to grasp within minutes or even seconds.</li>
<li>Navigating through the code is easy, even without sophisticated tools. That includes project, folder and file level organization. Any domain-related aspects should precede any technical details.</li>
<li>Reasoning about its behaviour is easy enough to not require a debugger to understand what should happen in given case. All the inputs and the output of given part of code should be easy to figure out without deep system knowledge.</li>
<li>Naming across the different parts of the same domain is consistent. Decide how given thing should be called and stick to it. Prefixes/suffices can be used to differentiate multiple values of the same property in one scope.</li>
<li>All the cases that can generate an error (side effects) are properly managed. There should be no way for an error to leak outside of the designated path.</li>
<li>When something goes wrong it does all it can to provide the most meaningful information to figure out what actually happened, and possibly why. That includes well-designed logging and/or auditing of everything that happens within the application.</li>
<li>When something really bad happens and it cannot operate any longer, it gracefully shuts down and notifies all the interested parties. Supervisors of the running application should be able to easily figure out that it is no longer operating.</li>
</ol>
<p>There are also several other aspects, not directly related to code but to the testing, deployment and runtime, that are not mentioned here. They are already covered in some other checklists, so I decided to skip them here. Usually, they are less generic and depend more on the kind of the application, environment and so on.</p>
<h2 id="waystoimprovethequality">Ways to improve the quality</h2>
<p>Knowing what makes a good software should help us to come up with ways to achieve it. Depending on the platform, language or frameworks we decide to use it may require different approach or tools, but some of the things should be common regardless of those.</p>
<h3 id="1dontlie">1. Don't lie</h3>
<p>If you name your function or endpoint <code>updateName</code>, make sure it does exactly that, and nothing else. If you're using statically typed language (which you should do!), make sure that the function/method signature tells the truth. Take this method as an example:</p>
<pre><code>public Person UpdateName(Person person, string newName) {
    person.Name = newName;
    return person;
}
</code></pre>
<p>If you look at the signature, you could expect that it gets a <code>Person</code> and a <code>Name</code> and returns a new version of provided <code>Person</code> with updated <code>Name</code>. As you can clearly see it doesn't fulfil the promise. It actually mutates the input value, so it clearly has an unexpected side effect. Evil.</p>
<p>Let's look at an improved version:</p>
<pre><code>public void UpdateName(Person person, string newName) {
    person.Name = newName;
}
</code></pre>
<p>Things are a bit better now. It still has a side effect, but at least that's what you can expect from a signature. It's good to know the important things without a need to dig into the details.</p>
<p>So what would be the desired approach? Using immutable data should be the preferred approach:</p>
<pre><code>let updateName (person: Person) (newName: string) : Person =
    { person with Name = newName }
</code></pre>
<h3 id="2solvethedomainprobleminafirstplace">2. Solve the domain problem in a first place</h3>
<p>When I first open some project the most important thing I want to know is what it's supposed to do. How things are solved is much less important, at least on the technical level. I want to know what are the key domain objects the software is dealing with. On the level of APIs (e.g. in web API or shared library) I want to know what are the key operations it is exposing. On the level of data structures, I want to know what is the root object and what it consists of.</p>
<p>I don't care where are the services, proxies or interfaces. Group things by domains, not by technical details. Use pattern names with consideration, and if possible avoid them. I want to know the entry point and steps that are required to solve given problem, not which pattern did you learn about yesterday. When it comes to dependencies, keep the structure flat. I rather read longer method than dig through multiple classes to figure out what is going on. It's OK to hide (some) less relevant details, but be explicit with the important actions. You and your team will be thankful for that, especially when coming back to the code after some time.</p>
<h3 id="3beconsistentlyexplicit">3. Be consistently explicit</h3>
<p>Probably most of the functions require some dependencies to do the work they're supposed to do. Whenever it's possible, prefer explicit parameters over implicit ones (like dependencies injected by the container). It makes signatures more elaborate, and while it may seem to be extra overhead at the beginning, it isn't actually that hard. If your language supports partial application then it's probably not a deal at all. By having the explicit dependency on a function instead of class/interface, you can quickly figure out what it actually does, and unit testing will be way easier (if it needs to be unit tested).</p>
<p>Making function dependencies explicit enables composability on the higher level than it is possible with implicit ones. You're no longer tied to components that need to be designed to work together (usually via interfaces) - you can mix and match functions as it makes sense for you. Any function signature becomes its interface, and lamdas become adapters whenever required. Welcome to the world of programming LEGO. And the outcome? You can say more about your code at the first glance, without a need to jump between places. Reasoning about the code will be much easier.</p>
<h3 id="4writecodenotprose">4. Write code, not prose</h3>
<p>This is a tricky one. You should write code for people to understand it, and it sometimes feels like you should start using what you've learned in the literature classes. And while some of the hints from the literature may be helpful, others may be really bad ideas. Take the synonyms as an example. When writing prose you are supposed to use them to not repeat yourself, so that the outcome will be more artistic and less monotone. But when writing code, being boring and repetitive is actually a very good idea.</p>
<p>When you'll decide to call the customer number, well, <code>CustomerNumber</code>, don't call it <code>ClientNumber</code> or <code>CustomerId</code> in other places. Be consistently boring with the naming. That's especially important when you're within one domain, but even across domains, it's good to keep the names consistent - unless they are actually different values. That will save you a lot of memory resources when reasoning about the code and will help to reduce the number of bugs caused by confusion. Even when you're dealing with many values of the same property within one scope, make sure to be consistent, e.g. you can use <code>currentEmailAddress</code> and <code>newEmailAddress</code> as a parameter names of the function updating an email address.</p>
<h3 id="5treatthesymptomsintheearlystage">5. Treat the symptoms in the early stage</h3>
<p>It's usually most effective approach to fix an issue before it develops into some serious problem. You fix the leaking tap before it floods your house, right? At the same time, most programming languages by design let the small problems kill your application - unless you deal with the problems at some stage. If you try to connect to the database and there is some network glitch, you usually don't want to serve the user some 500 error page, right? That's why exceptions come with a set of tools to handle them. And while very often you can handle them in some general way (e.g. by a global exception handler), this should be your last resort.</p>
<p>I would highly recommend handling any possible exceptions at the earliest possible stage. That will force you to think about the value you return from a function with side effects. In some cases, you may just want to use some default value, in other you want to have some other value (maybe of a different type) or meaningful error description. Many functional languages have built-in solutions for this. Haskell forces you to use IO monad whenever you deal with side effects. Others, like F#, may be more tolerant and let you ignore the error if you want to, but also provide helpful tools, like Result or Choice/Either types. You may also create such types by yourself, or use some external library (like my <a href="https://github.com/bartsokol/Monacs">Monacs library for C#</a>). The point here is to have explicit notice that something may go wrong so that the consumer is (more or less) forced to deal with the possible problem. Of course, it requires discipline, and won't prevent all of the possible exceptions, but the overall quality should go straight up.</p>
<h3 id="6dontbeashamedoftheproblems">6. Don't be ashamed of the problems</h3>
<p>Sometimes things go wrong. Even if you will handle all the possible problems inside your code, there may be some external dependency that will fail. When such things happen, it should be very easy to find it out. The most obvious solution for this is logging, and your application should log extensively. You should also make sure that the information that makes it way into the logs is as helpful as it can be (maybe just don't expose sensitive data, please). Good description of why you decided to put something into the logs, what were the conditions that caused it and where it actually happened (e.g. stack trace) are some of the key elements.</p>
<p>Another one is the ability to track the whole process. For example, in a web app you may want to use <code>Request-id</code> header across the calls and in the logs, so you can see what was the sequence of events that caused the particular problem.</p>
<p>One thing which may be hard to assess is the log level to use. I have two hints here. First, keep it low. There's no reason to raise an alarm when some insignificant problem occurred (e.g. app wasn't able to send the newsletter to one of the customers). Second, judge the impact. If something blocks the user from performing a critical operation, it needs to go loud.</p>
<p>The last tip in this section is the approach to application design. Most applications use logging as a useful way to find out what's happening inside, but the problem with logs is that they are temporary and very often too laconic. This is where event-based storage really gives you an advantage. Having all the operations stored in your database you can track very precisely when some unexpected behaviour occurs. Of course, it comes at a cost, but when done properly (e.g. with help of tools designed for the job) it can save you a lot of time (and money) in the future. And it will reduce the need for logging and tracking (e.g. user action tracking), which can also reduce the complexity and cost of the system.</p>
<h3 id="7complain">7. Complain</h3>
<p>When you break your leg, how long do you wait until you go to the hospital? Probably not so long. Whenever something really wrong happens to your application you should also let &quot;the doctor&quot; know about it, sooner than later. That's why whenever some critical exception occurs the application should log it in the most detailed manner, as explained above. I would recommend leaving dedicated log level for such critical situations - the ones that may need to wake you up in the middle of the night.</p>
<p>As your application may get into the state when it cannot inform anyone that it's gone, you should have some monitoring as well. There are multiple ways to do it, depending on application type. The most common may include health check endpoints for web apps or error reports delivered by e-mail or IM. The more critical the app is, the more such tools you may need to incorporate. You may want to use the actor frameworks with supervisors to keep your app alive, or even choose the platform that supports it natively, like Erlang's OTP. Those are aspects that are not directly solved in the code, but they often require some modifications to the application code as well. Be sure to prepare for those.</p>
<h2 id="finalwords">Final words</h2>
<p>Think. Let it sink in. Don't hurry. Rush may get you somewhere faster, but it may be the wrong path. Instead of spending time on overengineering your code, spend it on bulletproofing it. Focus on making the software that not only your users but also your admins and fellow developers will love. And that's the software that does it job right. That's the software that doesn't get in their way. That's the software that helps everyone get their job done.</p>
<p>The code you write is not only for you. Even if you're a lone developer, in weeks or months there will be different you, richer in new experiences. And while every piece of software becomes legacy code sooner or later, don't let it be legacy which no one wants to deal with, yourself included. Deliver less but better quality software and everyone will be grateful*. Less is more, more is less. Less rush is more quality. More quality is less hassle. It's a win-win situation if you're brave enough to look under the surface of time. Stay on the quality side, and the good software will become a reality.</p>
<ul>
<li>If you work for organization that thinks otherwise, quit today!</li>
</ul>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[How much code is enough?]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>I’ve had a discussion recently on Twitter about the amount of code we produce versus readability. I am a backer of concise code, using every character very intentionally. This doesn’t mean that I would opt to create code where every name is either one char or one verb,</p>]]></description><link>https://bart-sokol.info/2018/01/05/how-much-code-is-enough/</link><guid isPermaLink="false">5a4f58970185f50ca30ab5dc</guid><category><![CDATA[programming]]></category><category><![CDATA[architecture]]></category><category><![CDATA[design]]></category><category><![CDATA[.net]]></category><category><![CDATA[fsharp]]></category><category><![CDATA[f#]]></category><category><![CDATA[abstraction]]></category><category><![CDATA[naming]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Fri, 05 Jan 2018 17:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>I’ve had a discussion recently on Twitter about the amount of code we produce versus readability. I am a backer of concise code, using every character very intentionally. This doesn’t mean that I would opt to create code where every name is either one char or one verb, absolutely not. I strive to achieve a good balance, where there is just enough code to make it work while being easy enough to read and grasp the concept encoded in it. It’s a damn hard task, and I almost always have doubts whether I’ve got it right. But there is a language that makes this task a little bit easier. Yes, I'm speaking about you, F#!</p>
<!--more-->
<p>This post is my contribution to <a href="https://sergeytihon.com/2017/10/22/f-advent-calendar-in-english-2017/">F# Advent Calendar 2017</a>.</p>
<h2 id="thefstory">The F# story</h2>
<p>A few years ago I spoke with my friend who was at that time doing some F# work. I wasn’t really charmed by the language at the time, as I was used to C-like syntax and OO concepts from languages like C# or PHP. But then he said a thing that stroke me: “I write (just) a few lines of code every day”. Still, those lines of code delivered a lot of value, and I’m pretty sure they were more readable than hundreds of lines I was producing each day (many automatically generated by tools like ReSharper).</p>
<p>At that moment I’ve decided to put some more interest into F# to find out why so little code can be as valuable (if not more) than the piles of code produced by many developers every day. Enlightenment came to me on Mark Seeman’s presentation at WROC# conference. I’ve got an example of code which was completely new to me, yet just after few minutes of explanation I was not only understanding what’s going on, but I was ready to extend it, to play around with it. That bought me completely.</p>
<p>So what is so special about F# that helps to reduce the amount of code you have to write to solve the issue? There are some language design decisions that make the code more terse (some of them inherited from ML family, some not), like the compact syntax, good type inference and other type system features (like built-in tuples or algebraic types). Many of them are common across different functional languages, and some of them also make their way into more object-oriented languages as well.</p>
<p>There are lots of things to talk about on this topic, but let's focus on a few key ones that let you keep the code concise yet readable. Following paragraphs present the most common concerns which affect (directly or indirectly) those aspects.</p>
<h2 id="allthelittlethings">All the little things</h2>
<p>First of all, I make sure I’ve reduced all the noise. For me, this includes things like non-critical comments, non-significant whitespace, not required braces and so on. The less noise you have, the more focus you can put on things that really matter. This is the place where F# actually shines - in most cases its syntax is very terse (yes, I know, lambda syntax...), and significant white space significantly reduces the need for braces, making code naturally structured. Powerful type inference reduces the need to specify types explicitly, leaving you the decision whether you need to add it (usually to increase readability).</p>
<h2 id="appropriatenaming">Appropriate naming</h2>
<p>Naming is hard - unless you don't care. Is <code>a</code> a good name? It may be, in some cases, but can be totally confusing in others. Fortunately, we have now a possibility to use much more verbose names. Of course, people leverage this possibility to the extreme. Let's compare some extremes, just for fun:</p>
<pre><code class="language-fsharp">let area a b = a * b
let calculateTheAreaOfRectangle lengthOfTheRectangle widthOfTheRectangle = lengthOfTheRectangle * widthOfTheRectangle
</code></pre>
<p>In terms of readability, the former version is much easier to digest and grasp, but it may be hard to reason about it. The latter takes ages just to read, but once you're done, you should know everything about this function. Unless you've run out of memory ;) You could get some more reasonable version as well:</p>
<pre><code class="language-fsharp">let areaOfRectangle length width = length * width
</code></pre>
<p>Looks better? Hope it does. But let's not stop here. One of the most important aspects to consider when naming anything is the scope of the name. Using the first, a somehow extreme example in the right scope may totally change the way you receive it:</p>
<pre><code class="language-fsharp">module Rectangle =
    let area a b = a * b
    let perimeter a b = 2 * (a +  b)
</code></pre>
<p>In this case, the short form seems to be very appropriate, and I don't see a problem with using it. Of course, the domain also matters - in case of math names like <code>a</code> and <code>b</code> are commonly accepted and used. But when we change it to something more typical to business apps, things may change:</p>
<pre><code class="language-fsharp">module Person =
    let fullName a b = sprintf &quot;%s %s&quot; a b
</code></pre>
<p>Feels like something is missing here? Probably yes. Knowing the context you shouldn't need to guess or look into the implementation to know what are the parameters. Here more elaborate names will do a better job:</p>
<pre><code class="language-fsharp">module Person =
    let fullName firstName lastName = sprintf &quot;%s %s&quot; firstName lastName
</code></pre>
<p>This is the way I approach the naming and I think it works quite well. Keeping names brief will reduce the amount of code you need to read and also visual noise. The one thing to remember here is to make sure the name gives the reader enough information to understand the code. It's not about length, it's about saying enough without introducing noise. And as you can see, the default functional approach makes F# a good companion, letting you keep things concise without losing the readability.</p>
<h2 id="therightamountandkindofabstraction">The right amount (and kind) of abstraction</h2>
<p>The solution for every problem is another layer of abstraction. That's the thinking I've seen many times, and the one I highly disagree with. Abstractions in the code are very useful, as they allow us to generalise, separate and group things or concerns. They can also increase testability of the code. But they are just a tool. The goal of coding should never be using a tool unless your goal is to learn to use it. As with any tool, it gets often abused, causing loads of unnecessary code being created to meet the needs of the abstraction. This happens in many cases, let it be over-generalised code, lasagna code, multi-level inheritance and so on.</p>
<p>I've recently stumbled upon a project which sole goal was to store or retrieve some information, almost a classic CRUD. And what I've encountered inside? Four projects to solve this super-advanced issue (plus one for tests). Things got even more interesting inside, where I've found 3 layers of code, split across those 4 projects (if your math instinct is also nagging you, the fourth one was for data models). To make things worse, most of the methods were one-liners, passing arguments as a parameter to another layer (Controller to Service to Repository). And where was any domain-related logic in this project? In the Repository. That's just nuts!</p>
<p>So what were tests doing there? Basically checking if you pass right parameters from Service to Repository layer. That's the thing you could just verify with a glance of the eye and forget about it. My recommendation? Compact everything into one project, remove one of the layers (basically join Service and Repository) and you'll remove about 50% of the code in the project. Oh, and probably remove unit tests and write some integration tests instead. They may have much more value than unit tests in such case, as they will be testing some actual logic.</p>
<p>One more example would be the use of interfaces. If you are to follow SOLID principles, you'll most likely end up with many single method interfaces. They will probably be used to extract implementation details to enable testability (e.g. to not to read from a file in case the code is under unit test). But this actually introduces a lot of code - and can be largely reduced by leveraging more functional approach of passing functions as parameters. Let's compare those two approaches:</p>
<pre><code class="language-fsharp">// Constructor injection approach
type IReadFromFile =
    abstract member Read: string -&gt; string seq

type ReadFromFile() =
    interface IReadFromFile with
        member this.Read path =
            System.File.ReadLines(path)

type Files(readFromFile: IReadFromFile) =
    member this.GetFirstLine path =
        match readFromFile path |&gt; Seq.tryHead with
        | Some text -&gt; sprintf &quot;Line #1: %s&quot; text
        | None -&gt; &quot;&quot;

// Function injection approach
module Files =
    let readLinesFromFile path =
        System.File.ReadLines(path)

    let getFirstLine readFromFile path =
        match readFromFile path |&gt; Seq.tryHead with
        | Some text -&gt; sprintf &quot;Line #1: %s&quot; text
        | None -&gt; &quot;&quot;
</code></pre>
<p>I skipped the coupling logic, but it's a similar amount of code for both cases. There's obviously less code with the function injection approach, not only in terms of LoC but also in the amount of the artefacts one has to deal with. What's more, when you want to test this code, creating a mock function also yields less code than the mock implementation of the interface:</p>
<pre><code class="language-fsharp">// mock implementation of the interface
let ``printFirstLine should return first line from file`` () =
    let mockReadFromFile =
        { new IReadFromFile
            with member this.Read path = [&quot;foo&quot;, &quot;bar&quot;] }
    let files = Files(mockReadFromFile)
    files.GetFirstLine &quot;&quot; |&gt; should equal &quot;foo&quot;

// mock function implementation
let ``printFirstLine should return first line from file`` () =
    let mockReadFromFile path = [&quot;foo&quot;, &quot;bar&quot;]
    Files.getFirstLine mockReadFromFile &quot;&quot; |&gt; should equal &quot;foo&quot;
</code></pre>
<p>Although interfaces may be very useful in some of the cases, I would strongly recommend to not use them as a silver bullet to solve any potential issue. They introduce a lot of noise to the code when overused, without any clear benefits.</p>
<p>Those are just some of the examples where introducing abstraction can lead towards bloated code. Properly used abstraction increases code readability and helps to achieve compact but powerful code. I always think twice (or more) when I'm about to introduce an abstraction, because the downsides of using it may diminish the potential benefits. And even if I decide to introduce one, I try to choose the one that is less of a burden to the codebase.</p>
<p>And speaking about F# - some of the features that help with getting the right abstraction are partial application and union types. The former one allows you to have more granular dependency injection, helping to avoid leaky abstractions and unexpected dependencies. The latter one, combined with powerful pattern matching and active patterns, lead to clearer separation of different cases within the same scope, not forcing you to find the common denominator (when there even may not be any) just to be able to use things in one place.</p>
<h2 id="rightgrouping">Right grouping</h2>
<p>Another aspect that affects the way you write code, and in the result - how much code you need to write, is grouping the code. Most of the people I speak with see the benefits of domain-based approach when it comes to designing the code, yet still, lots of projects suffer from poorly grouped code, based on the technical aspects rather than domain concerns the code is tackling. This usually leads to leaky abstractions and unnecessary glue code, not mentioning the problems with readability.</p>
<p>There is a catch here. When you group things by domains and separate them properly, you may actually end up with more code. No worries though - it's OK to have more code in places where it actually adds value. So what are the things to look at when comes to grouping? First, recognize what is the domain of your project. If there are multiple domains/subdomains, then try to list them all. Next, try to identify the operations that may happen within those domains. It should be fairly easy if you're working for example on some web-based API, where each endpoint may map to some domain operation. Another step can be figuring out what are the shared components/services. Knowing that you can group things into two main categories - operation specific ones and shared ones. This leads to clear separation between technical details (which usually land in the shared category) and domain logic (found in operation specific category) and enhances discoverability - finding things within a project is much easier.</p>
<p>The grouping concern also applies to making a decision on where to put different pieces of code. For example, if you need to extract a bit of code from your function, you may want to create another function to capture the logic (e.g. complex filters or conditions). In the object-oriented approach, you would probably use a private method to do it, but there is a problem. If you'll end up with more than one such function, especially not reused in multiple methods, you end up with the problem described below - ordering. Is it good to mix private and public methods together, or should them land on the top/bottom, and what if you have a mix of methods with one reference and those with more? This is where local functions come into play - they help to capture the code that doesn't need to be exposed outside of given function, inside that function. Using local functions may not reduce the amount of code needed (maybe a bit, if you'll approach the naming principles mentioned above), but it will reduce the time needed to switch between the locations to grasp the logic inside the function, and also make things like refactoring much easier (if it's local function then you don't have to care about other users of it, as there are none).</p>
<p>Again F# gives you a lot of tools to work with when it comes to grouping. First of all, you're not forced to keep things in separate files (because of compiler or convention) - you may define data structures, accompanying functions and the API in the same file. This helps to gather all the related logic in one place, increasing readability and reducing the noise within the project.</p>
<h2 id="correctordering">Correct ordering</h2>
<p>There are many schools of ordering elements in the file, especially when it comes to languages with multi-pass compilers. Especially in object-oriented languages with encapsulation, this becomes sometimes almost a flame war - should public elements go first, or maybe private ones, what about protected ones, not to mention grouping and ordering fields, constructors, methods, properties... A lot of things to fight for. Fortunately, it's a little bit solved in F# by the single-pass compiler - everything you want to use needs to be declared already. That naturally puts things like public APIs on the bottom and leads you to read files / modules / namespaces just like recipes: use those tools, take those values and functions and take these steps to get the solution. Some find it quite limiting, others treat it as a relief from constant battles.</p>
<p>But what does it have to do with the amount of code? It turns out that it may have an impact on it as well. Due to the fact that you need to have at least a glance at what is already declared, you're more likely to reuse some existing components when you're about to add something new. It may lead to writing less unnecessary code, at least in some cases. The same applies to files - the most general things usually bubble to the top, while most specific things lean closer to the bottom.</p>
<h2 id="sohowmuchcodeisenough">So how much code is enough?</h2>
<p>This is, of course, a very subjective topic. First and most important thing is that code needs to solve the problem it's meant to solve. Next, likely same important is the question of readability. As I've mentioned before, it very much depends on the context, as the same code may be perfectly readable in one case, and completely illegible in other. Some, especially inexperienced developers, tend to use a lot of white space and braces to separate things, while others, myself included, may prefer to keep code clean from those extras.</p>
<p>Apart from personal preferences, the choice of tools has also a big impact on this. As I've shown above, F# is a pretty good choice in this regards (and not only!), as are many other functional languages. With new features coming into more object-oriented languages like C# or Java, it becomes easier to keep the code concise as well - make sure you leverage their potential.</p>
<p>You may not realise it, but we spend a lot of our development time reading the code. Having briefer code we can shift it to actually thinking more about the solution we're trying to produce, and eventually to writing some code. I hope you will review your practices of writing code to make sure that you communicate things clearly and concisely, helping to make a better use of our limited time. Howdy!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Not so obvious benefits of Microservices]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Recently I wrote a bit about how to approach microservice architecture, but I haven't really mentioned why should you bother. It turns out that microservices can have some serious pros compared to monolithic architecture - but they won't be applicable in every case. There can also be some serious cons,</p>]]></description><link>https://bart-sokol.info/2017/09/03/not-so-obvious-benefits-of-microservices/</link><guid isPermaLink="false">5a4f65230185f50ca30ab65a</guid><category><![CDATA[programming]]></category><category><![CDATA[architecture]]></category><category><![CDATA[design]]></category><category><![CDATA[microservices]]></category><category><![CDATA[services]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sun, 03 Sep 2017 21:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Recently I wrote a bit about how to approach microservice architecture, but I haven't really mentioned why should you bother. It turns out that microservices can have some serious pros compared to monolithic architecture - but they won't be applicable in every case. There can also be some serious cons, but this will be a topic for another post, hopefully coming soon. So, let's start with the goodies.</p>
<!--more-->
<h2 id="theobviousones">The obvious ones</h2>
<h3 id="independentdeployments">Independent deployments</h3>
<p>One of the core benefits of microservice architecture is the ability to independently deploy each service. That can not only speed up the development process but also help with fixing bugs, testing new stuff and so on. Of course, you will need to have some good deployment pipeline (with a possibility to revert deployments as well), but it's a must for microservices anyway.</p>
<h3 id="scaling">Scaling</h3>
<p>The fact that one service runs independently from others allows you to assign resources independently. This is especially convenient with cloud deployments, where you can dynamicaly set resources available for given instance (scale up) and spawn more instances (scale out). Of course, the latter requires some load balancing at least, but this can be done relatively easy with what cloud providers offer. Those abilities can help you limit the costs while having a possibility to improve performance when more customers start to use your service. And the fact that you can do it independently for each of the services allows for more granular control.</p>
<h2 id="thelessobviousones">The less obvious ones</h2>
<h3 id="domainseparation">Domain separation</h3>
<p>When you're inside a monolith, it's quite easy to blend things together and forget about separation of domains. That leads to tighter coupling between components, and often to unexpected bugs related to that. When you're in a microservice, you're basically left with what you've got there. And as you shouldn't have much, there isn't much to mix with. Microservices are working really great with domain driven design, helping you to keep the separation between domains and communicate with other domains using event-based approach. And given the rule of thumb that each service should be responsible for its own data, it's much harder to break some other things by changing some commonly used object (whether it's a data structure, a database or an API). Also, the API of the service tends to be much smaller than the API of the modules within a monolith, which keeps people less tempted to use the things which they shouldn't. Think of microservice as a separate domain, a bounded context, or whatever label you'll put on it - just make sure it does what it should, and not more.</p>
<h3 id="abilitytotrynewthings">Ability to try new things</h3>
<p>How many times did you want to try this new approach, a new framework, or even platform or language? And how many times did you end up doing the same old thing again, because, you know, it's the way it's done and cannot be changed? Well, in the microservice world things are much easier. Usually trying some new approach or framework is a piece of cake - just pick one that you want when you create the service and you're good to go. Things get usually more complicated with platforms and languages. The former requires additional steps to ensure it can actually be deployed somewhere, monitored, maintained and so on. The latter requires some agreement across the team, but if there are people willing to go this way, you don't have blockers like cross-language compatibility which can be a pain in some cases. In general, the microservice architecture gives you more freedom of choice, and that is usually a great news - people want to learn and develop new skills and it's a great way to enable this.</p>
<h3 id="continuousimprovement">Continuous improvement</h3>
<p>It's nice to do some bigger refactoring sometimes, but it can be very painful as well, especially when there are lots of things going on inside your monolith. When you're in microservice things get a little simpler. As you have a smaller codebase and fewer people are working on it, it's much easier to do any kind of improvements. Upgrading a dependency, doing some cleanup or changing the approach a little bit is less painful in microservice compared to the monolith. The smaller impact of those changes also means that it's safer to do it, so you're more willing to do it. That leads to more maintainable, better quality code, which is a great thing, especially when your codebase is growing and you cannot afford for bigger changes that will impact other parts of your system.</p>
<h3 id="teamseparation">Team separation</h3>
<p>When your team grows it starts to be much harder to synchronize changes that different people are making. Code reviews, merging pull requests and deployments are becoming more of a pain. Tracking the changes that got into each release becomes harder, testing is not easy as well. If you want to have continuous deployment, things are even worse - when you constantly want to deploy monolith, the environment will be unstable most of the time. With microservices, you can make those changes with more gradual manner, and you can have smaller teams focused on each part of the system. That enables you to scale the development team, let them be responsible for given part and also build up devops culture. Anyway, every team member won't be able to grasp the whole of your system (at least on the code level) and letting people focus on smaller chunks can be more effective and less stressful.</p>
<h3 id="morecompletedprojects">More completed projects</h3>
<p>And when we're speaking about the people, there is one benefit that will also help build up the team morale. People like accomplishing something - finishing tasks and projects can be such an accomplishment. With microservices you can have smaller projects which quite often can get into &quot;completed&quot; state, making people feel that they've finished something. Of course, there may be some maintenance work, but, when managed well, microservices can bring a more positive attitude to your team. And a happy team is one of the best things that can happen in a software development world.</p>
<h2 id="summary">Summary</h2>
<p>As you can see, there are quite a few benefits of using the microservice architecture. Some of them are easy to overlook, so it's good to sometimes look at the approach from a broader perspective. But of course microservices are not a bed of roses and there are several challenges to take as well. In the next post I'll try to list the most important problems, but for, now let's not forget the serious benefits I've mentioned above. Hope they will make you more willing to try it out by yourself!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Approaching Microservices in a safer way]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Microservices. You've probably heard about them million times. It's inevitable to avoid this if you're at least a bit interested in software architecture. Actually, you've heard about them so many times that you have to try them for your own! But should you? Is it the right approach for your</p>]]></description><link>https://bart-sokol.info/2017/07/23/approaching-microservices-in-a-safer-way/</link><guid isPermaLink="false">5a4f64d60185f50ca30ab651</guid><category><![CDATA[programming]]></category><category><![CDATA[architecture]]></category><category><![CDATA[design]]></category><category><![CDATA[microservices]]></category><category><![CDATA[services]]></category><category><![CDATA[english]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sun, 23 Jul 2017 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Microservices. You've probably heard about them million times. It's inevitable to avoid this if you're at least a bit interested in software architecture. Actually, you've heard about them so many times that you have to try them for your own! But should you? Is it the right approach for your application? Will it solve any of your issues? Or will it be the source of a terrible headache? Let's try to get some answers to those questions!</p>
<!--more-->
<h2 id="mythicalmicroservice">Mythical Microservice</h2>
<p>If you've heard or read about microservices in multiple places, you've probably already noticed one worrying thing - lack of precise definition of microservice. Of course, there are people telling you that microservice can only have up to 100 lines, or needs to be small enough to be rewritten within a scope of one week, sprint, or whatever. None of those &quot;definitions&quot; tell you anything; in some languages and frameworks 100 lines will be enough to get some functionality up and running; in others, it will take more than that to do just initial bootstrap. The same can be said about time scope - it doesn't say anything about team size, it's capabilities, knowledge of the topic etc.</p>
<p>It's basically up to you to decide what a microservice is in your environment. I've seen many examples, from ones as simple as single responsibility mail-sending service to large services capturing quite complex domain logic, exposing multiple endpoints and talking to plenty of other services. In my opinion, it really isn't so much about the size per se, rather about the scope. It really helps if you think about your system through the glasses of domain-driven design and its bounded contexts. Each of those contexts makes a perfect candidate for such a microservice. And even if you're not really focusing on incorporating full DDD approach, it may help a lot when looking through its lenses.</p>
<h2 id="startsimple">Start simple</h2>
<p>So, let's do the microservice thing! Yeah, it's easier said than done. If you're starting from scratch and don't have a strictly defined scope, you probably should start simple. Go with the monolithic approach, extracting only things which are totally separate from your core problem. Perfect candidates for first microservices would be things like interop modules, handling some legacy apps and data, or communicating with external systems. It should help you to embrace what it feels like to have more distributed architecture and get prepared for more.</p>
<h2 id="modularmonolith">Modular monolith</h2>
<p>In most cases, you should start with the monolithic approach. One thing you want to do in your monolith is to start thinking about separation of domains and grouping things by them, not by their technical properties. To give you an example, let's say you need to get some information about the products. Information may come from your database or from external service, doesn't really matter. You'll probably create some entities or DTOs to model what you're getting from an external source. You may have some repository or some network level service that would fetch the information. You also may want to use your application-specific view of that data by creating some domain or value object that will capture that data in a useful structure. Then you may want to create the mapper between your internal data structures and the external ones. Finally, you may want to create some service which will expose the functionality of fetching and mapping product data to other parts of your application. The key thing here is to keep all those things together - within one folder, module, namespace - whatever your language and frameworks support. Avoid grouping things by entities, DTOs, mappers, services and so on. By this approach, you'll get less coupling between unrelated components, and less coupling means fewer problems with moving things outside of your monolith.</p>
<p>For bigger chunks of functionality, it's often quite wise to create separate folders or projects, which will encapsulate all the code related to its domain. Make sure to create some kind of API for it - let it be an interface, for example - and use only it when communicating with that module. Be also very cautious when using data structures defined within that module - you may want to move them out some day, so don't rely too much on what's within that module.</p>
<h2 id="feelthepain">Feel the pain</h2>
<p>While you're still not having microservice architecture, you should already feel the first pain. Keeping things separate means having some duplicated code, an additional mapping between data from different modules, and so on. It's inevitable in microservice world, and it's actually very intentional. The key here is to learn that code reuse isn't the golden principle in software development. Functionality reuse is the other story - and yes, microservice architecture puts focus on reusing bits of functionality, not bits of code. It doesn't mean you cannot reuse code at all; you may still have some shared code, but you'll need to make sure it's actually reusable. You may want to create some shared libraries to achieve it, and they are not much less of a problem than microservices themselves. Always think twice before you reuse anything - sometimes some copy-paste can save you a lot of time in the future.</p>
<h2 id="prepareforthefuture">Prepare for the future</h2>
<p>Another aspect which limiting code reuse affects is refactoring. You may think that it's easier to do refactoring when having more shared code, as you may do it in one round. But this isn't so easy with microservices. They are usually separate projects, and even if you have shared libraries, you may need to synchronize the changes in all of them which are using that library. And one day you may be fed up with the technology you use right now, or it may just become obsolete, and you may want to change it to something else. With limited code reuse and modular (if not microservice) architecture, it's much easier to use new frameworks, languages, or even platforms. You're already prepared for that, technically and mentally. And even if you want to stick with what you have right now, refactoring things within a module is actually much easier when it doesn't share too much code with others.</p>
<h2 id="knowwhentoextract">Know when to extract</h2>
<p>So it's the time. You feel it in your bones. But you need to have some logical reasons. How to tell that it's time to extract something into a microservice? Try to go through the checklist below to find some of the potential reasons:</p>
<ul>
<li>Your codebase has grown so much that maintaining monolith becomes a pain.</li>
<li>Part of your application is used more (or less) often than others and you would like to scale it separately from other parts of your app.</li>
<li>Some parts of the code need to be deployed more (or less) often than the rest, and the deployment of the whole app is somehow painful.</li>
<li>You want to reuse the functionality that some piece of code provides in other applications, but you don't want to reuse the code (e.g. as a shared library).</li>
<li>Your team has grown and it's much harder now to work on one codebase without interrupting each other and causing conflicts.</li>
</ul>
<p>As you can see, being prepared for potential split makes solving scaling problems much easier. And by scaling I don't only mean performance concerns - it may also mean scaling in terms of size, development process, team size or maintanance.</p>
<h2 id="knowhowtoextract">Know how to extract</h2>
<p>If you have already thought about the modularity of your application, it's much easier now to split things into chunks. But there are many concerns left still, just to name some of them:</p>
<ul>
<li>How it should communicate with, or how it should be reached from other applications?</li>
<li>How to consume the service from other applications?</li>
<li>Where, when and how should it be deployed?</li>
<li>Who should be responsible for it?</li>
<li>How to handle bits of shared code that candidate for extraction is making use of?</li>
<li>Which technologies to choose for it?</li>
</ul>
<p>There are lots of things to think about when transforming into microservice, so make sure you have thought about them before beginning the process. In a longer term, the microservice architecture may be extremely beneficial for you, but it may also become the source of serious problems, especially when you're not well prepared. It's up to you to decide if it's right or not - and sometimes the only way to find it out is to try it on your own. Just make sure you know what are you getting into.</p>
<h2 id="somemoreconcerns">Some more concerns</h2>
<p>Other things worth considering when moving towards microservices may include:</p>
<ul>
<li>Deployment - how to configure the tooling?</li>
<li>Monitoring - how to make sure that the service is working properly?</li>
<li>Updates - how to handle service downtimes without breaking the user experience?</li>
<li>Backwards compatibility - how to make changes without breaking other parts of the system?</li>
<li>Size - how much should be extracted?</li>
<li>Growth - how much can be added to the service without causing additional issues?</li>
</ul>
<p>And the list goes on, and on...</p>
<h2 id="summary">Summary</h2>
<p>Microservices may be the right solution for your system. They can solve some of the issues that are mostly unsolvable in the monolithic architecture. But they also bring their own bag of troubles that you have to deal with instead. I personally really appreciate this approach, but I can also see a lot of reasons to not do it or to do it in a limited scale. Getting my hands dirty with moving things out of monolith into services, creating new services, or even getting rid of some of them added a lot to my toolbox, and I'm really happy to share my experiences and thoughts with you. Hope you can find some value in them as well.</p>
<p>In future posts I would like to address some of the concerns (and some of the benefits) in a bit more detailed way, so stay tuned! If you have any questions or comments, feel free to post them here or on Twitter - it's alway great to hear what you think!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[An alternative take on application architecture]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Do you remember when you have started writing your first programs? It's very likely that the code you've written was very procedural and your carefully crafted instructions were then somehow executed by this magical machine called the computer. Wasn't it fun? It was a lot of fun for me, and</p>]]></description><link>https://bart-sokol.info/2017/02/05/an-alternative-take-on-application-architecture/</link><guid isPermaLink="false">5a4f64620185f50ca30ab645</guid><category><![CDATA[programming]]></category><category><![CDATA[architecture]]></category><category><![CDATA[design]]></category><category><![CDATA[csharp]]></category><category><![CDATA[c#]]></category><category><![CDATA[fsharp]]></category><category><![CDATA[f#]]></category><category><![CDATA[error handling]]></category><category><![CDATA[null]]></category><category><![CDATA[exceptions]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sun, 05 Feb 2017 22:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Do you remember when you have started writing your first programs? It's very likely that the code you've written was very procedural and your carefully crafted instructions were then somehow executed by this magical machine called the computer. Wasn't it fun? It was a lot of fun for me, and if you're reading this then I can assume that it was the same for you. Yet many years later we look at our code and… yeah, we have to look deeper. And deeper. And even deeper. Go to definition. Oh, not that one, the other one. Oh, a little bit deeper. Yes! So here is the bug! Sounds familiar?</p>
<!--more-->
<p>The architecture of modern object-oriented applications is quickly becoming much of a pain. Dependency count is growing dramatically, followed by the complexity of those dependencies. Just take a look at the dependency graph of your application and answer honestly - how many surprises can you find there? I'm pretty sure that there will be a lot, especially if you're not the only author of that code.</p>
<p>In the team I'm working with right now this issue became a real pain. Making even simple changes in code required digging through tens of classes, and making a decision where to put new things was getting harder and harder. Fixing bugs was like fighting with Hydra - each fix introduced another set of bugs. And the problem was not only in the way the code was written but mainly in the overall architecture of the solution. The architecture which I've seen (and created!) multiple times, as it's almost exactly what *&quot;good programming books&quot; * recommend.</p>
<h2 id="thetypicalapproach">The typical approach</h2>
<p>So how typical application architecture looks like? My experience shows that usually we need to deal with multi-layer structure, where (in theory) each layer is responsible for different part of the job to be done. In MVC (or MVVM) applications it very often looks like this:</p>
<ul>
<li>Controller captures request (or ViewModel captures user input) and based on it executes service method responsible for given task, transforming the input data into parameters acceptable by the service.</li>
<li>Service encapsulates business logic, using other services, providers, repositories, (…name a pattern here…) to get necessary data or to delegate some of the operations. After its task is done, it usually persists the effect using the repository, and/or returns the result back to the controller.</li>
<li>Controller (or ViewModel) transforms the result into output format and returns it to the caller (user).</li>
</ul>
<p>Of course, this is a very simplified example, as most applications introduce more complicated logic into the process, including:</p>
<ul>
<li>Input data validation,</li>
<li>User authorization,</li>
<li>Caching and other optimisations,</li>
<li>Logging,</li>
<li>External dependencies (especially in distributed architecture).</li>
</ul>
<p>Problems usually appear quite early when you introduce any new thing into the process. The following questions may appear:</p>
<ul>
<li>Should it be a dependency or another layer?</li>
<li>If it's a dependency, on which level should I put it?</li>
<li>Can I trust the results of the calls to dependencies?</li>
<li>Does the dependency throw exceptions if something goes wrong?</li>
</ul>
<p>This is just tip of an iceberg and it only gets harder and harder as the application starts to grow. Of course, there are patterns and practices to be used which can mitigate those problems, but as the application grows it becomes more and more a mix of approaches and you can never be sure what to expect when you add something new.</p>
<h2 id="flowbasedapproach">Flow-based approach</h2>
<p>My team was facing those issues so often that we decided to sit down and try to take some different approach. We've taken pieces and blocks from different approaches out there, trying to create architecture that would be:</p>
<ul>
<li>Easier to understand and follow;</li>
<li>Easier to extend with new processes (or flows, as we call them);</li>
<li>Focusing on composability;</li>
<li>Designed for failure, yet keeping error handling simple.</li>
</ul>
<p>We took some lessons from domain driven design, encapsulating the internal state and exposing it by a reaction to external events (so keeping the service as the bounded context). Additionally, the limited trust approach when it comes to any external sources (and data coming from them) helped us to keep the service stable within the constantly changing environment. And we used a handful of techniques from the functional programming to make everything more concise and composable.</p>
<h2 id="howitlookslike">How it looks like</h2>
<p>The beginning is still the same - we get some external request that triggers the flow. Each external endpoint corresponds to one flow, helping to keep track of what's implemented where. Once you reach the flow, the magic happens.</p>
<p>The first thing which strikes you when you look at the code is how explicit yet simple it is. You don't have to dig into layers to see the steps needed to successfully execute the flow. In most of the flows one can find steps like:</p>
<ul>
<li>Validate the input;</li>
<li>Transform it to internal object capturing the intent;</li>
<li>Gather dependencies needed to execute the intent (we're calling it context);</li>
<li>Check the validity of the intent given the context;</li>
<li>Execute the intent given the context;</li>
<li>Run any of the repeatable steps (in our case it's things like price update or summary recalculation);</li>
<li>Persist the result into database.</li>
</ul>
<p>One thing that should strike you is the absolute lack of any direct error handling or even if statements throughout the flow. All of the calls are kept within the <code>Result</code> type and glued together using <code>bind</code> and <code>map</code> operations (oh, it sounds like a monad, scary!). That helped us to keep most of the dependencies afloat, making dependency graph shallow and easy to track (for injected dependencies the max depth is 3, for static dependencies it may go to 4 or 5 in some edge cases).</p>
<h2 id="composingflows">Composing flows</h2>
<p>Of course, the code very often gets more complicated than that. For example, when we create the context for execution we need to get the data from multiple sources, like database or external services. The nice thing about using composable types is that you can chain multiple calls using <code>bind</code> and make the code very brief and readable. For example, when you try to get something from a database and it will fail, getting additional information from other services usually makes no sense. In traditional OO approach, you could solve it by using constructs like</p>
<pre><code class="language-csharp">if (dbResult == null) return null;
</code></pre>
<p>after each call. But it adds lots of clutter to the code and also leaves open questions like *&quot;what should I return now?&quot; * or <em>&quot;how to name the next call result?&quot;</em>.</p>
<p>By leveraging things like lambdas, anonymous types and extension methods we achieved a state in which most of the functions are basically expressions (and can be written without curly braces in C# 6!). Additionally, most of them are static, making them independent of the global or local state, only reacting to input with appropriate output. Yes, that's a pure function, and it has several benefits:</p>
<ul>
<li>Not having any external dependencies, just input parameters, makes them easily testable.</li>
<li>Not having any side effects makes them easily testable.</li>
<li>Not dealing with the class state allows making them public without risks, which makes them easily testable.</li>
<li>As they are static and usually don't depend on context-specific types, reusing them (e.g. by extracting to common class) is pretty simple.</li>
</ul>
<p>You see some pattern here?</p>
<h2 id="handlingerrors">Handling errors</h2>
<p>We represent the result of any potentially failing call as the <code>Result</code> type. It's a very simple union type, which can be either a <code>Success</code> or a <code>Failure</code>. In F# you could write it as: <code>type Result&lt;'a&gt; = Success of 'a | Failure of Error</code>, where <code>Error</code> is a structure describing what went wrong.</p>
<p>Introducing <code>Result</code> type and making it almost a must for any impure function had several consequences. First of all, you can easily see from the function's signature that it may have side effects or inconsistent behaviour, thus it makes you more aware of any potential issues. Then you get into rules of writing functions:</p>
<ul>
<li>If function can fail in any way, it must return <code>Result</code> type;</li>
<li>If function may encounter any exceptions, they have to be handled internally and wrapped into Result type;</li>
<li>Null is not a valid return value in most of the cases, rather use <code>Option</code> instead (aka <code>Maybe</code>);</li>
<li>Mark any external call results unsafe (even just by calling them DTOs) and don't use them directly (map them to internal representation with options instead of nullables).</li>
</ul>
<p>Unfortunately, those rules cannot be enforced by linting or any other automated tool I'm aware of, so we need to keep it in mind when doing code reviews. This may be a bit of the drawback, but if you're doing in-depth reviews (and I think you should do!) then you need to dig into the logic anyway. It allows you to understand what and why is happening in the code and thus it feels natural to verify such things during the review.</p>
<p>Having such rules makes it easier to write the code, as you know if something may fail or have an unexpected result. As the result, you need to write less code (thanks to a set of helpers around <code>Result</code> and <code>Option</code> types) but at the same time handle errors gracefully.</p>
<h2 id="decisionsthatwevemade">Decisions that we've made</h2>
<p>Some of the decisions were almost no-brainers, but still, they are not the defaults for many apps:</p>
<ul>
<li>Grouping classes in the domain (flow) specific namespaces.</li>
<li>Only creating reusable blocks when there are many repetitions of the same code and we're sure it should be the same for all of the cases.</li>
</ul>
<p>Those simple things already helped to make the code more discoverable and easy to understand, but it was only a start. There were some more controversial decisions that we've taken which helped us to achieve the goal:</p>
<ul>
<li>Keeping interfaces within the same file as the implementing class  - fewer files, less noise.</li>
<li>Using static dependencies all around (of course for pure functions only) - fewer dependencies, less noise.</li>
<li>Using tuples to pass multiple results within the flows - no need to create types for more elaborate results.</li>
<li>Using anonymous objects to pass structured data between subsequent steps of the flow - no need to create and name short living types.</li>
<li>Leverage the potential of <code>using static</code>  - make the code more concise and readable.</li>
<li>Use value types (structs) quite a lot, especially for the <code>Result</code>, <code>Option</code> and <code>Error</code> types - fewer nulls, fewer checks in code.</li>
</ul>
<p>Although some of them were not easy to accept by others, we opted to give them a try. The code we're dealing with now is probably one of the best I've been working with (in an object-oriented language). It's easy to reason about, extend and test. Sure it would be better to use functional-first language and have much fewer problems to deal with, but being stuck with OO language boosted the creativity a bit as well. Hopefully, it will also be a big leap towards more acceptance and understanding of the functional programming in our team.</p>
<h2 id="drawbacks">Drawbacks</h2>
<p>I mentioned few times improved testability as a benefit of this architectural approach, but there are some cases where it comes at some cost. For example, when you have static dependencies (e.g. function that calculates item summary based on a list of items) there is no way to mock them. Thus testing any function that uses static dependencies requires from you more careful approach about input data, because if the data will be in the improper state the call will fail. And because the architecture separates error handling from actual business logic as much as possible, there are functions which need to be executed in a safe context and don't do any validation within. We made it less of the problems by simple test helpers generating valid test data and then just modifying properties important in given test case.</p>
<p>Another drawback may be unfamiliarity of the code for any people outside of the team. Although architecture doesn't use any difficult concepts, it uses a bunch of terms from functional programming which may be a bit overwhelming for some. Still, if they are willing to learn, it should bring a lot of useful tools to their toolbox. It just requires a bit of time to get used to it, and maybe a bit of openness for the new concepts.</p>
<h2 id="summary">Summary</h2>
<p>There is no perfect architecture, but it doesn't mean we should stick to what we've got right now and not try to experiment. By going back to basics and asking the right questions we can iteratively make our solutions better. What are the biggest issues with current approach? How can we mitigate them? Is there a way to avoid some of the mistakes we've made before?</p>
<p>By being open for different approaches and combining it with your experiences you can improve the application architecture step by step. It may not be an easy thing to deal with for everyone and we had to face that issue in our team as well. But so far the overall result is quite promising. We're delivering feature by feature, with good quality code and good test coverage, while keeping on track with a very challenging deadline. The final test - enabling it on production servers - is still to come, but I'm optimistic about the results. The count of bugs discovered during the tests is quite low so far, and working with the code is much more of a pleasure than it is with the old solution. That sole thing is enough to say it was worth to take the risk.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Six reasons why I find F# a better language than C#]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>I was thinking about this post for a while. The more I use F# and speak about it to others, the more often I am asked the same question: what are the advantages of using F#? It's not so hard to find those, but I wanted to have a list</p>]]></description><link>https://bart-sokol.info/2016/12/17/six-reasons-why-i-find-fsharp-a-better-language-than-csharp/</link><guid isPermaLink="false">5a4f63dd0185f50ca30ab639</guid><category><![CDATA[fsharp]]></category><category><![CDATA[f#]]></category><category><![CDATA[csharp]]></category><category><![CDATA[c#]]></category><category><![CDATA[programming]]></category><category><![CDATA[language]]></category><category><![CDATA[english]]></category><category><![CDATA[error handling]]></category><category><![CDATA[null]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sat, 17 Dec 2016 13:20:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>I was thinking about this post for a while. The more I use F# and speak about it to others, the more often I am asked the same question: what are the advantages of using F#? It's not so hard to find those, but I wanted to have a list that is more like fact list and less like personal preferences. Let's see what I came up with!</p>
<!--more-->
<p><em>First of all, a disclaimer. This is my personal opinion based on my experiences with both languages. I'm not trying to start any flame wars - I'm looking for strong facts, but they may not be same strong for everyone.</em></p>
<h2 id="1recordtypes">1. Record types</h2>
<p>I think there is more or less agreed among developers now that immutability is one of the desired properties for data structures. Sure, there are some cases where mutable types have some advantages (like performance critical code), but those cases are quite rare among the vast amount of code that we write every day. Additionally, there are lots of optimisations made on compile time and in the runtime that make performance impact of immutability almost neglectable, and even in some cases immutable data structures can be more performant (e.g. when doing comparisons between instances).<br>
But having immutability alone is not enough to be able to work in an effective way. We need to have additional tools to work with immutable types. One of those is the ability to easily create clones with one or more properties changed. This is where F# record types really shine. Let's look at this example:</p>
<pre><code class="language-fsharp">type Person = { Name: string; Age: int }
let john = { Name = &quot;John&quot;; Age = 27 }
let olderJohn = { john with Age = john.Age + 1 }
</code></pre>
<p>That's all you need to define the type, create an instance and clone it when using F#. Now let's try to write equivalent C# code:</p>
<pre><code class="language-csharp">class Person
{
  public Person(string name, int age)
  {
    Name = name;
    Age = age;
  }
  public string Name { get; }
  public int Age { get; }
}
</code></pre>
<p>That's just immutability, and we already have much more code. How to add cloning and updating values? Well, cloning is pretty easy, we can for example use <code>MemberwiseClone</code> method from System.Object, but we would need to implement it in every type we want to have this. The much harder part is updating the values. In this extremely simple case we can just create new object and copy properties from one to another, but what if we had not 2, but 10, 20 or more properties? Each time we would need to update even one property we would end up with a huge amount of code. I can't really think of an easy way to do it in the current version of C# (apart from some utils using serialization or reflection but that would be ugly and not really performant approach). There are plans to fix it in newer versions of C#, but until it's live we're stuck.</p>
<h2 id="2collections">2. Collections</h2>
<p>Immutable records are not the only thing we want to have - we also need to have immutable collections to be able to have fully immutable flow. And while creating an immutable version of existing collection is relatively simple in C# (having things like <code>ReadOnlyCollection</code> and <code>AsReadOnly()</code> LINQ extension), getting updated version with something modified is much harder. In F# you can write:</p>
<pre><code class="language-fsharp">let items1 = [0;1;2;3;4;5]
let head::tail = items1
let items2 = head::tail
</code></pre>
<p>Extracting head from the list (or array) is extremely easy, the same is for prepending it to the list. Of course, more complicated cases require the use of other tools like <code>List</code> or <code>Seq</code> modules, but it's there and it's easy to use. There are libraries for C# that make it possible as well - but it's another dependency you need to have in your project, and they are not so deeply integrated into the language.</p>
<h2 id="3discriminatedunions">3. Discriminated unions</h2>
<p>While records are great for keeping data that belong together, it's not the only case we can encounter when implementing some domain logic. I very often find myself in a situation where I want to have a data structure which will contain a different set of information for different cases. Classic object-oriented approach for this would be hiding the implementation behind a common interface and then using a plethora of design patterns to get the right information from the object.<br>
Let's see how it looks based on a common example: validation. We are getting some data structure which we need to validate according to the set of rules. What we need as an output is some data structure that will describe us what is the result of the validation. This is an example implementation of this in F#:</p>
<pre><code class="language-fsharp">type ValidationResult =
  | Passed
  | UnrecognizedProduct of Product
  | IncorrectPrice of Price
</code></pre>
<p>For simplicty I'll just add few results, but the list can be longer. Let's see how this can be done in C#:</p>
<pre><code class="language-csharp">interface IValidationResult
{
    bool IsPassed { get; }
}
class Passed : IValidationResult
{
    public bool IsPassed { get; } = true;
}
class UnrecognizedProduct : IValidationResult
{
    public bool IsPassed { get; } = false;
    public Product InvalidProduct { get; }
}
class IncorrectPrice : IValidationResult
{
    public bool IsPassed { get; } = false;
    public Price InvalidPrice { get; }
}
</code></pre>
<p>I kept formatting brief, but in real code this will be many more lines and potentially even files. Can you see a problem here? We don't have any common structure for all the cases, as they may contain different set of data depending on the kind of the error. But that's not the only problem we have - let's try to translate this result to user friendly message.</p>
<h2 id="4patternmatching">4. Pattern matching</h2>
<p>To display the right error message we can use pattern matching in F#:</p>
<pre><code class="language-fsharp">let getTranslation key = …
let getErrorMessage = function
  | Passed -&gt; getTranslation &quot;passed&quot;
  | UnrecognizedProduct product -&gt; sprintf (getTranslation &quot;unrecognizedProduct&quot;) product.Name
  | IncorrectPrice price -&gt; sprintf (getTranslation &quot;incorrectPrice&quot;) price.Gross
</code></pre>
<p>In C# I can see two approaches. One could be type-checking the result in method full of if's:</p>
<pre><code class="language-csharp">public string GetErrorMessage(IValidationResult result)
{
  if (result == null)
    …handle null param somehow…
  if (result.IsPassed)
    return GetTranslation(&quot;passed&quot;);
  if (result.GetType() == typeof(UnrecognizedProduct))
    return string.Format(GetTranslation(&quot;unrecognizedProduct&quot;), (result as UnrecognizedProduct).InvalidProduct.Name); 
  if (result.GetType() == typeof(IncorrectPrice))
    return string.Format(GetTranslation(&quot;incorrectPrice&quot;), (result as IncorrectPrice).InvalidPrice.Gross);
  …
}
</code></pre>
<p>The problem with this approach is visible at the end of the method. What to do for other cases? We don't have them yet, but they may be added in the future. With this code you won't get any warning if new implementation of <code>IValidationResult</code> is added to the code, and you need to either ignore it (by returning null, empty string or some generic error message) or throw an exception. Both are not really good ways to keep the code up to date. Can it be done in other way?<br>
We could change the definition of <code>IValidationResult</code> to have a method which will format the error message:</p>
<pre><code class="language-csharp">interface IValidationResult
{
    bool IsPassed { get; }
    string GetErrorMessage(string translation);
}
</code></pre>
<p>And then the code could get much simpler:</p>
<pre><code class="language-csharp">public string GetErrorMessage(IValidationResult result)
{
  if (result == null) { …handle null param somehow… }
  return result.GetErrorMessage(GetTranslation(&quot;unrecognizedProduct&quot;));
}
</code></pre>
<p>This is a much safer way to do it as at any time you'll be adding new validation result you'll have to add error formatting logic to it. But there are still some issues with this C# code. One is that we probably need to handle the null result case somehow (which we don't have to do in F#). The other problem is on much higher level - any time you need to check something based on the IValidationResult you would need to extend this class. Imagine you have such logic for a product which has plenty of fields and even more logic to handle different kinds of products etc. You'll end up with huge classes containing both the data and the logic. That would make tracking the logic across the products extremely hard because you need to check it in multiple implementations of the interface. For me, it's very cumbersome way of doing it cause I find code with separation between data structures and logic much easier to understand and track compared to heavy models.</p>
<h2 id="5errorhandling">5. Error handling</h2>
<p>Union types have another advantage when it comes to handling errors. There is a common pattern used in F# (and other languages as well) which can be illustrated with this simple type:</p>
<pre><code class="language-fsharp">type Result&lt;'TSuccess, 'TFailure&gt; = Success of 'TSuccess | Failure of 'TFailure
</code></pre>
<p>Having such simple type that allows you to say whether the action succeeded or failed is a great benefit. Not only your output type is more clearly stating that some operation may not succeed and you need to handle the failure, but also you have a very clear way of saying what exactly went wrong. Combine it with simple <code>bind</code> and <code>map</code> functions and you are on the right track - you can start doing Railway Oriented Programming. This deserves a post or even series of its own, but believe me - this is a game changer when it comes to error handling and heading towards error-free code.<br>
Of course, you can define the similar type in C# (and I would recommend you to do it and start using it) but without pattern matching, partial application and pipe operator it's much more complicated to use. Having defined bind and map functions will help a bit, but you just can't avoid the amount of code you need to write.</p>
<h2 id="6safedefaults">6. Safe defaults</h2>
<p>Having a nice way of handling errors is a great thing, but it would be even better to prevent them in the first place. That's where design decisions come in - F# defaults are safer than the ones in C#. Immutable records, collections and bindings (aka &quot;variables&quot;), non-nullable types by default and things like <code>Option</code> type (Maybe monad) baked into the language and standard libraries give you the power to write code which will be free from <code>NullReferrenceException</code> and other C# nightmares. Sure, writing very defensive code in C# can lead you to the same, but it will be at the cost of much more code you need to write.  And the more code you have, the bigger is the chance of having errors. Not to mention that readability and maintainability of the small codebase are much higher. With powerful type system, great type inference and language constructs like pipe and function composition operators, F# offers a lot that C# just cannot give, even in the upcoming (7) version.</p>
<h2 id="summary">Summary</h2>
<p>There are many lessons to be learned from using F#. But the biggest one for me is that C# is no longer the preferred tool when it comes to writing any kind of code. The amount of code you need to write, the unsafe defaults and lack of powerful language constructs makes C# much less appealing than it used to be. The more I experience F#, the more I find it the better choice for general purpose programming. And I would recommend you having your own ride, especially if you're a .NET developer - all the tools you need you probably already have on your machine. And I can guarantee you one thing - it will be cool and safe ride at the same time!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Your programming language is probably unproductive]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>It's really hard to create a good programming language. There are a number of aspects you need to think about, and you'll probably never reach the perfection. Still, there are some things you can take into account to make the code maintainable and easy to use and understand by humans.</p>]]></description><link>https://bart-sokol.info/2016/09/18/your-programming-language-is-probably-unproductive/</link><guid isPermaLink="false">5a4f630e0185f50ca30ab628</guid><category><![CDATA[programming]]></category><category><![CDATA[language]]></category><category><![CDATA[productivity]]></category><category><![CDATA[csharp]]></category><category><![CDATA[c#]]></category><category><![CDATA[fsharp]]></category><category><![CDATA[f#]]></category><category><![CDATA[java]]></category><category><![CDATA[ml]]></category><category><![CDATA[ocaml]]></category><category><![CDATA[elm]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sun, 18 Sep 2016 19:20:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>It's really hard to create a good programming language. There are a number of aspects you need to think about, and you'll probably never reach the perfection. Still, there are some things you can take into account to make the code maintainable and easy to use and understand by humans. And similarly, there are things that make the code much harder to read and use effectively. Let's get through some of them.</p>
<!--more-->
<h2 id="braces">Braces</h2>
<p>There is one thing that is common to most of the programming languages people currently use. They all take from the same design that was introduced a number of years ago, a design that allowed computers to easily understand more abstract instructions made by humans. The design which was created to easily create compilers for basically any platform out there. That design was implemented by a structural programming language called C.<br>
One of the key aspects of that design was an intensive use of all kinds of braces. They allowed to easily create starting and terminating points for all kinds of artefacts appearing in code, like blocks or function parameters. The idea was brilliant and it works really well even today.<br>
But what's good for computers is not always the best thing for human beings. Bytecode anyone? The introduction of braces in the code was a trigger for a number of religious wars, and it made us, developers, focus on the design of the language instead of focusing on the most important thing in our work - solving real problems.</p>
<p>Of course, there is a number of fields on which developers fight, some of them being fundamental, but vast of them are purely religious. While dynamic versus static typing can have a severe impact on how our programs will actually work, the location of an opening brace is definitely not that important. Moreover, the sole existence of braces as block delimiters makes even more harm. We are used to reading texts in our natural languages, and in those texts, we barely use any kind of braces. Additionally, they make some great capabilities of &quot;braceless&quot; languages like partial application much harder to implement. So, what's the best way to separate one block of content from another?</p>
<h2 id="whitespace">White space</h2>
<p>You know that. You see that every day in your code. People putting empty lines just to make one part of code distinguish from another. We all use indentation to mark blocks of code readable. Yet most of the languages force us to use braces almost everywhere. And while some of them allow omitting braces in some cases, many devs are so used to them that they put them basically everywhere. It ends up with code which has a ratio of meaningful code lower than 50%. Rest of it is pure boilerplate and don't give any value at all. Just look at the simple example:</p>
<pre><code class="language-csharp">Product GetProductById(int id)
{
    if (id &lt;= 0)
    {
        return null;
    }

    return _productRepository.Get(id);
}
</code></pre>
<p>And compare it with:</p>
<pre><code class="language-fsharp">let getProductById repository id : Product option =
    if (id &lt;= 0) then None
    else repository.Get id
</code></pre>
<p>It's a kind of code you'll probably find in any LOB application. Forget for a moment that it's an actual piece of software. Think about it as another paragraph of this post. Now try to read the body of both functions again. Which of them feels more natural?</p>
<p>The result may be a bit skewed because we are taught the first approach from the first days we start to learn programming. For most of the developers, the very first languages they interact with are ones like C, C++, Java, C# or JavaScript. The most popular, the most mainstream ones. Yet those are ones which have the most flaws in their design. And it's not only about braces or whitespace usage.</p>
<h2 id="verbosity">Verbosity</h2>
<p>Initially, code written in C tended to be quite concise. Small screens with small resolutions and small storage capacity forced developers to be very scarce on the amount of code they write. They used short variable names, acronyms and were trying to reuse what they had as much as possible. But as programs started to become bigger and bigger, this approach made them less and less readable, and eventually people started to be more elaborate in their code. The evolution of computers made it even more feasible, and people started to abuse the new capabilities. Languages like Java and C# made it to the almost ridiculous point where not only we have to be very explicit about every aspect of our code, but also made us split this code into an endless amount of files. And if we add to it the rise of design patterns and multi-layered code, we end up with code with basically mirrors the structure of the organisations we work for - corporations. We reached the point where form has overtaken content, where processes are more important than the actual purpose. We made the same mistake again.</p>
<h2 id="gettingbacktobasics">Getting back to basics</h2>
<p>For some time I got really fascinated with that beautiful, elaborated form. I enjoyed order, explicitness, curls of the block brackets. It's really tempting. But it also points towards nonsense. We start to treat the code as a piece of art, not a piece of engineering. And while a good design and well thought-through form help us to engineer better and more maintainable solutions, it cannot be our main focus. As in school of Bauhaus, the form needs to serve human, not the opposite. And if you look around you'll find out that it's a key to the success of many companies - the right amount of design backed by really clever engineering.</p>
<h2 id="evenmoreimprovements">Even more improvements</h2>
<p>So how can we make our code better and effectively make our software better? Think about using right tools. As programming languages are the basic tools in developers toolbox, think what you put in yours. Let's take a look at what people who are not software engineers use. There are languages which are very domain specific, like R, which was created by statisticians, for statisticians. In many aspects, it's totally different from the languages software developers use. Even with some real flaws, it's extremely successful in its field.</p>
<p>Then there are two more general languages that didn't go the C way, and in effect are very popular among people who aren't really software engineers. First one is Python, which is used very heavily in data science, but it's also very popular in web and game development and IoT areas. The second is Ruby, which was first programming language for many developers with a non-technical background. Both languages are very successfully used by initiatives like Django Carrots or Rails Girls and turn out to be very effective tools for learning programming. Their simple syntax and dynamic nature help people to focus on their intentions instead of on the form.</p>
<h2 id="goingfunctional">Going functional</h2>
<p>While both Python and Ruby are great tools for relatively simple solutions, their object-oriented nature has some serious drawbacks when it comes to more complicated solutions. That's where functional programming comes into the way. There is a whole family of languages which have a really effective design, and they are all functional languages. It's the ML family, which started with (surprisingly) ML language, whose most recent and actively developed ancestor is Ocaml. There are also languages which more or less take inspiration from the family, and you'll find Haskell, Elm and F# among them.</p>
<p>The first one is one of the purest functional languages, sitting on the top of the Ivory Tower of functional programming. And while it's great for learning functional programming, its applications are also quite limited.</p>
<p>Then we have Elm, which is gaining some big momentum right now, and there are reasons for that. It compiles to JavaScript and allows you to write purely functional applications that will work in a web browser. It's famous for its reliability and performance, hence if you're into web development you should definitely try it.</p>
<p>And then we have F#, which is general-purpose, functional first and strongly typed language that is primarily running on .NET platform. It can be also used to generate web applications in HTML and JavaScript, using tools like WebSharper or Fable.</p>
<p>All of those languages are quite easy to learn and help developers write concise and effective code with high maintainability and readability scores. Their simplicity end effectiveness is an inspiration for other language designers, and we can see concepts from those languages slowly appearing in other languages like C# or Java.</p>
<h2 id="summary">Summary</h2>
<p>Language design and form of the code shouldn't be the things developers put their focus on. Languages that have a simpler syntax and are primarily designed for humans allow us to focus on the purpose of what we write. Getting rid of unnecessary things from the code, along with proper use of whitespace, makes the code more concise and readable, and thus more maintainable. And the fewer things are out there, the less time people will spend on discussions on form, and the more they will be focused on their main goal - solving other people's problems.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Why Android sucks and why I'm still using it?]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>We're all addicts. We cannot walk out without our phones. We cannot even move to another room, knowing that some message may come unnoticed. We spend more and more hours every day looking at our smartphones, probably more than looking at other people or the world around us. Yet those</p>]]></description><link>https://bart-sokol.info/2016/07/18/why-android-sucks-and-why-im-still-using-it/</link><guid isPermaLink="false">5a4f629c0185f50ca30ab618</guid><category><![CDATA[mobile]]></category><category><![CDATA[android]]></category><category><![CDATA[ios]]></category><category><![CDATA[windows]]></category><category><![CDATA[google]]></category><category><![CDATA[smartphone]]></category><category><![CDATA[apple]]></category><category><![CDATA[microsoft]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Mon, 18 Jul 2016 18:15:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>We're all addicts. We cannot walk out without our phones. We cannot even move to another room, knowing that some message may come unnoticed. We spend more and more hours every day looking at our smartphones, probably more than looking at other people or the world around us. Yet those devices, on which we spend substantial amounts of money, are far from being perfect. Do you know anyone who's 100% happy with their smartphone?</p>
<!--more-->
<p>Yes, there are iPhone owners. They would say that their phones are great, that they love them. Until new model comes in. And have you asked them about the price? Gentlemen don't speak about money, right?</p>
<p>There are also Windows Phone (Mobile, 10, whatever it's called at this moment) users. They are either hating their phones, or loving them. Haters are waiting till their contract is over. Or phone drops &quot;accidentally&quot; into toilet ;) Lovers just don't use their smartphones. Or at least the &quot;smart&quot; part. &quot;How is your YouTube app doing?&quot; - you may ask, if you want to be rude. Oh, you can also ask them to change date/time in settings. Good idea to get them busy for a few minutes.</p>
<p>And there is Android. Globally, the most popular mobile operating system. Running on thousands of different device models, the same bad on all of them. Yes, it's customizable. Yes, it's the most open one. But what's its advantage is also its curse. Countless combinations made writing good quality app a real challenge. Probably 90% of apps in Play Store could be thrown away and nobody would even notice. And the (Android) world would be a better place. But it won't happen. It's gone too far and now it's too late to clean it up. Sure there are good quality apps as well, but nobody says how much money is being constantly pumped into them to make them work like that. And even when you'll be using the top notch apps only, there is the system. The worst part.</p>
<p>It looks good. It has quite well organized menus and options. Material Design brought fresh and consistent look and feel to the system and applications. There was a huge work put into designing all the interactions, all the animations, all the icons, all the layouts. It seems to be good counterpart to polished iOS. Yet everything is broken by how it's actually implemented.</p>
<p>Lag. It's the word Android users don't want to say. It breaks all the great ideas apart; it makes all the design virtually pointless. How many times you've done some stupid or irritating things because you wanted to act too quickly? How many times did you press the wrong option because you thought first time system didn't react? How many times did you think that some app is broken, while it was just waiting to be shown for too long?</p>
<p>I've been using Android since the early days of the platform, when it was really raw and unpolished. Over the time system evolved dramatically, and I really appreciate the work Google and other companies have put to make it so. But I also cannot understand how devices which are almost doubling in performance each year are working same sluggish way. Even without system customizations, which are often told to be cause of the issue, devices are not getting much faster. They may run newest games with higher frame rates, on higher resolutions, with more details. They may crack results in benchmarks. But hey, is this what we use them for most of the time? Is this really what matters for most of the users?</p>
<p>I've owned number of Android phones, from HTC, Samsung, LG and currently Motorola (aka Lenovo). With first 3 brands I've always opted to install custom ROM after some time, because of the performance and/or battery issues with manufacturer software. With my previous device, LG G2, installing CyanogenMod gave it a blast and for some time it almost felt like it should - responsive, smooth and not so power consuming. But after few months it always comes back to state where you feel it's not like it should be. I thought that I should just buy phone with stock (Nexus) or almost-stock (Moto, OnePlus) software. Due to availability I opted for Moto X Style (aka Pure) - I played with it in the store and it seemed to be great. But life again shown that after installing all required software and just few weeks of use it gets same sluggish as the old phone. Even compared with 4-year old iPhone with max fourth of the resources, it seemed to be slow, which should say something.</p>
<p>Saying that I still use it, and I'll probably stick with Android for some more time. Every alternative has it flaws - and the only real one being iPhone doesn't make me wanting to change. Sure, if the price difference wouldn't be so substantial (at least half more for comparable iPhone model vs Moto X) the choice would be really tough, and based on OS differences. Each year I hope that someone will make clean, powerful and time-proof Android phone, with great user experience that would match iOS, but with power and thought-through design of Android. But this year hasn't come yet.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Why most of our work environments are counterproductive?]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Recently I have read few articles on how our bodies and brains especially work, and how it affects our everyday living. They described how our environment and our habits affect our lives and our health, both physical and mental. It provoked me to think a bit about my experience and</p>]]></description><link>https://bart-sokol.info/2016/02/09/why-most-of-our-work-environments-are-counterproductive/</link><guid isPermaLink="false">5a4f622e0185f50ca30ab60f</guid><category><![CDATA[office]]></category><category><![CDATA[work]]></category><category><![CDATA[productivity]]></category><category><![CDATA[remote]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Tue, 09 Feb 2016 19:05:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Recently I have read few articles on how our bodies and brains especially work, and how it affects our everyday living. They described how our environment and our habits affect our lives and our health, both physical and mental. It provoked me to think a bit about my experience and observations and I'd like to share it with you.</p>
<!--more-->
<h2 id="therootcause">The root cause</h2>
<p>Our brains. Extraordinary machines, bio-computers, and even more. We use them every day and still don't know exactly how they work. But having more and more studies on it we slowly start to discover some of the principles. One of the things that many studies confirm is that human brain sucks in multitasking. It reminds more powerful 1-core CPUs than modern multi-core ones. Whenever it is pushed to do few things at the same time it switches frequently between the tasks rather than working on few of them at once. And as you may expect, there is significant cost of switching, just like in our computers.<br>
Of course that's only tip of an iceberg and there are lots of aspects omitted here (like things you do automatically or unconsciously) but when it comes to main focus of the brain (think of brain's &quot;main thread&quot;), it seems to be pretty relevant. That allows me to safely assume that distractions can significantly decrease our productivity and creativity. Basing on this assumption let's look how our work environments look like and how do they fit into this theory.</p>
<h2 id="openspace">Open space</h2>
<p>This is the most common and preferred setup in most of the corporate world. It gives a lot of flexibility and is effective when it comes to utilization of the office space. You can fit the biggest number of desks and people in given area with this setup. Other benefits of open space include ability to quickly come to any person within a zone, which makes communication quite easy.<br>
But the same things have also lots of drawbacks. The amount of people can be the first distraction. They will be coming and going, moving and talking, constantly nagging your senses. Visual and auditory distractions do not finish on it. People around will be attending calls, speaking aloud, coming to you to have a chat and so on. This noise can kill any productivity and exhaust even strongest people. There are also lots of other things to not like in open spaces (like spreading diseases or aircon setup problems) and probably that's why it is the least liked office setup among all office workers.</p>
<h2 id="smallroomoffices">Small room offices</h2>
<p>Other often encountered office setup is small room configuration, where (ideally) each team has its own room. The amount of people differ quite widely (from 2 to 10+) but the idea stays the same - people working together should be close to each other and separate from other teams. This of course reduces the impact of other people's behaviour to just few of them, but the impact from those sitting close is even bigger. If you're lucky to end up with people who respect each other and are not too distractive then your win - it can be quite productive environment. Still you cannot avoid all the issues which are common with open space setup, but at least you get a bigger chance of having sane environment. It is a lot easier to have some agreement among few people than among tens or hundrets.</p>
<h2 id="coworkingspaces">Coworking spaces</h2>
<p>Usually coworking spaces land somewhere in between open spaces and small room offices. Depending on their setup, amount of people or even time of day they can be more or less productive environment. They can be a good option to change the environment a bit, look for some inspiration or meet other people - all of those can have positive impact on your productivity. But in long term they can have opposite effect, again by too many distractions tempting your senses.</p>
<h2 id="homeoffice">Home office</h2>
<p>For many of us this is the &quot;workplace of dreams&quot; - but is it really like that? There are of course many benefits of this solution, such as saving time and money on commute, facilities of your choice (for example preferred chair and desk - if you can afford it) and limited amount of distractions. But there are some requirements for such environment to be productive. You need to make sure that there won't be anyone who will be distracting you from doing your work (think your family, dog, partying students or remodelling hobbyist as neighbours) and you'll have enough strength not be seduced by temptations around (e.g. playing games, cleaning the flat, going to sleep). You should also have some separate space, preferably your own room where you can keep all your required stuff and work distraction-free. And one more thing to consider is health - you limit the risk of getting diseases spread through air, but sitting at home all the time also won't make you healthier, so you should consider doing some exercises and going out to keep you healthy and sane.</p>
<h2 id="idealsolution">Ideal solution?</h2>
<p>There is one more approach I've heard about and it's probably very rare and expensive. The only company I know about which provided such conditions is Fog Creek Software (authors of Stack Overflow, Trello and others; don't know if it's still used there though). Their office setup consisted of separate room for each person, which is quiet, separated from most of the distractions and allowed a lot of customization, including desk height, air temperature, amount of light and so on. Until you reach some shared spaces you shouldn't be distracted by other people as well, unless you explicitly want to. Of course you can find some drawbacks of such solution (not only the cost) but it seems to be closest to ideal office space I can imagine. Of course you still need to take care of some common distractions which are independent of the place you work in.</p>
<h2 id="commondistractions">Common distractions</h2>
<p>Apart from place-specific issues with work environment you can find some which are common across all of them. One of the most common distractions are emails and communicators. You constantly get bombarded by notifications about new messages and you're feeling pressure to respond to them. If you're in shared space then things are even worse - you often hear other notifications as well, like ringing phones, mails, chats etc. Given that our brains are trained to react to those notifications it can distract you from your work completely. You can try to minimise it by using headphones, but usually you need to keep your music quite loud (often distracting others) or use unhealthy in-ear headphones. Other thing that can kill your productivity is clutter on your desk or around it. I don't think sterile environment is good either, but too many papers, devices, cups and other stuff around you can easily distract you from your main focus. The same applies to your computer - desktop full of icons or too many open applications will work exactly the same way.</p>
<h2 id="howtomakethingsbetter">How to make things better</h2>
<p>So we know that there are a lot of things which are killing our productivity, but can we do something about it? Of course yes - but the amount of impact you can have heavily depends on your employer standards and office culture. In the ideal world you should have flexibility to adjust your environment to fit your requirements to stay productive. Ability to work from different places (so remote work possibility), flexible working hours (and working time as well) and co-workers respecting each other seem to be very important things to consider when choosing the work environment. From the things you can do yourself I would recommend:</p>
<ul>
<li>Getting rid of any not critical notifications during your work time - Facebook, Twitter, private e-mails and chats can quickly kill your productivity</li>
<li>Unsubscribe from any newsletters (and other e-mails/app notifications) that you don't read or redirect them to separate e-mail which you'll read when you'll have some spare time</li>
<li>Limit the time you check office e-mail account to few times a day, e.g. check and respond to e-mails only before/after your coffee or lunch break</li>
<li>Declutter your desk and your computer from anything that is not crucial for your work (but don't go to far with it - keep a bit of cosiness as well, e.g. by nice wallpaper or some small personal accents on your desk)</li>
<li>When you're in shared environment equip yourself with good quality closed headphones which will be comfy enough to use them for hours; listen to some relaxing or stimulating music, preferably acoustic (again less distractions), to separate yourself from noisy environment</li>
<li>Try to change your environment from time to time - ask to work remotely from home or coworking space if possible</li>
<li>Make some breaks during your work, have a walk or even a bit of exercise if possible - it will let your brain process the information it gathered and give a bit of relief from distracting environment</li>
</ul>
<p>The list for sure can be longer, and if you have any other ideas or experiences don't hesitate to share them with me and others.</p>
<h2 id="summary">Summary</h2>
<p>Staying productive at work is not easy and it depends on many factors - from personal predispositions and habits to employer policies and co-worker's empathy. Knowing what can kill your productivity should help you avoid the biggest distractions and stay more focused on your work. It should also help you staying healthier and more relaxed, which is an obvious benefit. Whenever you will feel too distracted and unproductive, take a break, look at your habits and environment from aside and try to fix it, step by step. Every step taken will be step towards happier life!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Riot.js and Material Design Lite on Windows]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Recently I wanted to build a small web app for my own purposes (more like an experiment) and I was thinking how to approach it. For whatever reason I decided to go with SPA-like approach, having simple HTTP service as a backend and some simple yet powerfull enough web app</p>]]></description><link>https://bart-sokol.info/2016/02/05/riotjs-and-material-design-lite-on-windows/</link><guid isPermaLink="false">5a4f61b40185f50ca30ab5fe</guid><category><![CDATA[web]]></category><category><![CDATA[javascript]]></category><category><![CDATA[js]]></category><category><![CDATA[css]]></category><category><![CDATA[html5]]></category><category><![CDATA[riot.js]]></category><category><![CDATA[mdl]]></category><category><![CDATA[windows]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Fri, 05 Feb 2016 22:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Recently I wanted to build a small web app for my own purposes (more like an experiment) and I was thinking how to approach it. For whatever reason I decided to go with SPA-like approach, having simple HTTP service as a backend and some simple yet powerfull enough web app as a frontend. And as you probably know, the choice now is overwhelming - think Angular, React, Polymer, and so on. All of those libraries give you a lot of possibilities, but also come at cost. Not only they are heavy to download, but also they have quite steep learning curve and bring a lot of stuff which you'll never use in a simple app. In the search of alternative solutions I encountered small library called <a href="http://riotjs.com/">Riot.js</a>, introducing itself as &quot;React-like user interface micro-library&quot;. Quickly looking at some samples and docs I decided to give it a try. And as some things weren't as simple as I expected, I decided to put together a quick start guide with solutions to the issues I've encountered. So here you are :)</p>
<!--more-->
<h2 id="installingrequiredtools">Installing required tools</h2>
<p>As with any JS framework nowadays you need to start with Node.js and NPM*. Download latest stable version from <a href="https://nodejs.org/">Node.js website</a> and install it on your system. Once you're done, open console and we can start installing stuff. We need to install <a href="http://bower.io/">Bower</a>, Riot.js and simple HTTP server to make things easier:</p>
<pre><code class="language-bash">npm install -g bower
npm install -g riot
npm install -g http-server
</code></pre>
<p>** Some side note here - most of it is not needed; you can download everything from Riot site, but it won't be so cool, so you'd better stick with proposed approach*</p>
<h2 id="bootstrappingtheproject">Bootstrapping the project</h2>
<p>Once ready, you can start bootstrapping your project. Create some folder where you're going to keep your project, then navigate to it in your console window and type next magic command:</p>
<pre><code class="language-bash">bower install riot --save
</code></pre>
<p>You should have now <code>bower_components</code> folder with Riot library inside. You can now create index file in your editor of choice (if you have no idea what to use, give <a href="https://atom.io/">Atom</a> or <a href="http://brackets.io/">Brackets</a> a try). Create <code>index.html</code> file with HTML5 document structure and start adding required references. At the bottom of your <code>body</code> tag add reference to Riot.js:</p>
<pre><code class="language-html">&lt;body&gt;
    ...
    &lt;script src=&quot;/bower_components/riot/riot.min.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
</code></pre>
<p>There is also riot+compiler version available, but given the style library I will offer you to use it is better to stick with the minimalistic approach.</p>
<h2 id="yourfirstriottag">Your first Riot tag</h2>
<p>Once you're done with the previous steps, you can start adding your first tag. Create a folder you're going to use to store your tags in (I'd go with <code>tags</code> for purpose of this guide) and create a new file. Name it as you want to name your tag (not a requirement, but seems to be a good choice) with <code>.tag</code> extension, keeping in mind that recommended naming scheme is two-part: use names like <code>login-form</code>, <code>login-failed</code>, <code>item-list</code>, <code>item-details</code> etc. Again, not a requirement from Riot, but recommendation from W3C, so better stick with it.<br>
Inside your new file start creating your new tag. If you decided to create <code>item-list</code>, wrap everything in <code>&lt;item-list&gt;</code> tag:</p>
<pre><code class="language-html">&lt;item-list&gt;
    ...(your HTML code goes here)...
    ...(and JS code below it)...
&lt;/item-list&gt;
</code></pre>
<p>And save it as <code>item-list.tag</code>. Your first custom tag is ready! Well, almost. You need to use it somehow on your page. Navigate to <code>index.html</code> file in your editor and add a bit of plumbing code there:</p>
<pre><code class="language-html">&lt;body&gt;
    ...
    &lt;script src=&quot;/bower_components/riot/riot.min.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        riot.mount('item-list')
    &lt;/script&gt;
&lt;/body&gt;
</code></pre>
<p>This will mount the tag into your document's DOM. The only thing left is to somehow translate your tag so it can be actually used on your page. And here we encounter the biggest issue.</p>
<h2 id="findingtherightcommand">Finding the right command</h2>
<p>All Riot.js tags need to be compiled before they can be used on your page. You can just use version of Riot.js with compiler built in, but it won't work well with many style frameworks, including MDL (more on that later). So, let's go with compilation - shouldn't be hard. Let's try:</p>
<pre><code class="language-bash">riot tags/item-list.tag
</code></pre>
<p>Mission failed. At least for me. Command not found. Nah, not the <code>riot</code> command, it is present in path. The issue is inside <code>riot</code> command, which is trying to run <code>sh.exe</code> - which is not present on my system. So, what can we do now? We have to go deeper. In the installation folder for Node modules you need to search for riot module and check if you have the right command inside. For me it was found here:</p>
<pre><code class="language-bash">C:\Users\{username}\AppData\Roaming\npm\node_modules\riot\node_modules\.bin\riot.cmd
</code></pre>
<p>This one uses node.exe to run Riot JavaScript code, and it's working fine. So you can stick with it, create some script which will compile it, create some Gulp task or whatever - just remember to point it to right script*. Once your tag is compiled, you should get <code>item-list.js</code> file in your <code>tags</code> folder. If yes, then let's move to next step.</p>
<p>** Yes, I should probably raise an issue (or even PR) to Riot.js to solve it. Maybe later. Or maybe you can do it? :)*</p>
<h2 id="includingyourtaginyourcode">Including your tag in your code</h2>
<p>So, you have compiled your first tag and it's now time to use it. Modify your <code>index.html</code> file by referencing compiled tag file and putting your shiny new tag somewhere in your (HTML) body:</p>
<pre><code class="language-html">&lt;body&gt;
    ...
    &lt;item-list&gt;&lt;/item-list&gt;
    ...
    &lt;script src=&quot;/bower_components/riot/riot.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;/tags/item-list.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        riot.mount('item-list')
    &lt;/script&gt;
&lt;/body&gt;
</code></pre>
<p>Now let's see if it works - you can use <code>http-server</code> command installed earlier to serve the files and view them in browser. By default it should start listening on 8080 port, so once you run it navigate to your browser and open <code>localhost:8080</code>. You should see your brand new tag displayed on the page. If not then check all the steps above again ;)</p>
<h2 id="addingsomestylewithmaterialdesignlite">Adding some style with Material Design Lite</h2>
<p>Material Design Lite (MDL) is CSS/JS style framework created by Google, implementing their design language called (ta-da) Material Design. It's maybe not so comprehensive as Bootstrap or other great frameworks, but it provides some high-quality components to build great looking websites utilizing this neat design language. Starting is very simple - you just need to add references to MDL to your HTML file, either from CDNs or from local source. For local development I prefer to have everything locally - you can do it by installing MDL with Bower:</p>
<pre><code class="language-bash">bower install mdl --save
</code></pre>
<p>Now you can add it to your <code>index.html</code> file, CSS in <code>head</code> section, JS in body:</p>
<pre><code class="language-html">&lt;head&gt;
    ...
    &lt;link rel=&quot;stylesheet&quot; href=&quot;/bower_components/material-design-lite/material.min.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
    ...
    &lt;item-list&gt;&lt;/item-list&gt;
    ...
    &lt;script src=&quot;/bower_components/material-design-lite/material.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;/bower_components/riot/riot.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;/tags/item-list.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        riot.mount('item-list')
    &lt;/script&gt;
&lt;/body&gt;
</code></pre>
<p>Now you can use MDL classes in your elements. Navigate to <a href="https://www.getmdl.io/">MDL website</a> for details how to use it. Once you save your changes, remember to recompile your tags each time you change them! One of the solutions for this is to use <a href="https://github.com/jumilla/atom-riot">riot plugin in Atom</a> which offer auto tag compilation on save. You can also use some file watchers (e.g. using Gulp) to do it for you.</p>
<p>At this point I should also say few words on why you should compile everything manually instead of simply using riot+compiler script. Unfortunately because of the way MDL is constructed (and some other frameworks as well) it doesn't handle well dynamic DOM, which is how riot+compiler works - it generates DOM objects on the fly. Without precompiled tags many JS-based functionalities provided by MDL just won't work, which will negatively impact both visual and functional aspects of your application. I think the compilation step is not so hard once you set up everything, and MDL seems to be worth the effort :)</p>
<h2 id="summary">Summary</h2>
<p>Now you should have simple yet powerful startup point for your next website or webapp. Setting everything from scratch should let you understand how it works and customize many aspects of your app with ease.<br>
Using two simple and light libraries you get a lot of things for free, without a lot of effort or cost of investing in larger frameworks. You get modularity, easy management of components and separation of styling from functionality. For sure it won't be solution for every web app you'll want to create, but for small to mid size solutions it should be quite a good choice. And as almost everything is build using very basic tools and in simple manner, moving to some other frameworks in future should be also pretty easy. That's why I praise minimalistic solutions - they let you focus on the purpose of doing things, not the way how to do it.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Developing software for public institutions]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>In these days it's hard to imagine any bigger organisation to work without proper software supporting its everyday tasks. Very often this needs to be highly specific system that cover custom data and custom workflows, but also specific tools and technologies used within the organisation. There are also many common</p>]]></description><link>https://bart-sokol.info/2014/11/19/developing-software-for-public-institutions/</link><guid isPermaLink="false">5a4f60a10185f50ca30ab5fa</guid><category><![CDATA[software]]></category><category><![CDATA[process]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Wed, 19 Nov 2014 11:24:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>In these days it's hard to imagine any bigger organisation to work without proper software supporting its everyday tasks. Very often this needs to be highly specific system that cover custom data and custom workflows, but also specific tools and technologies used within the organisation. There are also many common functionalities across institutions, e.g. shared by multiple universities or government organs. And seeing how it's currently handled in Polish institutions pushes me to ask: how hard can it be?</p>
<!--more-->
<h3 id="theproblem">The problem</h3>
<p>Just take a look on a newest &quot;failure&quot; - system made for 2014 local elections. I won't go into technical details about the system cause I don't have enough knowledge about all the circumstances, but the circumstances itself are a very good starting point. How can it be that the development process for such an important system starts just 3 months before the elections? For sure there is some fault in public orders system which doesn't handle critical cases well. Loosing competitors can revoke the results until it's too late to actually start work. And the specifications… How is it possible that people who create requirements aren't able to provide sufficient technical requirements, not to mention judging the results. And the cooperation, or rather lack of it. Is it really so hard to have some common standards across multiple institutions? Is it really so expensive to have a group of experts dedicated to help people from different sections create those standards and help to implement it?</p>
<h3 id="somepossiblesolutions">Some possible solutions</h3>
<p>So how can we address those issues? First of all, by learning. Look around the world and see how others are handling such challenges. In the UK for many years there is a standard methodology that is required to be used by government organisations for managing projects. It's called PRINCE2 and can be used in many different areas. It keeps focus on managing the resources effectively, making sure you learn from what you're doing and keeping track on progress. With P3O - Portfolio, Programme and Project management practices it helps British institutions deliver high quality project with benefits for everyone. The benefits are obvious, and the cost of implementing it is really low compared to the results. Why not reuse it then?</p>
<p>And then it comes to software development. There are virtually endless options available, I can just name few. Is it really necessary to have public orders for such an important software? Shouldn't it be handled differently? As the domain in this case is very specific there should be a requirement for the ones that actually design such software to fully understand the needs of customer. Is this possible that some random company that has only a very brief understanding of what is required, basing on public order specification, create a good quality software in short term and with lowest possible cost? It seems almost impossible, and it's confirmed by reality. In my opinion the best approach for government software is to have in-house software development teams that not only know how to create computer systems, but also have good understanding of how those institutions work. This (at least in theory) should not only be cost-effective (in a long term) but also should guarantee that the results match the expectations.</p>
<p>The other option is for some related institutions to sign long term contracts with vendors to do the work. It could be more cost-effective and probably could improve quality even further, but there is a catch. If a vendor is selected mainly (or even only) on a basis of expected cost, it won't work at all. There is plenty of companies that assume that every task can be handled by limited number of students, and with even brilliant students you'd probably won't have enough experience and knowledge to solve all the complicated tasks. Not to mention analyzing, understanding and documenting sometimes ridiculously strange requirements.</p>
<h3 id="summary">Summary</h3>
<p>There is no perfect approach for given problem, and the problems and solutions I've mentioned are only tip of an iceberg. Nevertheless, even small steps forward can help to solve numbers of problems with just minimal effort. We need to learn, to cooperate and not to look for guilty ones, but look for solutions. Without that each and every project of this kind would be a Russian roulette, with more chances to lose than win.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Not so short story of the software testing]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Today I'll tell you a story about testing.</p>
<!--more-->
<h2 id="thestorybegins">The story begins</h2>
<p>Some long, long time ago human race started to code. Everyone was happy that the software they're writing was working (well, in most cases it wasn't, but let's skip it). So they kept writing even more software, and begun</p>]]></description><link>https://bart-sokol.info/2014/10/19/not-so-short-story-of-the-software-testing/</link><guid isPermaLink="false">5a4f5fd10185f50ca30ab5f5</guid><category><![CDATA[software]]></category><category><![CDATA[testing]]></category><dc:creator><![CDATA[Bart Sokol]]></dc:creator><pubDate>Sun, 19 Oct 2014 08:37:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Today I'll tell you a story about testing.</p>
<!--more-->
<h2 id="thestorybegins">The story begins</h2>
<p>Some long, long time ago human race started to code. Everyone was happy that the software they're writing was working (well, in most cases it wasn't, but let's skip it). So they kept writing even more software, and begun creating <em>systems</em>, not <em>only</em> programs. And then, one day, someone asked the programmer: &quot;How can I be sure that the system you've developed works as expected?&quot;. &quot;Well, you can test it.&quot;, he answered. And the whole story of software testing begun.</p>
<h2 id="evolution">Evolution</h2>
<p>First, it was all manual. Someone just thrown few numbers into system and checked if output was correct. Then someone discovered that he can program the same, and the first automated tests were there. They would probably be called now <em>integration tests</em>, as they were crossing the whole system, not only one piece of software.</p>
<p>As systems got even more complicated, developers introduced <em>layers</em>, and discovered that each layer can be tested independently. By coincidence, object-oriented programming was on everybody's tongue, so someone said &quot;Hey, let's test just one class at once!&quot;. And we arrived at the very beginning of every modern programmer's testing experience - writing <em>unit tests</em>.</p>
<h2 id="expansion">Expansion</h2>
<p>So, now you test <em>each and every</em> class in your code. You've got perfect code coverage figure. And you run your software, and bang! It explodes. Database has change since the last time you've checked. So, as an experienced developer, you go and write integration tests (sounds familiar?). Then to make sure your perfect UI (it's always perfect) works well too, you write <em>coded UI tests</em>. And now you think you can sleep well.</p>
<h2 id="badthingshappen">Bad things happen</h2>
<p>Until one day critical bug is found on production environment. You wake up at night, write <em>regression test</em> to verify it and fix it ASAP. Once again, tests saved you and let you have less nightmares.</p>
<p>But the customer is always unhappy. With your latests release performance of the software degraded drastically and everyone asks why. As you're now an unquestioned expert in software testing, you sit down and write <em>performance tests</em> that measure each and every important piece of code, compare the results and tell you where is the bottleneck you have to fix. Once again you are a hero, and the world is saved, they don't have to wait 500 ms for search results. Now it only takes 400.</p>
<h2 id="whatelseshouldiknow">What else should I know?</h2>
<p>There are plenty of tests that you should be aware of. Smoke tests that let you quickly judge software environment stability; security tests that cover most common security flaws and let you know how unsecure your system is; and a whole bunch of other manual or automated tests that can be proceeded.</p>
<h2 id="waitmanualicanwriteacode">Wait, manual?! I can write a code!</h2>
<p>Yes, manual. Manual testing is as important as automated (or even more). There are millions of things that computers can't notice, things that cannot (and shouldn't) be automated. Some may say that everything can be coded; the answer is yes, but what's the cost? Is it worth automating <em>everything</em>?</p>
<h2 id="butheyimadevelopernottester">But hey, I'm a developer, not tester!</h2>
<p>You are, and your responsibility is to make sure (and prove in many cases) that what you've developed is highest possible quality and works <em>as expected</em>. Of course, there should be some QA team that would help you with this, but remember that they are to <em>support</em> you, not to <em>replace</em> you. I would cover more on each team member responsibilities in one of the next posts.</p>
<p>The story end here for today. Hope you've enjoyed it and you would start thinking more about the quality next time you estimate your task. The road to glory is here long and bumpy, but don't be afraid! The world would be thankful!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>