<?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:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matti Bar-Zeev on Medium]]></title>
        <description><![CDATA[Stories by Matti Bar-Zeev on Medium]]></description>
        <link>https://medium.com/@mattibz?source=rss-ff40a255fd6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lca1Px4bsHARyMx_hva0Hw.png</url>
            <title>Stories by Matti Bar-Zeev on Medium</title>
            <link>https://medium.com/@mattibz?source=rss-ff40a255fd6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:59:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattibz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating Your Code Quality — Considerations and Innovation]]></title>
            <link>https://medium.com/duda/automating-your-code-quality-considerations-and-innovation-671472193d85?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/671472193d85</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[quality-software]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 13:19:07 GMT</pubDate>
            <atom:updated>2022-02-10T13:44:38.242Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating Your Code Quality — Considerations and Innovation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wh0ppkxwbFyFaO0YaTMlCg.png" /><figcaption>Photo by <a href="https://unsplash.com/@trueagency?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">True Agency</a> on <a href="https://unsplash.com/s/photos/developer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As your software project matures, code quality becomes extremely important, to the point where it can determine whether your project succeeds or fails. But what does “code quality” really stand for? What tools and considerations should you take into account when maintaining it, and where does innovation come into the picture?</p><p>In this post you’ll be joining me as I answer these questions, with some real use cases and a taste of how Duda approaches this challenge. Are you ready to take the next step towards software craftsmanship? Let’s go…</p><h3>What is code Quality?</h3><p><a href="https://www.codegrip.tech/productivity/why-is-code-quality-important/">Code quality</a> is a set of standards and practices that allow your code to achieve 2 main things:</p><ul><li>Fulfill its purpose in the most efficient way</li><li>Enable a safe and easy means to refactor or change it when required</li></ul><p>While a few developers can cope with code of small volume and random loose-ends here and there, large organizations must set some standards and practices, by which <em>all</em> should follow and ensure that the code remains clean and tidy for the next person to modify or debug.</p><p>Poor code quality means that your customers are getting their new features or bug fixes late, if at all, since modifications are extremely hard and risky.</p><p>Another side effect of poor code quality, which is not commonly spoken about, is that it tends to lead to frustration within the development team, that in turn leads to top developers abandoning what they consider “a sinking coding ship”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jRwwVrL7-xc04XMsEqDVNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@elisa_ventur?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Elisa Ventur</a> on <a href="https://unsplash.com/s/photos/frustration?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Can you harm your own code?</h3><p>We sometimes tend to feel that the potential of damaging our code lies with others, but both you and your peers have the same potential of harming the quality of your code, and it can originate in the most insignificant things you can think of, for instance:</p><p>Say you did a PoC for the project you are working on and introduced a new library dependency to your code. But then you decided to revert the PoC and whoops, you forgot to delete the dependency. Your code, though still working, now has a redundant dependency that gets installed in each developer’s machine and on each build pipeline. Aside from taking time, this dependency might even open a window for security breaches, for no real reason.</p><p>You would surely want to prevent such cases, and so you say — “I’m an experienced developer. I will remember to remove that dependency when I’m done”. <br>But reality tells us that as much as we’d like to, we cannot keep such promises, simply because we forget. So how can we still prevent such cases from happening?</p><h3>“You cannot enforce what you cannot automate”</h3><p>Let’s assume you’ve already agreed with your peers and managers on certain code quality standards and practices. As with everything, the weak link in that chain is our human nature — when we’re writing code or handling the numerous tasks our craft demands of us, we sometimes neglect the well agreed standards, and the reasons are irrelevant. It does not mean you are a bad developer, it just means you’re human.</p><p>If we leave the enforcement of these standards to our memory and good will, they are bound to be broken. We need something better to protect us from ourselves. If we take the example above, we’d like some automated tool to alert us when such a dependency is left hanging redundant.</p><h3>Advantage of automated vs. manual tools</h3><p>Reviewing any PR and remembering each standard or practice is practically impossible, not to mention that waiting for that PR to get reviewed can sometimes be nerve wracking.</p><p>Another interesting fact is this — I’d like you to imagine the feeling of getting bad coding feedback from your colleague, and then imagine the feeling of getting the same feedback, but from an automated process? Which one is better received? You’d probably feel that the automated feedback has a better “taste” to it.</p><p>Yes, we should strive to get all our standards enforced in an automated manner. It’s fast, it’s friction-less and it scales well.</p><h3>Finding the right tools for the job</h3><p>For each standard and practice there is a tool that is best suited to enforcing it.</p><p><a href="https://eslint.org/">ESLint</a> is a great tool for “static code analysis” — a method of inspecting source code before a program is run, done by analyzing a set of code against a set of coding rules. You can also extend ESLint with your own organization’s rules, to align the coding style and avoid common pitfalls.</p><p>Testing is another awesome tool for making sure no regressions are made and refactoring is easy. Commit linters can inspect your commit messages and make sure they comply with <a href="https://www.conventionalcommits.org/en/v1.0.0/">conventional-commits</a>, for instance.</p><p>These are just a few examples of the tools we developers have in hand.</p><p>If we take the previous example of preventing redundant dependencies in our project, we would like a tool that inspects the dependencies and the code of a project, and makes sure that there is at least a single usage for each dependency registered. Such tools exist, like Yarn <a href="https://github.com/depcheck/depcheck">depsCheck</a>, NPM’s <a href="https://www.npmjs.com/package/depcheck">depscheck</a> or <a href="https://github.com/depcheck/depcheck">depcheck</a>, but at least at the time of writing these lines, these tools do not support Monorepos <em>well</em>.<br>This is where innovation kicks in…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vF83anRWzo8QVvL9t8sMHw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hnhmarketing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hunter Haley</a> on <a href="https://unsplash.com/s/photos/tools?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Inventing your own tools</h3><p>Sometimes the tool you need cannot be found or does not have the exact feature you’re looking for, and then you have two options — leave the enforcement to be done manually, with all the caveats mentioned above, or invent it yourself. At Duda we realized that if we’d like to keep our monorepo clear from redundant dependencies, we need to create our own tool for that. This tool, aside from finding these redundant dependencies in nested packages, also offers to fix them for you.</p><p>Let me show you what I’m talking about — I’ve added “ESLint” as a dev dependency to one of the packages in our <a href="https://en.wikipedia.org/wiki/Monorepo">monorepo</a>, and run our tool:</p><pre>yarn deps:check</pre><p>It goes over all the packages of the mono repo and scans them. Here is the outcome I get:</p><pre>UNUSED DEV-DEPENDENCY eslint package is unused, in order to fix this issue, please REMOVE this package from the devDependencies list</pre><pre>ERR! depsCheck FAILED: Something is wrong with your package.json dependencies list. Please follow instructions and fix these issues manually or run with — fix</pre><pre>error Command failed with exit code 1.</pre><p>The automated fix simply asks whether or not to remove this redundant dependency:</p><pre>UNUSED DEV-DEPENDENCY eslint package is unused, in order to fix this issue, please REMOVE this package from the devDependencies list</pre><pre>? FIX? (Y/n)</pre><p>And once the developer confirms:</p><pre>info ‘eslint’ was REMOVED successfully from devDependencies list</pre><pre>info depsCheck SUCCESS</pre><p>As if this isn’t enough, our tool will go the extra mile and advise that you install the dependencies once again, since it’s modified some package.json files… Talk about max Developer Experience :)</p><p>Describing this tool in its fullest details deserves a post of its own, but at high-level, this tool scans all the packages in the monorepo using Lerna’s API, then for each package it checks whether there are unused dependencies (using <a href="https://github.com/depcheck/depcheck">depcheck</a>) and aggregates the issues found. If it can’t find any usages for a certain dependency, it will alert and give some fixing options to the developer to choose from. Not too complicated and totally worth the effort!</p><h3>Running them tools</h3><p>One of the main considerations for introducing such automated tools is where and when to run them. Some tools, like ESLint, can run as part of <a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">Git hooks</a>, probably before the commit is made (“pre-commit”), using tools like <a href="https://typicode.github.io/husky/#/">Husky</a> to manage it.</p><p>Some may run on the build pipeline, while others are preferred to run manually on demand. Sometimes they need to run on both. How should you decide which is suitable?</p><h3>Avoid killing dev velocity</h3><p>As with any process that is introduced to the development workflow, these tools also have the potential to hurt the development velocity and experience. <br>This can manifest itself in 2 main ways:</p><ol><li>Developers are slowed down by the local env process, like running all the tests on a pre-commit hook</li><li>CI processes may slow down due to running multiple enforcement processes as part of the pipeline, and so slowing down the feedback and deployments</li></ol><p>The idea is to make sure that <strong>what</strong> needs to run, runs only <strong>when</strong> it is needed.</p><p>Some tools, by nature, will “tell” you where they should run, like the tool for making sure you comply with the commit message, which tells you that it needs to run before the commit is executed.</p><p>Our package dependency check tool should run before the Git push is done, since its scope is multiple changes done in potentially multiple commits.</p><p>But what about running unit tests? Should they run before the commit as well?</p><p>This is a good example of where you need to make some adjustments, in order to not harm the dev velocity, but still maintain good quality. <br>A good balance might be — on pre-commit we only run the tests for the <strong>changed</strong> files, when this commit is pushed to the remote SCM we’d like a Git action to run the entire test suite. Minimum “noise” for the developer, while maintaining full protection over our code quality .</p><h3>Deciding how your tools should act</h3><p>Another consideration you should take is how you would like your tools to act.</p><p>In the matter of a redundant dependency, you would like to stop everything and require that the developer fix that. But in other cases, you might want to configure your enforcement rule to only warn (like, “warn me if my methods do not return anything”), but be careful — when you decide on a “warning”, it’s like saying “Good to know, but I don’t mind it”.</p><h3>Wrapping up</h3><p>Defining your coding standards well is an important step towards maintaining code quality and making your software reliable. However, the immediate next steps should be enforcing them with the most suitable automation tools and considerations. Remember — you cannot enforce what you cannot automate.</p><p>Sometimes you will not find the right tool for what you wish to achieve. Don’t hesitate to create your own — this is what mankind has done since the dawn of time :)</p><p>After you pick your tools wisely, you need to take into consideration how these tools will affect the overall development experience of your organization. Where and when they should operate are equally important. A tool that damages the dev experience, does more harm than good.</p><p>And in the end, choose how your tools should act.</p><p>You will then start to see the fruits of your efforts — your code becomes more and more aligned in standards and format, while maintaining it becomes easier and, dare I say, enjoyable :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671472193d85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/duda/automating-your-code-quality-considerations-and-innovation-671472193d85">Automating Your Code Quality — Considerations and Innovation</a> was originally published in <a href="https://medium.com/duda">Duda</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving to dev.to]]></title>
            <link>https://mattibz.medium.com/moving-to-dev-to-693d5442ad24?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/693d5442ad24</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 16:19:24 GMT</pubDate>
            <atom:updated>2021-01-12T14:32:50.139Z</atom:updated>
            <content:encoded><![CDATA[<h3>Taking my dev writing activity to dev.to</h3><p>Hi all, how is it going?</p><p>Well, I’ve decided to take my <strong>dev</strong> writing activity to dev.to for now, so if you want to keep tapping to any dev related posts I write be sure to check (and subscribe to):</p><p><a href="https://dev.to/mbarzeev">Matti Bar-Zeev - DEV Profile</a></p><p>Take care and see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=693d5442ad24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everybody’s free (to write code)]]></title>
            <link>https://mattibz.medium.com/everybodys-free-to-write-code-79e43cd9a148?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e43cd9a148</guid>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[parody]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 13:20:10 GMT</pubDate>
            <atom:updated>2020-07-06T13:20:10.733Z</atom:updated>
            <content:encoded><![CDATA[<p>A coder’s take on Baz Luhrmann’s “Everybody’s free (to wear sunscreen)”</p><p>Ladies and gentlemen of the abstract class<br>Write tests<br>If I could offer you only one tip for the future, testing would be it<br>A long-term benefits of testing have been proved by scientists<br>Whereas the rest of my advice has no basis more reliable<br>Than my own meandering experience, I will dispense this advice now</p><p>Enjoy the power and beauty of your product, oh, never mind<br>You will not understand the power and beauty of your product<br>Until you moved on, but trust me, in 3 years, you’ll look back<br>At releases you’ve made and recall in a way you can’t grasp now<br>How much possibility lay before you and how fabulously you really coded<br>You are not as junior as you imagine</p><p>Don’t optimize for the future<br>Or optimize, but know that pre-optimization is as effective as trying to solve an algebra equation by chewing Bubble gum<br>The real troubles in your code are apt to be things that never crossed your worried mind<br>The kind that blindsides you at 4 p.m. On some idle Tuesday<br>Do one merge every day that scares you<br>Saying, don’t be reckless with other people’s PR<br>Don’t put up with people who are reckless with yours</p><p>Code review</p><p>Don’t waste your time on estimations<br>Sometimes you’re ahead, sometimes you’re behind<br>The race is long and in the end, it’s only with yourself<br>Remember approved PRs you receive, forget the rejects, if you succeed in doing this, tell me how<br>Keep your completed side projects, throw away the uncompleted ones</p><p>Stretch</p><p>Don’t feel guilty if you don’t know what you want to do with your career.<br>The most interesting programmers I know didn’t know at 22 what they wanted to do with their career<br>Some of the most interesting 40-year-olds I know still don’t<br>Get plenty of sunlight<br>Be kind to your fingers<br>You’ll miss them when they’re gone</p><p>Maybe you’ll commit, maybe you won’t<br>Maybe you’ll merge, maybe you won’t</p><p>Maybe you’ll get fired at 40, maybe you’ll dance the ‘Funky Chicken’<br>On your company’s exit<br>Whatever you do, don’t congratulate yourself too much<br>Or berate yourself either<br>Your choices are half chance, so are everybody else’s</p><p>Enjoy your coding skills, use them every way you can<br>Don’t be afraid of it or what other people think of it<br>It’s one of the greatest instruments you’ll ever own<br>Debug, even if you have nowhere to do it but your own living room<br>Read the manual even if you don’t follow them<br>Do not read financial magazines, they will only make you feel spent</p><p>Get to know your keyboard shortcuts, you never know when they’ll be gone for good<br>Be nice to your colleagues, they’re your best link to your PR<br>And the people most likely to stick with you when it breaks production<br>Understand that colleagues come and go<br>But a precious few, who should hold on</p><p>Accept certain inalienable truths<br>Performance will decline, managers will demand, you too, will get burnt out<br>And when you do, you’ll fantasize that when you started<br>Performance was great, managers were aspiring<br>And juniors respected their seniors<br>Respect your seniors</p><p>Be careful whose advice you buy but be patient with those who supply it<br>Advice is a form of nostalgia, dispensing it is a way of fishing the past<br>From the disposal, wiping it off, painting over the ugly parts<br>And recycling it for more than it’s worth</p><p>But trust me on the testing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e43cd9a148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapping your npm scripts with npmapper]]></title>
            <link>https://mattibz.medium.com/mapping-your-npm-scripts-with-npmapper-43c9c0b0cee0?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/43c9c0b0cee0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sat, 02 Nov 2019 09:03:00 GMT</pubDate>
            <atom:updated>2019-11-02T09:03:00.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKZfU_Q8B4tTDelM4KbL1g.png" /></figure><p>One of the cool features of npm is the ability to run procedures which can be defined under the project’s package.json file. <br>I’m pretty sure that if you are reading this post you also have a few npm scripts under your project’s package.json file and are wondering what “mapping” them means…</p><p>Large projects usually contain large number of npm scripts. You have a script for testing, for building, for linting, etc. Those scripts usually are the aggregation of a number of other building blocks, for example, a test script is made out of unit testing, e2e testing and other testing aspects which are composed together.</p><p>But while creating these “lego-bricks” and composing them together gives you great flexibility, it makes your package.json file very hard to understand and maintain. What calls what? what params are passed to a command? are there any duplications? <br>We need something to inspect our scripts and map them so it will be easy to read and understand them. At least I needed it…</p><p>So I have created <strong>npmapper</strong></p><p>npmapprer is an npm CLI tool which lets you map your npm scripts in a human-friendly way to get a good overview on what’s <em>really</em> going on in your package.json file. <br>Just run npx npmapperon your project and you will get a nice HTML report on your browser.<br>They say a picture is worth a thousand words so here is an image of an HTML report example of running npmapper on Vue.js package.json file, only for the test script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKZfU_Q8B4tTDelM4KbL1g.png" /><figcaption>vue.js test script mapped</figcaption></figure><p>You can see in the image above exactly what are the steps which run under the test script. You can drill into each and see its parameters or sometimes what delegation it does to another script (or in some projects even to another project’s package.json).</p><p>You can decide whether you want to map the entire scripts or just the one which interests you, or perhaps you’d like the outcome to be a JSON report instead of HTML one.</p><p>Wanna try it? simply run npx npmapperon your project containing a package.json file and the result will pop on your browser.<br>Wanna read more details? Here is the <a href="https://github.com/mbarzeev/npmapper">Github repo</a> and the <a href="https://www.npmjs.com/package/npmapper">NPM page</a> for the project.</p><p>And of course, I would love to hear any suggestion, comment of feedback you might have on the tool. Happy mapping :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43c9c0b0cee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’s Render Props in Practice]]></title>
            <link>https://medium.com/myheritage-engineering/reacts-render-props-in-practice-b3775fcbf3c3?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3775fcbf3c3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 11:51:51 GMT</pubDate>
            <atom:updated>2019-11-30T18:23:21.400Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking render props from theory into practice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRjo7nCkUwCaxADPgLVhmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/_4815u_ACqQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">José Alejandro Cuffia</a> on <a href="https://unsplash.com/search/photos/ui-components?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are a front-end developer using ReactJS, you’ve probably caught a lot of buzz about <strong>render props</strong> and how they are supposed to be this great solution for situations where your components become too complex to work with, but like me, never have realized how it comes to play in real life.</p><p>In the following story I will walk you through the phases of understanding how the need for render props arises, and when it does, how to make them work for you.</p><h3>Prologue</h3><p>ReactJS is all about components, and R&amp;D organizations which adopt ReactJS as their client side technology very quickly find themselves developing their own components library for common usage bearing many custom-made components.</p><p>Such was the <strong>Pager</strong> component which we found ourselves discussing one fine afternoon in a meeting. A component containing Prev/Next arrow buttons which shifted the current page cursor and dispatched a “change” event to notify its surrounding components, but alas, now a new functionality and appearance requirements raised questions about the nature of this component.<br>The new version of the <strong>Pager</strong> component should include <em>quick-paging</em> buttons which allow you to jump to a certain page within a buffer of <em>n</em> pages, while still maintaining the old arrow buttons’ functionality.</p><p>Check out the images below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*g2dqO6DLkdufGFGQbVIBJA.png" /><figcaption>The existing Pager component</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*U3QWkS_ZOxrTTQj7HI52VA.png" /><figcaption>The new enhanced Pager component</figcaption></figure><p>How would you approach it?</p><p>One of the suggestions was to add a <strong>variant</strong> to the component (a “prop” to the rest of the React world), which will determine the appearance and functionality we desire out of the existing component, while the other suggestion was to build a new component, since the implementation of the new requirements within the existing Pager component would make it a nightmare to maintain, and bug-prone due to high complexity.</p><h3>The Gospel</h3><p><a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a> is one of my favorite React mavens. His ReactJS courses are very popular and offer a smooth yet comprehensive introduction to the React world.</p><p>A recent talk he gave in “React Rally 2018” was published and I took the 25 minutes to sit and watch it. This talk was called “Simply React”, and delivered content that could not be far from it.</p><p>Briefly put, he told the story of a poor React component developer who needed to keep extending her component’s functionality and appearance to a complete complexity and props mess, with the amazing twist at the end (spoiler alert!) — all the live demos for each enhancement presented were based on a single, 37 lines of code, component (the link to the presentation can be found at the bottom of this story). Wow!</p><h3>Initial Thoughts</h3><p>This is exactly what we needed! A single, simple to maintain component that could enable us to easily introduce new functionality and appearances to it. A component that can support both “this and that” without bloating its props. Can we convert the Pager component into a single base-component that can be extended and composed to achieve our goals?</p><h3>Getting to Work</h3><p>I assume that most of you reading the piece know how to implement a component which renders and acts differently according to a prop or multiple props, so I am not going to show examples of that, but rather, jump straight to the road which led me to the solution’s implementation.</p><blockquote>Before we start, <em>I’ll preface this by saying that </em>the focus of the following code examples is on the core concepts brought in this story. You won’t see any fancy style references and some functionalities/validations will only be hinted in the code.</blockquote><h4>The Naive Start</h4><p>You first start with the naive implementation of the Pager component which will receive a <em>pagesCount</em>, a <em>cursor</em>, prev/next button labels, and an <em>onPageChange</em> callback that will receive the current cursor as an argument. When we reach either the low or the high page limit the “prev” and “next” buttons become disabled accordingly. Let’s see how the component looks:</p><p>(By the way, declaring the state as I did is made possible with <a href="https://babeljs.io/docs/en/babel-plugin-proposal-class-properties">this babel plugin</a>)</p><h4>pager-naive.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/286761f9d0b5f963f240550fb5326c13/href">https://medium.com/media/286761f9d0b5f963f240550fb5326c13/href</a></iframe><p>In order to use it we will do the following:</p><h4>pager-naive-usage.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08404d488a07cbcef605bbb7d5549fcf/href">https://medium.com/media/08404d488a07cbcef605bbb7d5549fcf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*g2dqO6DLkdufGFGQbVIBJA.png" /><figcaption>Naive Pager</figcaption></figure><p>Now we’ve got a component which does what we want, but that’s about it and nothing more. The only way to alter its appearance without touching its core code is by changing the text which appears on the arrow buttons. We can’t even change the “pipe” separator if we want to. We need more.</p><h4>The “Compound Components” Approach</h4><p>We’ve gotten the basics going, but we would like to give more freedom to the look and layout of the component (e.g., have the prev and next buttons be actual buttons, or maybe change the separator, while keeping the same layout and logic). The mere button text props from the Naive Pager component will not be enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*YD-YVacO-8myqTUT4QI2YQ.png" /><figcaption>Example</figcaption></figure><p>This is where “Compound Components” comes in handy, basically declaring placeholders for the next/prev buttons which encapsulate the interaction logic of the Pager component. These are “inner” components inside our Pager component which we can later use when composing our final presentation.</p><p>Our compound components are named “Prev” and “Next” and both can get props of their own and render their children accordingly. Their children are what we would like to appear instead of just hard-coded text.</p><p>The way the compound component interacts with the “parent” component props is via the approved <a href="https://reactjs.org/docs/context.html">React Context API</a>. This way we are able to provide nested DOM structure as our Next/Prev children which can still access the “parent” component’s state and props. In other words, the component’s context wraps its children’s rendering and gives them access to the <em>cursor </em>and <em>pagesCount</em> props plus the <em>changePage</em> method, all declared and managed in the “parent” component.</p><p>Notice that in this example I’m rendering “N/A” when the cursor reaches max or min, but that is just to emphasize that the Next and Prev compound components can act according to the cursor position. Let’s see how the component looks:</p><h4>pager-compound.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f52b80eaaab8d82bde4a98b48043e0a6/href">https://medium.com/media/f52b80eaaab8d82bde4a98b48043e0a6/href</a></iframe><p>In order to use it we will do the following:</p><h4>pager-compound-usage.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d72c2685ff1dbc427a25e0f1e13ea49c/href">https://medium.com/media/d72c2685ff1dbc427a25e0f1e13ea49c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*YD-YVacO-8myqTUT4QI2YQ.png" /><figcaption>Compound component Pager</figcaption></figure><p>Now we have more control over the component’s appearance — we changed the Prev/Next into buttons and the separator from a pipe to a hyphen. We can even change the order and layout of these buttons using plain JSX and CSS while not risking the component’s functionality. Brilliant.</p><p>… but still not enough.</p><h4>Render-Props FTW</h4><p>We cannot settle with having only compound components, because we need to actually change the building blocks which make the component. In addition to the arrows we need “page-buttons” in the middle, for quick paging.<br> <br>Now we’re ditching the compound components and we’re going for <strong>render props</strong>.</p><blockquote>A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.</blockquote><blockquote>(ReactJS docs)</blockquote><p>In short, render props hand off the composition responsibility to the one using the component, which means that our basic Pager component should expose its API (state and callbacks) to be consumed by other composed components that are more focused on the desired appearance and functionality.</p><p>Our core functionality stays the same (pages, cursor, and event), but now there is a different appearance and interaction with the component which wraps the basic functionality. First, let’s see our basic Pager component and understand what’s going on there:</p><h4>pager-basic.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86541793b864a63687cf7cfa59627438/href">https://medium.com/media/86541793b864a63687cf7cfa59627438/href</a></iframe><p>The interesting part in the basic component above is the render method. We see that we’re returning the invoke result of the component’s children, so we understand that the children of the PagerBasic should actually be a function, and this function receives 5 arguments — the <em>cursor</em>, the <em>pagesCount</em>, callbacks for prev/next, and <em>changePage</em>. You can see that the changePage implementation stays the same as within the previous component examples above.</p><p>Now that we have this basic component, how do we proceed? Let’s first attempt to implement our simple prev/next component using the PagerBasic component.</p><h4>prev-next-pager-usage.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8f3a447f185c889458d97649844ff3/href">https://medium.com/media/ba8f3a447f185c889458d97649844ff3/href</a></iframe><p>In the example above we’re declaring a functional component called PrevNextPager that uses the PagerBasic component and supplies the render function (i.e., the render props) to it as children.</p><p>Inside the render function we construct how we would like our component to look, relying on the arguments the function receives (remember the PagerBasic render method?). The state and logic of the component are kept intact within the PagerBasic component. In the PrevNextPager we simply supply the means to display and interact with it.</p><p>As you can see, using it is very simple. Give the component the props it requires and you have it! Now you can decide whether this should be a component declared in a separate file, or in the file using it, or even inline the JSX, it’s your call according to how you see the composed component usage in the future. Let it sink for a sec… pretty neat, right?</p><p>It’s time to deal with the more complex component. We start again by composing our basic component, but now we inject the page navigation part (the page navigation can even be a component on its own, but in order to keep things clearer I’ve implemented it inline). For this component we need to add an extra prop to support a <em>buffer count</em> which determines how many pages will be displayed between the arrows (we don’t have to, but why the hell not). We’ll add this prop to our new component.</p><h4>quick-pager-usage.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e66035f577faf7c2e52aab5c1e8b56/href">https://medium.com/media/c0e66035f577faf7c2e52aab5c1e8b56/href</a></iframe><p>This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*U3QWkS_ZOxrTTQj7HI52VA.png" /></figure><p>Don’t be intimidated by the QuickPager render props implementation. It simply takes the buffer prop and creates those page buttons while assigning them the page index they represent. A click on each will call the changePage method (which is passed as an argument) with the desired page index. From there on, it’s all the PagerBasic’s job to take care of. I even marked the selected page with a corresponding <em>className</em> just to show that you can manage this selection outside the BasicPager. The BasicPager tells you which is the current selected page index. It’s your responsibility to do with the data as you wish.</p><p>It is also important to notice how we only added what’s needed where it is needed, i.e., the buffer prop. Other components relying on our BasicPager will not be affected by it. This, in turn, also helps keep our new component easy to maintain.</p><h4>Conclusion</h4><p>This is some powerful stuff, right? But you know what they say — with great power comes great responsibility, so I won’t advise you to go and change all your components to support render props. Having said that, I’m sure you can think of several components on your repository which can benefit greatly from this approach.</p><p>I’m happy to hear your thoughts on this story, so feel free to leave them here. You can also find me on Twitter <a href="https://twitter.com/mattibarzeev">@mattibarzeev</a>.</p><p>Happy coding ☺</p><h4>Resources</h4><p><a href="https://www.youtube.com/watch?v=AiJ8tRRH0f8">Simply React — A presentation by Kent C. Dodds</a><br><a href="https://egghead.io/courses/advanced-react-component-patterns">Advanced React Component Patterns course on egghead.io</a><br><a href="https://reactjs.org/docs/render-props.html">Render Props on ReactJS docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3775fcbf3c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/myheritage-engineering/reacts-render-props-in-practice-b3775fcbf3c3">React’s Render Props in Practice</a> was originally published in <a href="https://medium.com/myheritage-engineering">MyHeritage Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Reviews Code of Conduct]]></title>
            <link>https://medium.com/front-end-weekly/code-reviews-code-of-conduct-6c78a026ed35?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c78a026ed35</guid>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 07:05:19 GMT</pubDate>
            <atom:updated>2018-08-12T06:28:00.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuUGVTsLFZ-eKARHbOb66Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/2FPjlAyMQTA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Schnobrich</a> on <a href="https://unsplash.com/search/photos/laptop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>My guidelines for a professional and sincere code review</h4><h4>Intro</h4><p>This post is not about the many benefits of practicing code reviews within a development organization. I found that many articles deal with these benefits but tend to neglect the way code reviews should be conducted.<br>To be honest, I’m still learning how to give and receive code reviews myself. It is an on going process for me, but I managed to gather some rules along the way to form a basic code of conduct that I try (yes, try. I don’t always succeed) to follow.</p><p>In this post I would like to share these with you — <br>Below there are 7 guidelines, 6 of which end with a simple question that sums it up. I call it The “The question I need to ask myself before commenting on a code review”, or The “pre-commenting question”.</p><h4>I should stop trying to make the reviewed code look as if I wrote it</h4><p>Nobody can write code the same way I do , nor should they. We all should follow the same standards we agreed upon, but it will never be the same. Need and example? how about <a href="https://medium.com/front-end-hacking/naming-matters-7c32ff5c1ed4">naming stuff</a>?<br>One of my biggest mistakes was trying to make the code I’m reviewing be as if it was written by me. You know what I mean, right? I’m talking about commenting over whether to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary</a> logical statement or not in a certain spot, or assigning an expression to a variable instead of using it in its raw form later on.<br>If I have a strong reasoning why something should be a certain way then yeah, I should comment about it, but that’s not always the case. The pre-commenting question should be:</p><blockquote>Does the comment I’m about to write has a strong reasoning behind it or is it a matter of personal preferences?</blockquote><h4>Avoid being Holier Than Thou</h4><p>I had to accept, as a rule of thumb, the fact that there is always something to do in order to make the code better, for as we know — The <strong>best</strong> code is the code not written. Writing code is balancing between efficiency, quality and maintainability, and each of us developers have a slightly different set of priority weights for these aspects.<br>The problem starts to rise when we review code. I’ve noticed that when I review code my own priorities tends to change. Suddenly issues, which I let fly under the radar when I wrote some code, seriously disturb me now — when someone else did the same.</p><blockquote><strong>True story</strong>: I once copy/pasted some code and got a code-review comment on the content from the developer who authored the source.</blockquote><p>In this case there are 2 available options — either I comment about it and fix every place I did the same or suggest modifying the code very nicely (and perhaps admitting my weakness as well). Preaching what you don’t practice really sucks. The pre-commenting question should be:</p><blockquote>Do I deserve such a comment myself?</blockquote><h4>Be focused on the reviewed code’s objective</h4><p>Code has context.<br>While we review code modification we try to look at the modified bits but you got to have the context to see the broader picture. The thing is that sometimes I look at the contextual code and see some wrongs. I see that the code is written with bugs or in bad need of a refactor, and perhaps it does, but that’s when I need to remind myself to focus on the objective of the current modifications and review its related code. If I think that there is a need to refactor or change something outside that scope, it is better to take it offline the code review and prevent the noise. The pre-commenting question should be:</p><blockquote>Does my comment relate to the modified code and its objectives?</blockquote><h4>Be suggestive, not decisive</h4><p>Even though we’re dealing with software development, which is supposed to be a form of scientific implementation, in many cases choosing the right direction to go is not obvious and there are grey areas. Sometimes the direction we choose is very much dependent in the context the code runs in. Once I understood that there is more than a single way on doing stuff my comments begun to be more suggestive, e.g. “<em>Please consider replacing…</em>” or “<em>It might be a good idea to…</em>” instead of “Replace this” or “Do that”. Receiving such a comment and agreeing with is also much easier on one’s ego. <br>If I do find something that makes me go “<em>Why the hell did he do that?!</em>” I stop to realize that there is a slight chance that it was done with a good reason behind it, and so instead of “<em>Why the hell did you do that?!</em>” I might ask for the reasons, e.g. “<em>I think the implementation is wrong due to… , what was the reason behind doing this?</em>”. The pre-commenting question should be:</p><blockquote>Might there be a reason the author chose this implementation?</blockquote><h4>Use references when needed</h4><p>Sometimes I sense that a certain comment might be a little controversial , or maybe realize the comment relates to some newly discovered facts not commonly known— In these cases I find it useful to add a link to an article or Stack Overflow thread which might shed some light on what I’m talking about. I’m not saying your comments should drown in links, but if you know of an elaborated explanation that might help the author get you, why not include it? It also shows that you took the time and effort to be clear.<br>The pre-commenting question should be:</p><blockquote>Would it help the author understand if I add an additional reference?</blockquote><h4>Give positive feedback when deserved</h4><p>Everybody likes to get a good feedback on their work, but “<em>Wow! that’s an amazing change!</em>” over changing <strong>var</strong> to <strong>const</strong> is not what I would call “giving a positive feedback” on a code review. <br>I found that when the author makes a modification that was not required for the code to work (like refactoring, cleaning code, re-naming and the list goes on) positive feedback spontaneously comes out. Forcing it, just for the sake of having it, is something I really try to avoid. The pre-commenting question should be:</p><blockquote>Does code change really deserve a positive feedback?</blockquote><h4>If there’s nothing to say — just say it</h4><p>Sometimes the modified code leaves me speechless, in a good way. In this case I try to practice leaving a single comment saying something like “<em>Looks good to me, I have nothing to comment about :)”. </em>Why? cause not leaving a single comment might be taken as if I didn’t review the code or didn’t pay attention to it. More over, leaving a positive comment like this (when deserved) is always a nice thing to receive. No pre-commenting question here ;)</p><h4>Conclusion</h4><p>Code reviews are another interface among developers and as such I believe it should be treated with the same importance over how it is conducted.<br>I’m pretty sure you have your own guidelines or other points of view over what I’ve written — be sure to share them on the comments :)</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c78a026ed35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/code-reviews-code-of-conduct-6c78a026ed35">Code Reviews Code of Conduct</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Grunt to NPM — part 2]]></title>
            <link>https://medium.com/capriza-engineering/from-grunt-to-npm-part-2-6ca18fc98300?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ca18fc98300</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sun, 01 Oct 2017 05:37:59 GMT</pubDate>
            <atom:updated>2017-10-01T07:59:27.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0k_UNUE0aKZUZbvA-P7GUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1CrN-IbvtH0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gareth Davies</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Diving into the migration details</h4><p>In <a href="https://medium.com/capriza-engineering/from-grunt-to-npm-part-1-f97f43d1d594">Part 1 of this article</a> we’ve talked about the motivations and challenges involved in migrating Capriza’s Designer build from Grunt to NPM.<br>In this part we will dive a little bit into the details of implementation to get a sense on what it actually means to migrate the build process of a matured front-end process to NPM.<br>All ready? here we go…</p><blockquote>Before we start, it is important to note that this article assumes basic knowledge of how NPM handles scripts. If you feel you need to refresh on that, this following <a href="https://docs.npmjs.com/misc/scripts">NPM documentation</a> is a good place to start.</blockquote><h3>Some Core NPM Scripts Concepts</h3><p>Like in any tool you’re using, NPM also has conventions and concepts to help us achieve our goal. Here are the ones of our main interest:</p><ul><li><strong>Life-cycle hooks</strong> — For each NPM script you can hook a “pre” and “post” script simply by adding a prefix with the same name; say you have a script called “create”, a script names “<strong>pre</strong>create” will run automatically before it. Read more about it <a href="http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html">here</a>.</li><li><strong>Script segmentation </strong>— Though not a must, you can divide your scripts into segments using a colon (“:”) within the script’s name. Aside from keeping things in order it can become useful when you want to run all segments with tools like <a href="https://www.npmjs.com/package/npm-run-all">npm-run-all</a>.</li><li><strong>Piping </strong>— We can stream data from a certain script to the script following it using Bash’s pipe operator (“|”). As we shall later see this comes very handy when deploying a version and triggering a Jenkins build which relies on it.</li></ul><h3>The Package.json File</h3><p>The place to put our scripts is in the project’s package.json file, under the “scripts” prop. Before you jump and write your first script here is a little tip -</p><blockquote>Not only true for NPM but goes for code as well - it is considered a good practice to break the scripts into units with a single responsibility and later combine and reuse them via the tools NPM provides us.</blockquote><p>With that in mind lets review what we’ve done.</p><h3>Running Unit Tests</h3><p>The first script we’re going to talk about is “test”. The “test” script is a built-in NPM script which typically has a placeholder made for it if you create the package.json using npm init.This is how it will be written:</p><p>&quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</p><p>To implement the test according to our needs we used the <a href="https://www.npmjs.com/package/karma">karma</a> node package. This is a good place to tell you that one of the cool things about NPM is that it knows where to look for the packages within the projects <em>node_modules</em> directory so it’s pretty straight forward with no long paths. Our test script looks like this:</p><pre>&quot;test&quot;: &quot;karma start&quot;</pre><p>NPM will take it from there, given that you have a <a href="http://karma-runner.github.io/1.0/config/configuration-file.html"><em>karma.conf.js</em></a> file on the project root directory, your tests will start running.<br>We also wanted to generate a coverage report and for that we’ve used Karma as well with an additionalset of parameters:</p><pre>&quot;coverage&quot;: &quot;karma start --single-run --reporters junit,coverage&quot;</pre><p>Here we’re running a single run that generates 2 types of reports: junit and coverage (both are Karma’s plugins).<br>All the parameters you see in the script above can be found under Karma’s docs. Nothing hiding in a 3rd party mediator. Since the “coverage” script is not a built-in NPM script, in order to trigger it you need to use the “run-script” or in short just “run”, like so:</p><pre>npm run coverage</pre><h3>Code Manipulations</h3><p>Usually you would like to concatenate the project code and maybe uglify it in order to prepare it for production. The Grunt plugin used for these purposes was <a href="https://github.com/capriza/grunt-usemin">grunt-usemin</a> which internally utilizes several node packages. <br>This process is made of two core phases — One is concatenating JS and CSS “blocks” from target HTML files while the other is generating new HTML files which have reference to these newly concatenated files.</p><p>This is all great but we wanted more control over the process. We found out that if we extract this process to a custom node script which uses <a href="https://www.npmjs.com/package/usemin">usemin</a> package (among others) we are not bound to support just “js” or “css” block types but rather have custom blocks like “remove” for blocks that shouldn’t be included on the final result.</p><p>Our first move was to create a <em>usemin-script.js</em> and start constructing what we exactly want this process to do. Within this script we concatenate the JS code, concatenate the CSS, <a href="https://github.com/jakubpawlowicz/clean-css">clean and minify</a> it and finally remove code we do not need in production, like <em>livereload</em> scripts.</p><p>But having a node script allowed us to do even more — we can actually control how each part of these manipulations works. For instance we can set exactly what kind for compression the <a href="https://github.com/mishoo/UglifyJS">UglifyJS</a> library will do (read more about <a href="https://davidwalsh.name/compress-uglify">the options here</a>) or how usemin.getHtml() method will generate our final HTML file (minified or not? remove empty attributes? remove comments?).</p><p>We were no longer chained into the configurations the Grunt plugin provided us. If we would like to remove one phase (like the uglification and we shall soon see why) or add another processing into it, it’s pretty straight forward.<br>Eventually, NPM script only calls our <em>usemin-script.js</em> node script with a parameter for the target HTML file path and takes it from there:</p><pre>&quot;usemin:designer&quot;: &quot;node build/scripts/usemin-script.js main.html&quot;</pre><blockquote>Something to note about uglification — As mentioned above, as part of the usemin package there is also an option to uglify the code (using UglifyJS). After several comparisons we’ve made we noticed that when using gZip compression, the difference between the uglified compressed code and the gZipped code does not justify the maintenance around source-mappings (for debugging usage), and since we don’t consider uglifying obfuscation a sort of security we chose to avoid uglification.</blockquote><h3>Pre-Compiling Templates</h3><p>As mentioned in <a href="https://medium.com/capriza-engineering/from-grunt-to-npm-part-1-f97f43d1d594">Part 1</a> of this article, Capriza’s Designer utilized Handlebars templates to render part of its DOM. <a href="http://handlebarsjs.com/precompilation.html">Handlebars documentation</a> is pretty straight forward, but the Grunt plugin adds some additional “features” over it, which can lead into misuse of Handlebars and add (even more) complexity to the configuration since the parameters names are not quite the same as with Handlebars. This is a classic case where a Grunt mediator obscures the vendor implementation from us, thus makes it very hard to maintain later on.</p><p>Moving to NPM scripts using the Handlebars pre-compiler package directly we turned something which looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06bda404059c96fd483a6df73b2d2524/href">https://medium.com/media/06bda404059c96fd483a6df73b2d2524/href</a></iframe><p>into this simple NPM script (excuse medium for wrapping it):</p><pre>&quot;templates:designer&quot;: &quot;handlebars templates --output templates/output/compiled-templates.js --namespace Handlebars.templates&quot;</pre><p>I will explain what it does though I think that it speaks for itself — take the template files under the “templates” directory, compile them with the “Handlebars.templates” namespace and dump the result into the compiled-templates.js files.</p><p>And while the rest of the work follows the same implementation concepts, there are two more scripts worth further elaboration:</p><h3>Amazon S3 deployment</h3><p>Capriza’s Designer versioned artifact can be deployed to Amazon’s S3 to later be fetched and used. In our day-to-day work we use this task to upload a new version so that our automation tests will run against a specific version for regressions. <br>As we’ve mentioned earlier, one of the great benefits NPM script gives you is the ability to also run NodeJS scripts, thus allowing a greater flexibility in what can be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/0*DF_IN31IMz-ltp7i.png" /><figcaption>Amazon S3</figcaption></figure><p>We have created a custom node script which utilizes the <a href="https://www.npmjs.com/package/s3"><strong>S3</strong> Node package</a>, and the <a href="https://www.npmjs.com/package/git-user"><strong>git-user</strong> package</a> to extract user data we need for deployment parameters (such as the unique version name we’re giving the newly deployed artifact) and deploy the artifact.<br>We also use the Progress package to display the upload progress and attach it to the progress event the S3 package has, just to be nicer to the ones using it :)</p><p>In the end, when we run npm run deploy our script builds the Designer artifact (on the “<strong>pre</strong>deploy” hook) and then runs the deploy node script which does the rest. Here is how it looks while uploading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*PImLZ-5ynuRJ18J3qYhlWw.png" /><figcaption>Uploading the Designer artifact to S3</figcaption></figure><h3>Triggering a Jenkins Job</h3><p>In general, we don’t just deploy the Designer artifact; we also trigger a <a href="https://jenkins.io/">Jenkins</a> job which runs our automation tests.<br>Capriza uses an in-house tool called “<strong>Watchdog</strong>” (which deserves a post of its own) to run the Designer’s automation tests. The process is comprised of building the Designer artifact, deploying it and then triggering a Jenkins job which runs the tests against the uploaded version.</p><p>As you can probably guess, this script is dependent on the “deploy” script — when it’s done, it takes the deployed version and passes it to the Jenkins job as a parameter. The Jenkins job triggering-script is also a NodeJS script which uses the<a href="https://www.npmjs.com/package/jenkins"> <strong>Jenkins</strong> node package</a>. God, you can find anything you can think of in NPM!.</p><p>But how do we pass the deployed version to the this script?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/0*fIjDX-ARejQ3Xsr4.jpg" /><figcaption>Jenkins</figcaption></figure><p>For this we use <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html">Bash’s piping feature</a> like so:<br>The deploy script writes the deployed version to process.stdout when the upload completes, e.g.: process.stdout.write(deployedVer). The jenkins-script listens to the stdin to get that info, like so:</p><pre>process.stdin.on(&#39;data&#39;, (data) =&gt; {</pre><pre>     deployedVersion = data;</pre><pre>});</pre><p>And the way we register it under package.json is like so (notice we’re using the pipe operator):</p><pre>&quot;watchdog&quot;: &quot;npm run deploy <strong>|</strong> node build/scripts/jenkins-script.js&quot;</pre><p>Pretty neat, right? When we run npm run watchdog we get it all “magically” done. Now you can see how all the building blocks come together. That’s some powerful stuff we’re enjoying right there.</p><h3>And so…</h3><p>Our journey to replace Grunt with NPM has completed. We’ve managed to migrate all our Grunt’s responsibilities to NPM, removing all of Grunts dependencies from our code and simplify the way we work and maintain our Designer product. <br>While this is not the last step in this path, taking it helped us to get more agile and flexible to changes and progress.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ca18fc98300" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capriza-engineering/from-grunt-to-npm-part-2-6ca18fc98300">From Grunt to NPM — part 2</a> was originally published in <a href="https://medium.com/capriza-engineering">Capriza Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Grunt to NPM — Part 1]]></title>
            <link>https://medium.com/capriza-engineering/from-grunt-to-npm-part-1-f97f43d1d594?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97f43d1d594</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[grunt]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sat, 26 Aug 2017 18:57:06 GMT</pubDate>
            <atom:updated>2017-08-27T07:13:03.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0k_UNUE0aKZUZbvA-P7GUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1CrN-IbvtH0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gareth Davies</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Background, Motivation and Prepping</h4><p>There is a lot of buzz around using NPM scripts as a task runner driving build processes, but most of the content out there speaks in <em>slogans</em> without really touching real project aspects and challenges, so we at Capriza decided to <strong>really</strong> dive into it and see if our Designer product’s front-end build process can benefit from it.<br>Here is what we’ve learned…</p><h3>Some Background</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*p0Kzh_2FjbGL5UN2qT_70A.png" /><figcaption>Capriza’s Designer</figcaption></figure><p><a href="https://www.capriza.com/product/simplify-transform/">Capriza’s <strong>Designer</strong></a> is the tool to use in order to create your own Zapp (Micro-App) by dragging &amp; dropping web components onto a mobile canvas while configuring the Zapp flows and the styling you desire.<br>The Designer is a Firefox add-on (a.k.a extension) which holds a web content and as such it goes through a standard build processes web front-end project go these days, and in our case, using <a href="https://gruntjs.com/">Grunt</a>.</p><h3>Hey, what’s wrong with Grunt?</h3><p>Why would you use tools like Grunt/<a href="https://gulpjs.com/">Gulp</a> and the likes to begin with?<br>Well, these tools provide a way to automate and break a build process into well defined units with distinct outcomes and later on combines them together to assemble final product artifacts. <br>It allows us to configure the process and control its flow, and though Grunt delivered what was expected of it, working with it over time became somewhat of a maintenance burden. Here are some of the reasons behind it:</p><ul><li>Tasks were very hard to maintain, even when extracted from the main Gruntfile. Configuring these tasks resulted in constructing weird looking JavaScript object literals which adhere to no common standard.</li><li>We felt that Grunt and the likes act as a <em>redundant</em> mediator between us and the node package (or CLI) actually doing the work. In some cases, the Grunt plugins provided APIs which were not directly supported by the node packages, thus inviting us to unknowingly break their conventions.</li><li>As part of its architecture, Grunt relies on <a href="https://gruntjs.com/getting-started#installing-grunt-and-gruntplugins">plugins</a>. These plugins are also installed via NPM and reside under the projects node_modules directory. We realized that for each task we wish our build to preform we need to install the Grunt plugin which internally depends on the actual node package that does the work, so for example, to precompile <a href="http://handlebarsjs.com/">handlebars templates</a> we need the handlebars node package and the Grunt plugin to enable it via Grunt. This quickly caused our node_modules directory to bloat and also prolonged our clean NPM install time.</li><li>We thrive to reduce the configurations involved in automatic process like builds and tests. Removing Grunt and its dependencies from the stack seems to be a good step in that direction.</li><li>Debugging Grunt is hard. Going from understanding what the Grunt plugin does into what the inner npm package does is tedious and sometimes can send you the wrong path.</li></ul><p>These are the main reasons behind our desire to find a better solution for our build process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/0*FsII6R2ViV7OZQzg.jpg" /></figure><h3>Why then NPM?</h3><p>There are quite a few option like Gulp and <a href="http://broccolijs.com/">Broccoli</a>, why then use NPM?<br>As far as we were concerned there were 2 main reasons why NPM scripts suited our needs best:</p><h4>Simplicity</h4><p>Using NPM scripts is simple and to the point. If you need to know what the script does you go to the node package documentation and there you have it. No need to read any Grunt plugin or any other 3rd party docs.</p><h4>Commonality</h4><p>Working on front-end project there is a great probability that NPM is already involved in the process, even if you’re not using it as your task runner tool.<br>So was it on our case. It is already there and does not require additional installation or configuration, so if we can use it for more purposes — why not?</p><h4>More Control. Less Errors.</h4><p>Invoking the node packages directly via CLI or creating your own scripts and triggering them gives you more control on what’s being done and avoids unexpected errors which might happen due to misalignment between the Grunt plugin and its corresponding Node package.</p><h4>Flexibility and Updates</h4><p>Using NPM means you have the ability to practically utilize every node package out there for your needs, which cannot be said about Grunt for Grunt needs a plugin wrapper over that node package — a plugin that might not exist yet. Moreover, in many cases it is hard to keep up to date with the latest node package versions since it’s Grunt wrapper we depend on does not support it yet.</p><h3>Prepping towards migration</h3><p>Grunt used to manage the entire Capriza’s Designer build process. The build was consisted out of several tasks. Each one of these is a candidate to be migrated to NPM and we shall later see the set of challenges some presented, but our first task was to understand what Grunt currently does for us.<br>Here are the main ones:</p><ul><li><strong>Code Concatenation</strong> — Reading the main HTML files and extracting the scripts tags blocks from them to produce a concatenated, sometimes minified, files. This process results in Prod-ready HTML and JS files.</li><li><strong>Pre-Compiling Templates</strong> —Capriza’s Designer utilize Handlebars templates and as part of the build these templates are being per-compiled to produce JS files which represent them for performance concerns.</li><li><strong>Compiling LESS</strong> — Capriza’s Designer uses LESS for better maintaining CSS. Our build compiles the LESS files into production-ready CSS files.</li><li><strong>Copying files</strong> — Any build process has it — moving files from one location to another to prepare a distribution directory ready to be deployed.</li><li><strong>Amazon S3 deployment </strong>— The Designer, like many other projects, is being deployed to <a href="https://aws.amazon.com/s3/">Amazon’s S3</a>. There is a Grunt task which was made of several sub-tasks to preform this rather complex deployment process.</li><li><strong>Triggering Jenkins job</strong> — As a part of the development cycle at Capriza, developers are often running an in-house tool called “<strong>Watchdog</strong>” for E2E testing (automation tests). This process can be triggered by Grunt on demand. Of course this task is dependent on a deployed version which we want our E2E test to work on.</li><li><strong>Unit Testing</strong> — Running unit-tests is a core aspect of Capriz’a Designer development process. We are using Karma as our runner and Grunt triggers it. When triggered these tests will run in the background while you code to make sure that no regression happens and TDD is made more smoothly.</li><li><strong>Watch </strong>— In order to speed-up development, files are being watched for changes in order to generate their updated compiled artifact or to run unit-tests in the background. This “Watch” process is initiated by Grunt.</li><li><strong>Dev Tools</strong> — Capriza also has a tool for making the developer day-to-day work easier. It consists of a simple server to serve artifact and several watch commands which monitor modification to the source code and generate new artifacts accordingly on the fly to provide immediate feedback (like compiling LESS). The tool utilizes Grunt tasks by calling them upon source code change.</li></ul><p>In this part we’ve seen what were the motivations behind migrating our Designer’s build process to NPM and the set of challenges ahead of us.</p><p><strong>Part 2</strong> of this article will send us diving into the details behind core tasks described above, leaving nothing behind for Grunt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97f43d1d594" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capriza-engineering/from-grunt-to-npm-part-1-f97f43d1d594">From Grunt to NPM — Part 1</a> was originally published in <a href="https://medium.com/capriza-engineering">Capriza Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Front-End]]></title>
            <link>https://medium.com/front-end-weekly/unit-testing-front-end-38b9bf1de079?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/38b9bf1de079</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Sat, 04 Feb 2017 20:25:52 GMT</pubDate>
            <atom:updated>2017-02-05T17:24:30.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dezeADDetLJ4lqkmqLun1A.jpeg" /></figure><h4>Chapter One, where we learn what should not be unit-tested in Front-End</h4><h4>Intro</h4><p>If you have been coding Front-End long enough you’ve probably came across this annoying statement—<em> “Front End cannot be unit tested”</em>. <br>This statement, to put mildly, is a complete and utter BS. The truth is Front-End can (and should be) unit-tested. The reason that developers avoid it by saying it cannot be tested is mainly due to the fact that what they think should be unit-tested is really hard to do, but the real problem here is not the unit test tools but rather <strong>what “they” think should be tested</strong>.<br>In this one I’ll share with you my thoughts on what type of tests should be avoided in Front-End unit tests and why, plus a suggestion or two on what you can do instead.</p><h4>Don’t Test Animations</h4><p>I witnessed cases where a developer wanted to test whether an animation happened or not, which translated into waiting the time the animation should take and then checking if the animated DOM element is at a certain position or a certain opacity. <br>Here we have 2 wrongs in a single test. First one is the <strong>test waits</strong>. It waits the animation duration before the assertion and in my book (and according to others as well) a test should not break the 250ms time limit, and if I’m waiting 500ms (or sometimes more) I am seriously slowing down the speed my tests suites run.<br>Second one is that tests check your code logic. <strong>Element positioning is not code “logic”</strong>. Generally when we want to animate stuff we define a certain CSS animation transition and then change the CSS class of a certain DOM element, letting the browser take over and do its stuff. So what I want to test is whether the CSS class has changed or not. I trust the browser does its stuff well.</p><blockquote>Test the logic behind CSS modifications instead of the end result of it.</blockquote><h4>Don’t Test 3rd Parties</h4><p>Code which you are not responsible of and have no means or willing to modify should not be tested as part of your source code tests. <br>Say you have a library which helps you parse strings. If you have a function which uses it, mock the 3rd party library and return a fake response from it. What the library does internally should not concern you for you are only interested on how your code acts upon different results from it. So… mock the results.<br>This also allows you to run your tests without depending on whether this 3rd party is there or not. The less your tests relies on the environment they run in the more deterministic they are.</p><blockquote>Mock 3rd parties and return fake results which support your test cases when you can</blockquote><h4>Don’t Test the Browser</h4><p>In continue to the idea above, there isn’t much sense in testing a Browser’s API. By that I mean, there is no real value in testing the document or window API much as there isn’t none in testing native browser’s API available when developing browser extensions. When testing you’re interested in the results of these APIs, so you might as well mock them.<br>Again, we’re assuming that the browser is fully covered by it’s own developers, which usually is the case ;)</p><blockquote>Rely as little as you can on the environment you’re running on when writing your tests. Use mocks for environment APIs</blockquote><h4>Don’t Test Integration</h4><p>That pretty much goes without saying, right?<br>If your are doing unit-tests you are testing the scope of a “class” or a “component”, and it alone. If you find yourself going outside that scope, in terms of not mocking dependent APIs but actually waiting for them to execute their real code, then you’re doing it wrong.<br>I’m always alerted when I see a Jasmine test which spies over a function and calls it through e.g. spy(myObj, ‘method’).and.callThrough();. You should ask “why do I need to call that function? can I mock it’s response?”. In many cases the answer is <strong>yes</strong>, which makes the test a lot simpler and less dependent on the application environment.</p><blockquote>Unit-tests are not integration tests. Make sure you stay in the scope of you tested code and mock the outer world as much as you can.<br>(but remember — too many mocks are a code smell which indicates a bad design)</blockquote><h4>Don’t Test Async Operations</h4><p>Async operations generally mean integration test, since you are stepping outside the “scope” you’re testing and wait for a response from another component in order to get back and continue. <br>A common mistake is to create a “server” mock and have it return a response when the Front-End requests it, so that we would be able to test how our code acts on that response.<br>Doing that means that (A) you rely on that server mock on your unit-tests and (B) that you are waiting for a response, which can be delayed and slow down your test. <br>When you find yourself in this spot, ask what exactly are you trying to test — is it the XHR or is it your class’s handling the response? The answer usually is the later and if you want to check how your code acts upon a response, simply mock the response by mocking the XHR. Nobody really cares about the server-communication on unit-test scope.</p><blockquote>Server mocks are rarely needed to unit-test Front-End code. Save testing time and complexity by mocking Async operations</blockquote><h4>Don’t Test the Pixel</h4><p>Front-End unit tests are not there to check if a pixel shifted 2 units to the left. If you think that unit-tests can save you from corrupting the UI your are sadly wrong. This is not what they are for. There are other tools which help testing the UI, but unit-tests are there to keep our code logic safe and working. If someone changed the rules of a certain CSS class it’s not the job of unit-tests to pick this up. Avoid testing positioning, opacity or any other appearance properties on your units.</p><blockquote>Unit tests check code logic, not UI appearance. Use the suitable tools which are meant for it instead.</blockquote><h4>In Conclusion</h4><p>I hope that my practices mentioned above gave you a little more confidence that Front-End can and should be unit-tested. As long as you know what’s important for you to test and from what you need to stay away, these tests will become part of you regular Front-End coding.</p><p>If you enjoyed reading this, please click the ♥ below. This will help sharing the story with others :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38b9bf1de079" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/unit-testing-front-end-38b9bf1de079">Unit Testing Front-End</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naming Matters]]></title>
            <link>https://medium.com/front-end-weekly/naming-matters-7c32ff5c1ed4?source=rss-ff40a255fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c32ff5c1ed4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Matti Bar-Zeev]]></dc:creator>
            <pubDate>Thu, 26 Jan 2017 20:16:24 GMT</pubDate>
            <atom:updated>2017-04-05T15:16:45.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8IXLOXQxdpUJJ4WFfqfQg.jpeg" /></figure><h4>Naming your code correctly can save you and your colleagues a lot of time. here’s how…</h4><p>Whether it is variables or functions, naming has a crucial part in debugging and understanding code, and since we spend more time reading code than writing it, it’s important that we pay attention to this (somewhat neglected) aspect of coding.<br>The value of correct code naming is so evident in every hour I spend reading code and in this post I would like to share with you my practices and code naming rules of thumb.</p><h3>Variables</h3><h4>Generally speaking…</h4><p>Everybody create variables, but very few take the time to really name them correctly. The reasons for it may vary but mostly it’s because we wanted to check something’s working really fast and left that “t” variable there to puzzle future maintainers (usually ourselves).</p><p>My rule of thumb<strong> </strong>on this matter is -</p><blockquote><strong>A variable name needs to indicate its meaning as precisely as it can</strong></blockquote><p>and that does not mean what type the variable is. I don’t care whether it’s a Number or a String. I do however care if it represents the amount of items or the user name.</p><p>You may think that the above is trivial but I bet you can find many places in the code you maintain where a variable was misleading and made you go astray logically.<br>You will read this variable name over and over for many times so you might as well set it to help you. If we dive a little deeper there are rules I follow which relate to the type of the variable:</p><h4>Booleans</h4><p>The rule here for me is quite simple and straight forward —</p><blockquote>Boolean variables represent a yes/no question. I will ask “Is this view in fast mode?” or “has this object got items?”</blockquote><p>And this will produce a straight forward variable names, such as “<strong><em>isInFastMode</em></strong>” in the view scope or “<strong><em>hasItems</em></strong>” in the object scope. I consider the alternative “fastMode” and “items” a bad practice and misleading. I rather have my conditionals read as close as can be to plain English, e.g. <strong><em>if(isInFastMode)</em></strong> than the developers crocked English syntax <strong><em>if(fastMode)</em></strong><em>.</em></p><h4>Collection vs. Single</h4><p>Sometimes you have a collection, say “items”, and inside this collection each object is a single “item”. If we take these as they are and use them for variable names we will be facing a problem. The problem is<strong> </strong>2 different variables which can be differentiated only by a single little “s” at the end of their name. That, my friends, is the main cause behind many debugging hours which end up with “damn! there’s an ‘s there!”.<br>To avoid it I set a rule —</p><blockquote>When dealing with collections I use the plural form, e.g. “<strong>items</strong>”, but when dealing with a single item I name it “<strong>singleItem</strong>”.</blockquote><p>This really helps me telling right away which is which. Again, it might sound petty to you but aside from optimizing your code performance you should also take care of optimizing your code readability speed, and this does just that.</p><h3>Functions</h3><h4>Generally speaking…</h4><p>Functions are a key aspect of the language I’m practicing these days, that is JavaScript, and this requires me to treat their name with extra respect. <br>Same as with variables, function names should state what the function does, and so my first rule is —</p><blockquote>If it is hard to find a name which defines what your function does it usually means that your function does too much and needs to be broken into smaller functions (extract function).</blockquote><h4>This and that</h4><p>Sometimes the name you instinctively give a function may alert you that your design is a bit “smelly”.</p><blockquote>If your function name has “and” in it, e.g. “seekAndDistroy()”, in most cases it means that this function is doing 2 things</blockquote><p>And therefore should be extracted into 2 different functions, e.g. <strong>seek()</strong> and <strong>destroy() </strong>and call them one after the other or even better, obtain the flexibility to call one of them without the other.</p><h4>Getters Functions</h4><p>Unlike the a getter on an JavaScript Object, this one refers to functions which return a value according to an argument or two. Their name should obviously state their purpose, so the verb “get” should reside there, e.g. “<strong>get</strong>ItemById(id)”.</p><blockquote>A function which has a name with “get” in it should always return some kind of calculated value.</blockquote><p>I try to avoid alternative verbs like “fetch”, “retrieve”, “obtain” etc. when there is no need for them, just to keep my code consistent and the life of the one reading it easier.</p><h3>Files</h3><h4>Generally speaking…</h4><p>File names help a lot to indicate what is defined within that file. Given that you are not defining multiple module inside a single file, knowing a file name can pretty much give you a good idea about its content.<br>So there is not much about it —</p><blockquote>If the file defines a view I will indicate it in its name, e.g. “items-list-view.js”</blockquote><p>Some may not agree with this approach, but I found it very comfortable for later searches.</p><h4>Test Files</h4><p>Although test files are not bound to the code they test, I try to align them both by their names. So if for example I have an “items-list-view.js” files which defines a… (well you can tell what it defines, right ;) then the corresponding test file will be “items-list-view-spec.js”. This creates pairs of files, one is the source and the other is the test. The result is a fast way to know if a certain module has tests or not.</p><h3>conclusion</h3><p>There are more examples that I’ve probably forgot, but the point I want to make is that paying attention to how we name the key aspects of our code is an investment worth our while. Giving suitable names which clearly define the purpose of a variable, a function or what-have-you can save a lot of time later on, whether it’s debugging it or maintaining it.</p><p>If you enjoyed reading this, please click the ♥ below. This will help sharing the story with others :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c32ff5c1ed4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/naming-matters-7c32ff5c1ed4">Naming Matters</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>