<?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 Omar De Los Santos on Medium]]></title>
        <description><![CDATA[Stories by Omar De Los Santos on Medium]]></description>
        <link>https://medium.com/@omarnyte?source=rss-1649520c5307------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oQW83e6TOMvvulxAC5laXw.jpeg</url>
            <title>Stories by Omar De Los Santos on Medium</title>
            <link>https://medium.com/@omarnyte?source=rss-1649520c5307------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:21:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omarnyte/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[Declarative Testing in React]]></title>
            <link>https://medium.com/better-programming/declarative-testing-in-react-4730b16e71ec?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/4730b16e71ec</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 00:32:05 GMT</pubDate>
            <atom:updated>2020-01-11T01:20:06.322Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to write refactor-proof tests for the future</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3w7ha4K0Sg3wxp4GWgtpkQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jdent?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Dent</a> on <a href="https://unsplash.com/s/photos/testing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Have you ever started refactoring your React code, and you knew exactly which tests would break even before those tests ran?</p><p>If so, it’s very likely that you’ve been writing your tests imperatively. By writing your tests declaratively instead, you improve your tests by ensuring that they only fail when behavior — not a particular implementation — changes.</p><p>In short, the imperative programming paradigm comes down to specifying <em>how</em> you want to accomplish something while the declarative programming paradigm comes down to specifying <em>what</em> you want to accomplish.</p><p>In the real world, this would be the difference between giving your taxi driver turn-by-turn directions as opposed to just giving them the address where you intend to go.</p><p>Neither of these paradigms is inherently better or more correct, and they both come with their own advantages and disadvantages.</p><p>When working with React, however, a number of issues arise when writing imperative code and especially when writing imperative tests. After all, React is a declarative framework. The <a href="https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom">React documentation</a> explains that:</p><blockquote>This approach [that reconciles the virtual DOM with the real DOM] enables the <strong>declarative</strong> API of React: You tell React <strong>what</strong> state you want the UI to be in, and it makes sure the DOM matches that state.</blockquote><blockquote>This abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app.</blockquote><p>One major issue with writing imperative tests for a declarative framework becomes painfully obvious when attempting to refactor your code. <a href="https://www.refactoring.com/">By definition</a>, refactoring involves changing <em>how</em> your code is written but not <em>what</em> the behavior is.</p><p>But imperative tests assert against <em>how</em> the code has been written instead of <em>what</em> the behavior is. Often, this means that your tests assert against props being passed to specific components or ensure that a component contains a given state.</p><p>They might even invoke the instance methods of your class components. Combining these antithetical paradigms will necessarily result in failing tests whenever you refactor.</p><p>While it may not seem like a huge deal when you know to anticipate failures, those sorts of tests can really slow you and your team down. Today, you might know exactly which tests will break and how to fix them, but you’ll likely lose that intuition as the app grows and as different members of your team work on the app.</p><p>Developers unfamiliar with your tests would never know to anticipate these failures, so every refactor would involve spending valuable time altering or deleting failing tests. At their worst extreme, imperative tests could discourage refactoring entirely.</p><p>If your tests cannot provide you with the confidence that you aren’t breaking anything, you’ll be refactoring and adding new features blindly as if you had no tests.</p><p>Following the steps below won’t automatically make your tests fool-proof. They still leave plenty of room for writing brittle or incomprehensible tests.</p><p>But these steps will guide you toward writing tests that encourage experimentation with React’s newest features while providing confidence that your user experience has not changed.</p><h3>Use React Testing Library Instead of Enzyme</h3><p>At the risk of coming across as a sponsored post, you’ll already be following most of the recommendations below simply by switching to <a href="https://testing-library.com/docs/react-testing-library/intro">React Testing Library</a>.</p><p>But you don’t have to take my word for it. <a href="https://reactjs.org/docs/test-utils.html#overview">React officially recommends React Testing Library over Enzyme</a>.</p><p><a href="https://airbnb.io/enzyme/">Enzyme</a> can do nearly everything that React Testing Library can, but React Testing Library can’t do nearly as much as Enzyme can.</p><p>As counterintuitive as that might sound, that’s precisely how React Testing Library encourages you to write far more robust tests. Their <a href="https://testing-library.com/docs/dom-testing-library/intro">documentation</a> adequately captures the problem with imperative tests:</p><blockquote>You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended.</blockquote><blockquote>As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don’t break your tests and slow you and your team down.</blockquote><p>On the other hand, Enzyme’s powerful API often encourages writing implementation-heavy tests. With Enzyme, you can <a href="https://airbnb.io/enzyme/">“manipulate, traverse, and in some ways simulate runtime given the output”</a>.</p><p>But Enzyme allows you to do those things in very imperative ways. With methods like <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/children.html">children</a> and <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/state.html">state</a>, you can peek into components to see exactly how they’ve been written.</p><p>Methods like <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/invoke.html">invoke</a> and <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/setState.html">setState</a> permit you to interact with components in a way that no end user ever would. And that type of interaction precisely highlights the core philosophical difference between the two libraries.</p><p>React Testing Library strives to have your tests interact with your code just as your users would. Its powerful <a href="https://testing-library.com/docs/dom-testing-library/api-queries">querying API</a> pushes you to see your tests just as your users would see your website running on their browser.</p><p>For example, your tests could find an input field <a href="https://testing-library.com/docs/dom-testing-library/api-queries#bylabeltext">byLabelText</a> and <a href="https://github.com/testing-library/dom-testing-library/blob/master/src/events.js#L59">fire a change event</a> to simulate typing in that field. This approach treats the component under test as a blackbox.</p><p>As long as that blackbox outputs the expected content into the DOM and onto the user’s screen, developers can freely experiment with new design patterns or tinker with React’s newest features without encountering test failures.</p><p>When they do encounter failures, they can be certain that they’ve actually broken a feature of the app.</p><h3>What if I Choose Not to Use React Testing Library?</h3><p>Whatever your reasoning or limitation for not switching over from Enzyme, you can still write great tests with that library.</p><p>Enzyme’s API does not prevent you from writing declarative tests grounded on user interaction. In order to do so, though, you’ll need to refrain from using a lot of Enzyme’s features.</p><h4>Always “mount” rather than “shallow” render</h4><p>Enzyme gives you the option to render the component you are testing in isolation (via shallow rendering) or to deep render that component along with all of its child/grandchild components (via mount rendering).</p><p>The <a href="https://airbnb.io/enzyme/docs/api/shallow.html">Enzyme documentation</a> explains the motivation for shallow rendering as “useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren’t indirectly asserting on behavior of child components.”</p><p>The motivation certainly appears sensible, but I’ve encountered enough drawbacks to that approach that I no longer use it.</p><p>First, shallow rendering has proven to be incompatible with some of React’s newest features. For example, <a href="https://github.com/airbnb/enzyme/issues/2011">it prevents you from accurately testing components that use Hooks</a>.</p><p>Although it’s very likely that shallow rendering will one day support Hooks, there’s no saying whether it will support the next set of new features. Moving over to mount helps provide confidence that you have correctly employed those features into your existing app.</p><p>More significantly, shallow rendering makes it burdensome to refactor by introducing reusable components. Suppose that you’ve created the form below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f5ecf4c90d9e12998daf188a655d02/href">https://medium.com/media/40f5ecf4c90d9e12998daf188a655d02/href</a></iframe><p>Some fairly simple <a href="https://jasmine.github.io/">Jasmine</a> tests might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11de6816118aa3253c49db9a0ff44b7f/href">https://medium.com/media/11de6816118aa3253c49db9a0ff44b7f/href</a></iframe><p>After creating enough of these text fields and noticing some repetition, you might decide to create a reusable TextField component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a837503f488cb900adfbed96e885e85/href">https://medium.com/media/0a837503f488cb900adfbed96e885e85/href</a></iframe><p>After bringing in your new component, your form would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2681f56061df0b1df1d0cdfc6dd8789a/href">https://medium.com/media/2681f56061df0b1df1d0cdfc6dd8789a/href</a></iframe><p>After this refactor, all three tests would fail because the shallow-rendered Enzyme wrapper would not render the content of any of the TextField children.</p><p>But the behavior of your app has not changed. To the end user, the DOM looks exactly the same before and after the refactor!</p><p>The shallow-rendered wrapper <em>does</em> correctly show that SomeForm has rendered three TextField components, and this limited blueprint of your component might encourage you to find the TextField component wrappers and assert that they receive the correct labelText prop.</p><p>I’ll strongly advise against doing that in more detail further below. But even if I did suggest that alternative, you’d still need to revisit and edit a failing test when refactoring. By mounting instead, your tests would continue to see the leaf nodes output onto the DOM, and you can avoid revisiting those tests.</p><p>From a testing perspective, shallow and mount respectively encourage writing unit and integration tests. By completely discouraging shallow rendering, it naturally follows that I also discourage writing unit tests.</p><p>Hopefully, it’s starting to become more clear why.</p><h3>Write Fewer Unit Tests and Default to Integration Tests</h3><p>Before I go any further, it’s worth briefly reviewing the <a href="https://martinfowler.com/articles/practical-test-pyramid.html">testing pyramid</a>, which provides a guideline for the sorts of tests that developers should write.</p><p>At the most foundational level, unit tests are small and isolated, so writing and running them is relatively inexpensive. Service tests (more often called <em>integration tests</em>) ensure that two or more of your units behave correctly when put together.</p><p>They’re more brittle than unit tests because multiple units can contain the cause of a test failure. Finally, UI tests (sometimes called end-to-end tests) ensure that your entire system works correctly.</p><p>These sorts of tests will often run your site on a browser, make actual HTTP requests, and possibly even hit a real database (albeit one dedicated to tests).</p><p>It’s no surprise that UI tests are the most expensive type of tests to write and maintain. They’re also the least helpful in pinpointing the exact source of a bug.</p><p>The cost/benefit ratio associated with the different types of tests has historically incentivized a pyramid-shaped test suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*6yt2W9tgriBbbMec.png" /><figcaption><a href="https://martinfowler.com/articles/practical-test-pyramid.html">https://martinfowler.com/articles/practical-test-pyramid.html</a></figcaption></figure><p>My biggest issue with unit testing in React is that there’s no consensus about what a React unit is. Is a view component a unit? If it gets too big and you decide to split it in two, are they now considered two units?</p><p>Are <a href="https://reactjs.org/docs/higher-order-components.html">higher-order components</a> or components that pass <a href="https://reactjs.org/docs/render-props.html">render props</a> themselves a single unit? What if they use <a href="https://reactjs.org/docs/hooks-reference.html">Hooks</a>? Is the Hook a unit?</p><p>I understand that it may come across as a wholesale dismissal of these very valid questions, but these questions don’t really matter if you write integration tests by default.</p><p>If you decide to split a tested component into two (or more) components, your integration-by-default tests won’t care or have to change. If you decide to replace render props with the <a href="https://reactjs.org/docs/context.html">Context API</a> to make your code less verbose, your integration-by-default tests won’t care or have to change.</p><p>When you finally bring in <a href="https://jaredpalmer.com/formik/">Formik</a> because you realize just how frustrating maintaining your own forms in React can be, your integration-by-default tests won’t care or have to change.</p><p>As long as your integration tests always specify what you want to see in the DOM, it doesn’t matter how you get there. This is exactly how React is meant to be written, and I strongly believe that it’s how most React tests should be written.</p><p>Of course, there’s still an important place for unit tests. However, I like to limit unit testing to reusable components and to any non-React business logic.</p><p>By unit testing reusable components, you provide any consumers of that component with confidence that it works as expected.</p><p>Because those unit tests interact directly with the API of your reusable components, they also document how those components should be used and how they should behave.</p><h3>Kent C. Dodds 🌌 on Twitter: &quot;&quot;The Testing Trophy&quot; 🏆A general guide for the **return on investment** 🤑 of the different forms of testing with regards to testing JavaScript applications.- End to end w/ @Cypress_io ⚫️- Integration &amp; Unit w/ @fbjest 🃏- Static w/ @flowtype 𝙁 and @geteslint ⬣ pic.twitter.com/kPBC6yVxSA / Twitter&quot;</h3><p>&quot;The Testing Trophy&quot; 🏆A general guide for the **return on investment** 🤑 of the different forms of testing with regards to testing JavaScript applications.- End to end w/ @Cypress_io ⚫️- Integration &amp; Unit w/ @fbjest 🃏- Static w/ @flowtype 𝙁 and @geteslint ⬣ pic.twitter.com/kPBC6yVxSA</p><h3>Don’t Assert Against React Components</h3><p>It might strike you as odd that a library meant to test React shouldn’t assert against React components. But <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/find.html">find</a>ing a React component by its display name or constructor ties your tests to that component’s specific name and location in your directory, respectively.</p><p>Even with IDE tools that quickly find and replace text across files and automatically update imports, these changes create a lot of noise in pull requests.</p><p>As an alternative to finding and asserting against React components, you can find and assert against components in the DOM in ways similar to Enzyme’s querying API.</p><p>If you find these too difficult to implement yourself (or if you are looking for a quick fix), you can begin by adding data-testid attributes to the elements against which you are asserting and finding those elements.</p><p>Finding your components this way will make it painless to later bring in React Testing Library, which allows you to <a href="https://testing-library.com/docs/dom-testing-library/api-queries#bytestid">query by </a><a href="https://testing-library.com/docs/dom-testing-library/api-queries#bytestid">data-testid</a> as a sort of escape hatch.</p><p>In projects where you expect design and copy to change frequently, data-testid attributes make your tests more resilient to change. As your project stabilizes, you might want to migrate toward queries that your users can actually see.</p><p>Although that migration might make your tests more brittle, they help ensure that your users can actually interact with your app in a sensible way.</p><h3>Don’t Assert Against Props</h3><p>Asserting against props opens up your test suite to a lot of fake positives. I most often see attempts to unit test a component fall into this trap.</p><p>When you assert against props, you’re almost certainly doing so because your component under test contains a dependency to another component. In an effort to isolate your component under test, you might decide to assert that your own component passes the correct props to a dependent component.</p><p>Although this strategy does achieve isolation, it does so at the expense of test confidence.</p><p>To expand upon the example above, such a test file might look like the one written below. For simplicity, they use the <a href="https://airbnb.io/enzyme/docs/api/ShallowWrapper/at.html">at</a> method to find the first TextField node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/196282bef053e82b30c94819d25c889b/href">https://medium.com/media/196282bef053e82b30c94819d25c889b/href</a></iframe><p>A developer might decide to alter the TextField in such a way that replaces the label tag with placeholder text inside of the input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41cb48107db2f9403a08357ed5d4fd53/href">https://medium.com/media/41cb48107db2f9403a08357ed5d4fd53/href</a></iframe><p>In the absence of strong integration and functional tests, the developer making this change might not encounter any test failures and thus feels safe pushing the change.</p><p>I’d argue that you should want your tests to fail in this case because your end user’s experience has changed: they’d have no idea what they should be typing inside of the input fields!</p><h3>Don’t Assert Against or Force State</h3><p>Giving your tests knowledge about the internal state of your components will almost surely keep you from keeping your React code up to date.</p><p>As of <a href="https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019">React 16.8</a>, it’s possible to write React almost entirely with functional components thanks to <a href="https://reactjs.org/docs/hooks-intro.html">Hooks</a>. Functional components cannot use state the same way that class components can. Instead, they must use the <a href="https://reactjs.org/docs/hooks-state.html">useState</a> hook.</p><p>When I begin work on a feature, I like to start by converting any class components I encounter into functional components. When I do so, I rely on my tests to indicate whether I’ve made a mistake in the conversion.</p><p>But this strategy becomes significantly slower when I have to address misleading test failures along the way.</p><p>In much the same way that an end user doesn’t care about your implementation, a developer consuming your reusable component shouldn’t care whether it was written as a class or as a functional component.</p><h3>Don’t Test Instance Methods</h3><p>The belief that you shouldn’t test private methods has become fairly uncontroversial. After all, those methods aren’t exposed, and they’re strictly implementation details.</p><p>However, those same considerations don’t always extend to instances of React class components. Enzyme provides you with an <a href="https://airbnb.io/enzyme/docs/api/ReactWrapper/instance.html">#instance</a> function, and it’s not uncommon to see tests taking full advantage of that method to invoke instance methods.</p><p>But even if you confidently test the behavior of the instance method, such a test doesn’t ensure that the method is actually being used correctly. It doesn’t even ensure that the instance method is being used at all, and that gap could lead to the preservation of dead code.</p><p>If your codebase eventually stopped using an instance method, deleting it would cause test failures. Whoever encounters that failure might play it safe by keeping that method. Pretty soon, your class components could get unmanageably large.</p><p>Class components can also become large by containing business logic in their instance methods. If you feel strongly about unit testing that business logic, you can and should abstract the logic out in a functional, React-agnostic way.</p><p>By making those methods functional, you make them reusable for other components. By making them agnostic to React, you also abstract your business logic away from your UI framework, making it easier to eventually migrate to a newer version of React or even to a new UI library.</p><p>As above, not testing instance methods also makes it possible to refactor your class components into functional components (which cannot have instance methods) without breaking any tests along the way.</p><h3>The Drawbacks</h3><p>As many benefits as they bring to your test suite, the strategies I’ve outlined above don’t come without any drawbacks.</p><h4>Increasing reliance on integration tests hides the source of a test failure</h4><p>With fewer unit tests across your test suite, your test failures will inevitably involve a number of connected components, likely masking the source of a failure. This is a perfectly valid concern.</p><p>But — written correctly — your tests will not mislead you about where the error might live. When a unit test fails, you will know that the error <em>must</em> be present in the unit under test.</p><p>When an integration test fails, you will know that the error <em>must </em>be present somewhere down the DOM beginning with the component that your test renders.</p><p>Facebook has also created an amazing set of <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">developer tools</a> to inspect your React components, which makes debugging surprisingly pleasant.</p><p>While they will never be a replacement for tests, the tools do allow you to quickly see how props and Context values trickle down the component tree or how your components change as their internal state changes.</p><p>You can use this quick feedback to help you determine the source of a test failure.</p><h4>Losing the benefit of testing as documentation</h4><p>As a positive side-effect, tests often provide you and your team with documentation for interacting with your API. But if your tests begin to focus on user behavior, they begin to lose that benefit.</p><p>However, you can achieve the same benefit with a number of strategies varying in cost. You can enforce types for the props passed into your components using the lightweight <a href="https://reactjs.org/docs/typechecking-with-proptypes.html">PropTypes</a> library.</p><p>You can also strongly type your entire app using <a href="https://flow.org/en/docs/react/">Flow</a> or <a href="https://www.typescriptlang.org/docs/handbook/react-&amp;-webpack.html">TypeScript</a>. Both approaches allow you to document how to consume your components by quickly looking at type definitions or PropType signatures.</p><p>For a more designer-friendly approach, <a href="https://storybook.js.org/">Storybook</a> vividly documents your UI components, allowing developers to dynamically learn how to use your components.</p><p>Bringing in these libraries does take time and effort. However, I’d weigh the increase in time to maintain yet another library with the decrease in time spent dealing with brittle tests.</p><h3>Conclusion</h3><p>You probably already know that React changes extremely quickly. The components that I write today are pretty much unintelligible to the React that I learned in late 2017.</p><p>If you want to take full advantage of React’s newest features as painlessly as possible, you’ll have to stop testing React’s current features. React will also not be the most popular front-end framework forever.</p><p>It’s difficult to anticipate which new framework you’ll be working with a few years down the road, but the less your tests know about React, the easier they will be to port over to another testing framework later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4730b16e71ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/declarative-testing-in-react-4730b16e71ec">Declarative Testing in React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolated Unit Testing with Test Doubles]]></title>
            <link>https://medium.datadriveninvestor.com/isolated-unit-testing-with-test-doubles-75eff05f76a9?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/75eff05f76a9</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 17:53:37 GMT</pubDate>
            <atom:updated>2018-12-22T08:01:54.616Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NDxrQiq3Cp_NSnUZ" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x92xg18PwxSkTRuy.jpg" /></figure><h4>A painfully simple example in Ruby with rspec and rspec-mocks</h4><p>When practicing Test-Driven Development, it’s important to ensure that your unit tests actually test just a single unit (often a single class) of your codebase. If your unit tests depend too heavily on external classes, it becomes difficult to determine the source of a test failure. One common way to achieve isolation is to implement a test double rather than rely on the inner workings of an external class.</p><p>Like a stunt double, a test double will jump into action and replace an actual object inside of your test. Test doubles help isolate your unit tests, ensuring that the tests you write actually test a single unit. They can also help speed up your tests by avoiding costly or slow processes, such as emitting a request to an actual API (which you may or may not own) or querying a database (which may contain production data or need to be seeded).</p><p>The method or class being tested is often referred to as the System Under Test, or SUT. In a strongly-typed language, a test double must conform to the interface of an object on which the SUT depends. By conforming to the object’s interface, the SUT has no idea that it has been passed in an object other than the object that it would typically receive in production. In a dynamic language like Ruby, doubles act as <a href="https://en.wikipedia.org/wiki/Duck_typing">duck types</a>, responding to a method call that exists in the implementation of the system it stands in for. In this example, we’ll focus on the latter type using Ruby and RSpec.</p><p>This article assumes that you are already familiar with unit testing (specifically with RSpec). If you don’t already feel comfortable with those topics, here are some suggested readings before returning to mocks.</p><ul><li>For an introduction to the three levels of testing: “<a href="https://martinfowler.com/articles/practical-test-pyramid.html">The Practical Test Pyramid</a>”</li><li>For an introduction to unit testing with RSpec: <a href="https://www.theodinproject.com/courses/ruby-programming/lessons/introduction-to-rspec">“An Introduction to RSpec”</a></li></ul><h3>A Note about Nomenclature</h3><p>If you look up the difference between test doubles and mocks, you might be surprised to realize that there isn’t a consensus about their difference. <a href="https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs">Martin Fowler</a> argues that the the former utilizes state verification while the latter uses behavior verification to test a given object. While the distinction might work on a theoretical level, the mocking framework that you choose will often decide the difference for you. For example, rspec-mocks blurs the distinction between the two. As per the RSpec mocks <a href="http://rspec.info/documentation/3.4/rspec-mocks/">documentation</a>:</p><blockquote>rspec-mocks is a test-double framework for rspec with support for method stubs, fakes, and message expectations on generated test-doubles and real objects alike.</blockquote><p>The distinct implementations of mocks and doubles among different mocking libraries and frameworks makes it imperative to always read the documentation instead of relying on a preconceived notion about what a mock or a test double actually is.</p><p>As with most aspects of software development, passionate developers with strongly-held opinions will often back or admonish certain philosophies about testing. My goal is not to convince you that you should prefer one method of testing over another. Rather, I hope to demonstrate that isolated unit testing isn’t difficult once you’re familiar with the tools available to you.</p><h3>A Simple, Wholesome Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uuFkfksEbzcWH8co.jpg" /></figure><p>In a more perfect world, every human being would have a pet. A human would be able to interact with its pet through predetermined actions: feeding, petting, etc. Those actions would affect the pet’s emotional and physical qualities.</p><p>To abstract that behavior into object-oriented code, we can think of a few classes that capture the desired behavior. First, we’d want a Human class, which is initialized with a pet. Because different species of pets vary so much from each other, we’d want to create a hierarchy of classes to represent the different possible pet species. The superclass Pet would contain the functionality common across all pets. For this example, we’ll establish that all pets eat, and they all make some kind of noise. A specific species would be able to further refine the behavior common to all pets, and it might even add its own unique behaviors.</p><p>In this example, the Human class will depend on the Pet class (and possibly its inherited classes) because a human instance will invoke methods on a pet instance. In other words, the Human class is our SUT. To demonstrate how the use test of doubles allows us to develop and test a class before its dependency has been created, we’ll develop our Human class as we test it.</p><h3>Instantiating a Human</h3><p>We can follow the suggestion of Freemand and Pryce in <em>Growing Object-Oriented Software Guided By Tests </em>and<em> </em>write our tests as if the implementation of the system under test already exists (84). This approach helps us begin to think about good variable and method names. The strategy also helps us begin to see how much setup is required to instantiate and object. A complicated, verbose setup could signal that we can abstract some of the setup steps into a distinct class.</p><p>Using <a href="https://www.rubydoc.info/gems/rspec-expectations/frames">RSpec expectations</a>, our first test should simply assert that an instantiated human contains and exposes a pet. We really don’t want to get sidetracked building out the Pet class, but to ensure that our doubles match our eventual implementation, we will be creating instance_doubles rather than a regular old doubles. When using an instance_double, RSpec will throw an error if the object you wish to replace doesn’t contain a method you intend to use.</p><pre>describe Human do<br>  context &quot;init&quot; do <br>    it &quot;should initialize a Human with a Pet&quot; do<br>      pet = instance_double(&quot;Pet&quot;) <br>      human = Human.new(pet)<br>      expect(human.pet).to eq(pet)<br>    end<br>  end<br>end</pre><p>It should be no surprise that our test fails with an error:</p><pre>An error occurred while loading ./spec/human_spec.rb.<br>Failure/Error:<br>  describe Human do<br>    context &quot;init&quot; do<br>      it &quot;should initialize a Human with a Pet&quot; do<br>        pet = instance_double(&quot;Pet&quot;)<br>        human = Human.new(pet)<br>        expect(human.pet).to eq(pet)<br>      end<br>    end<br>  end</pre><pre>NameError:<br>  uninitialized constant Human<br># ./spec/human_spec.rb:6:in `&lt;top (required)&gt;&#39;</pre><p>Normally I’d proceed by doing the bare minimum to address an error, rerunning the test, and repeating the cycle until I eventually reach a failure. I’ll actually write a bit more code than that to avoid a lot of redundancy in this article. Since every human needs a pet, we’ll ensure that every new human must be created with a pet, and we’ll make that pet accessible via an attr_reader.</p><pre>class Human <br>  attr_reader :pet<br>  <br>  def initialize(pet)<br>    <a href="http://twitter.com/pet">@pet</a> = pet <br>  end <br>end</pre><p>In a strongly-typed language, like Java, you would need to ensure that the test double conforms to the expected interface. Otherwise, your code would not compile, and you’d be unable to run your tests. With Ruby, we’ll need to be a little more verbose inside of our #initialize.</p><pre>class Human <br>  attr_reader :pet <br>  <br>  def initialize(pet)<br>  raise ArgumentError.new(&quot;A Human must be initialized with a Pet&quot;) unless pet.is_a?(Pet)  <br>  <br>  <a href="http://twitter.com/pet">@pet</a> = pet<br>  end<br>end</pre><p>Unfortunately, our test double is not an instance of Pet. If you puts(pet.class.name) inside of the test, you’ll see that pet is actually an instance of RSpec::Mocks::InstanceVerifyingDouble. To prevent the error upon initialization, we’ll need to <em>stub </em>the response that we want our double to return. We’ll explore stubs further below, but a stub is simply a hard-coded response to a method call. Below, you can see how we specify the method</p><pre>context &quot;init&quot; do <br>  it &quot;should initialize a Human with a Pet&quot; do<br>    pet = instance_double(&quot;Pet&quot;)<br>    allow(pet).to receive(:is_a?).with(Pet).and_return(true) # STUB CONFIGURATION<br>    human = Human.new(pet)<br>    expect(human.pet).to eq(pet)<br>  end<br>end</pre><p>Our single test should now be green! Of course, that error was an expected behavior, so we should definitely create a test for that scenario. To avoid giving the impression that our test double is a type of Pet , we’ll remove the test double and pass in an argument of type String instead.</p><pre>it &quot;should throw an error if a Human is not initialized with a Pet&quot; do<br>  pet = &quot;Not a pet&quot;<br>  expect { Human.new(pet) }.to raise_error(ArgumentError)<br>end</pre><h3>Feeding Our Pet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wAv8n6jhfz8YxL2ep3C2g.jpeg" /></figure><p>If you own a cat, you’ve probably woken up to loud meows requesting food. With that in mind, the first thing we should program our human to do is feed its furry friend. Like a human, a pet experiences hunger, so feeding it should alter its hunger level.</p><p>Even with such a simple example, we’ve quickly hit the boundary of a unit test: an external dependancy. In the real world, the methods that you call will probably not be as simple as the one we will soon implement. They may also change. They might not even work as expected. To save you the headache of figuring out the source of a possible error, you want to ensure that no unit in your unit tests is coupled to the implementation of another.</p><p>In this specific case, we can achieve independent tests using a spy.</p><h4><strong>Spy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cASj16JddFEgYBg8.jpg" /></figure><p>As its name implies, a spy spies on an object, tracking the number of calls to an objects’s methods and even the arguments passed into those calls. Depending on the mocking library you are using, a spy may wrap itself around an existing method without altering its underlying behavior. However, rspec-mocks creates spies as_null_objects, so the code you are spying on never runs. Though this behavior may seem intrusive, it ultimately helps up stay focused on developing the current system under test.</p><p>As above, we use an instance_spy rather than a regular old spy in order to build up a very simple skeleton of our dependency.</p><pre>context &quot;feeding a pet&quot; do <br>    it &quot;should cause the pet to eat&quot; do <br>      pet = instance_spy(&quot;Pet&quot;)<br>      human = Human.new(pet)<br>      <br>      human.feedPet()<br>      expect(pet).to have_received(:eat) # SPY ASSERTION<br>    end<br>  end</pre><p>Because we haven’t created the #feedPet method, we get the following error:</p><pre>Failures:</pre><pre>1) Human feeding a pet should cause the pet to eat<br>     Failure/Error: human.feedPet()</pre><pre>NoMethodError:<br>       undefined method `feedPet&#39; for #&lt;Human:0x00007f9780057db8&gt;<br>     # ./spec/human_spec.rb:19:in `block (3 levels) in &lt;top (required)&gt;&#39;</pre><p>Following our error and going just a little beyond what it requires, we add the following instance method to Human.</p><pre>def feedPet() <br>    self.pet.eat()<br>end</pre><p>However, that still gives us the expected error:</p><pre>Failures:</pre><pre>1) Human feeding a pet should cause the pet to eat<br>     Failure/Error: self.pet.eat()<br>       the Pet class does not implement the instance method: eat<br>     # ./lib/human.rb:9:in `feedPet&#39;<br>     # ./spec/human_spec.rb:19:in `block (3 levels) in &lt;top (required)&gt;&#39;</pre><p>All it takes to get rid of our error now is the following empty instance method to the Pet class:</p><pre>def eat()<br>end</pre><p>If you feel uncomfortable about this empty method, you can always raise an error inside of it. That way, if you accidentally do end up calling the actual method, you’ll know right away. As mentioned above, the pet test double will not invoke the actual method even though it requires the method to exist.</p><pre>def eat() <br>  raise &quot;Pet#eat has not been implemented&quot;<br>end</pre><p>When we later arrive at Pet&#39;s unit tests, we can determine what we actually want the #eat method to do. Perhaps we want to track our pet’s hunger level as an Integer, which goes up by one when it is fed. Perhaps we’d like to track a pet’s weight, which increases if a pet eats while it’s already full. Perhaps the pet is just like my old cat, and her hunger level will remain high despite how much you feed her. Because of our isolated test, we can focus on the human‘s behavior without simultaneously concerning ourselves with the pet‘s behavior or change of state.</p><h3><strong>Imitating Our Pet</strong></h3><p>It’s safe to say that every pet owner has imitated the sound that its pet makes, so we’ll test that next. The naive approach to this test might be to assert against a String we expect to receive from our pet. However, there are many reasons for a pet’s sounds to change. Maybe a cat hisses when it’s hungry but purrs when it’s full. Or maybe our human adopts a new species after its old pet runs away.</p><h4>Stubs</h4><p>Instead of relying on a value that would very likely change, we’ll make use of a stub. Asserting against a stubbed response helps us conform to the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov substitution principle</a>, which states that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.” In other words, it shouldn’t matter what kind of pet our human interacts with as long as the pet behaves like a pet and exposes the expected methods.</p><p>As above, we rely on an instance_double to ensure that we’ve laid out the foundation for our dependent class.</p><pre>context &quot;imitating a pet&quot; do <br>  it &quot;should speak the sound that its pet makes&quot; do <br>    pet = instance_double(&quot;Pet&quot;)<br>    stubbedPetSound = &quot;Oink&quot; <br>    allow(pet).to receive(:speak).and_return(stubbedPetSound)<br>    human = Human.new(pet)</pre><pre>    imitation = human.imitatePet()<br>    expectedImitation = &quot;It&#39;s so funny when my pet says #{stubbedPetSound}&quot;<br>    expect(imitation).to eq(expectedImitation)<br>  end<br>end</pre><p>By now, we should be pretty familiar with the error we expect to receive.</p><pre>Failures:</pre><pre>1) Human imitating a pet should speak the sound that its pet makes<br>     Failure/Error: allow(pet).to receive(:speak).and_return(stubbedPetSound)<br>       the Pet class does not implement the instance method: speak<br>     # ./spec/human_spec.rb:29:in `block (3 levels) in &lt;top (required)&gt;&#39;</pre><p>After creating an empty Pet#speak method, we’ll skip the error we know we’ll receive for not having implemented Human#imitatePet and create that method now.</p><pre>def imitatePet() <br>    return &quot;It&#39;s so funny when my pet says #{self.pet.speak()}&quot;<br>end</pre><p>Stubs are incredibly useful when unit testing an instance method that relies on the returned value of another class’s method. In our example above, we don’t know what kind of sound our pet will make. We don’t even know what kind of pet our owner might have. When those things eventually change inside of the Pet class, our Human test will not have to change as long as the publicly exposed method signature remains the same.</p><p>Because our Pet class doesn’t yet have an external dependency, it will not need the rspec-mocks framework to remain isolated. As long as it remains without an external dependency, testing that class should remain relatively straightforward, so I won’t demonstrate its tests.</p><p>Hopefully this simple example helps you understand how make use of mocks to isolate your unit test as well as why it’s important to think about isolation.</p><h4>For further reading:</h4><p><a href="https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs">Mocks Aren’t Stubs,</a> by Martin Fowler</p><p><a href="http://xunitpatterns.com/State%20Verification.html">State Verification</a> v. <a href="http://xunitpatterns.com/Behavior%20Verification.html">Behavior Verification</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75eff05f76a9" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/isolated-unit-testing-with-test-doubles-75eff05f76a9">Isolated Unit Testing with Test Doubles</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differentiating Test Doubles]]></title>
            <link>https://medium.com/@omarnyte/differentiating-test-doubles-ea1f65f5083f?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1f65f5083f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Mon, 15 Oct 2018 02:42:04 GMT</pubDate>
            <atom:updated>2018-10-15T15:30:21.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4HaBZARH_TTgdFfJK3EOA.jpeg" /></figure><h4>Dummies, Spies, Stubs, Fakes, and Mocks</h4><p>When practicing Test-Driven Development, it’s important to ensure that your <a href="https://code.tutsplus.com/articles/the-beginners-guide-to-unit-testing-what-is-unit-testing--wp-25728">unit tests</a> test just a single unit (often a single class). If your units depend too heavily on external classes, it becomes difficult to determine the source of a test failure. Test doubles help isolate your unit tests, ensuring that the tests you write actually test a single unit. They can also help speed up your tests by avoiding costly or slow processes, such as emitting a request to an actual API (which you may or may not own) or querying a database (which may or may not contain production data and which may need to be seeded).</p><p>The method or class being tested is often referred to as the System Under Test, or SUT. A test double conforms to the interface of an object on which the SUT depends. By conforming to the object’s interface, the SUT has no idea that it has been passed in an object other than the object that it would typically receive in production.</p><p>When it comes to the vocabulary of test doubles, there doesn’t appear to be a consensus on the difference between them the wide range of them. Although the names may vary across different mocking frameworks, a familiarity with the different features available across test doubles can help you build isolated, resilient tests.</p><h4>Dummy</h4><p>Dummies are the simplest type of test double. They really don’t do much other than get passed in to fulfill a parameter requirement. Creating dummies is so simple that it doesn’t require an external library.</p><p>Often, though, the need for dummies might signal that your code could be improved. If you find yourself passing in an argument simply to prevent a compilation error, you might want to see if the language you are working with supports variable arity methods. These types of methods differentiate between methods with the same name if their parameters differ in length. For example, the following two Java methods are both called describeCat, but the appropriate one will get called depending on whether you pass in one or two arguments to the call.</p><pre>public class Cat {<br> <br>  public static String describeCat(String name) {<br>    return &quot;This cat&#39;s name is &quot; + cat + &quot;. Its energy level is unknown, so beware when interacting with it.&quot;; <br>  } </pre><pre>  public static String describeCat(String name, String energyLevel) {<br>    return &quot;This cat&#39;s name is &quot; + cat + &quot;. Its energy level is  &quot; + energyLevel + &quot;.&quot;;  <br>  }</pre><pre>}</pre><p><strong>When to use dummies:</strong></p><ul><li>If the SUT requires an argument to contain a valid property (such as an existing directory path)</li></ul><h4><strong>Spies</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZN2TWY9SeACvNxCEIAVUg.jpeg" /></figure><p>Aside from dummies, spies are the least intrusive type of test double. As their name implies, they spy on methods in a fairly unobtrusive way, and they don’t change the underlying behavior of the method on which they’re spying. Instead, they wrap themselves around a method, allowing you to record and run assertions against the way that the SUT interacts with that method. Often this will mean running assertions against the number of times a method was called as well as against the arguments passed into those method calls.</p><p>Spies can also act a bit like dummies. Some libraries, like <a href="https://sinonjs.org/releases/v6.3.5/spies/">Sinon.js</a>, allow you to create spies as anonymous functions. Unlike a dummy, though, you wouldn’t just pass it into a method to fill a parameter requirement. Instead, you’d run an assertion to ensure that the anonymous function was called.</p><p><strong>When to use spies:</strong></p><ul><li>When the SUT contains conditional logic which affects the number of times a method gets called</li><li>When a method manipulates an argument, which gets passed as an argument to another method</li><li>Ensuring that a callback gets called in an asynchronous method</li></ul><h4><strong>Stubs</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQK0qI9OVyeCzR0OBuchSw.jpeg" /></figure><p>Although spies are great for ensuring that helper methods within a class get called, they don’t help isolate your SUT from methods located in an external class. To prevent a unit test from depending on the functionality of another class, stubs provide one way of operating under the assumption that the an external class works as expected.</p><p>Like a spy, a stub also wraps itself around an existing method. Once wrapped, the stub can be configured to respond to in a certain way based on given arguments, or it can be configured to always return the same response. The consistent responses can then be used to run assertions against the SUT.</p><p><strong>When to use stubs:</strong></p><ul><li>Testing error handling by forcing a method inside the SUT to return an error</li><li>Preventing an external call (such as an AJAX, fetch, XMLHttp) or a database query</li></ul><h4>Fakes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsCBcNkQhmsJuylZsG8MOA.jpeg" /></figure><p>Previously, I wrote an article titled <a href="https://medium.com/@omarnyte/understand-java-i-o-streams-by-writing-your-own-2981f9a2d89">“Understand Java I/O Streams By Writing Your Own”</a>. In that article, I created a MockInputStream and a MockOutputStream class, which would be instantiated and have their methods called by a MockSocket class. Looking back, I actually misnamed those classes. In reality, they actually resemble fakes because fakes constitute actual implementations of the object on which the SUT depends. The main difference between fakes and their actual implementation is that a fake may be constructed with a shortcut that makes it unsuitable for production.</p><p>Fakes must conform to an interface. In a strongly typed language, such as Java, passing in a fake object that doesn’t inherit from an expected class or implement an expected interface will throw a compilation error. For these languages, mocks that you create will need to <a href="https://en.wikipedia.org/wiki/Duck_typing">walk like a duck and quack like a duck</a> if the method expects to receive a duck.</p><p><strong>When to use fakes:</strong></p><ul><li>When you can replace a slow process with a faster process without changing the interface (such as using an in-memory database)</li><li>When the SUD returns void but you want to run an assertion against a side effect.</li></ul><h4>Mocks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KA7ceqnFJoy--pcSPXJelA.jpeg" /></figure><p>Mocks are different from fakes and stubs in that the expected <em>behavior</em> between the SUT and the dependency is declared upfront when setting up the mock. This means that the expected method calls — and possibly the order of those methods calls — are configured into the mock when instantiating it. Fakes and stubs stand in for a real object, but the assertions in the tests are made against the <em>state</em> of the SUT after interacting with the external dependencies.</p><p><strong>When to use mocks:</strong></p><p>There seems to be a bit of a debate between using mocks or stubs/fakes. Quite honestly, after learning the difference between them, I feel more hesitant to use mocks. Because mocks assert against the interactions with the methods of another class, it necessarily means that the test will be coupled to the implementation of that class. Because spies can be used to test the behavior of a SUT, they can be used to eliminate the need for mocks. At the end of the day, it depends on whether it makes more sense to verify a SUT’s behavior or state — something that I didn’t explore in this article. Like most debates in software development, it really depends on the specific project and especially on the specific SUT.</p><p>For further reading:</p><p><a href="https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs">Mocks Aren’t Stubs,</a> by Martin Fowler</p><p><a href="http://xunitpatterns.com/State%20Verification.html">State Verification</a> v. <a href="http://xunitpatterns.com/Behavior%20Verification.html">Behavior Verification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1f65f5083f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JRE, JVM, JDK…IDK]]></title>
            <link>https://medium.com/@omarnyte/jre-jvm-jdk-idk-15038a4993d5?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/15038a4993d5</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 21:51:44 GMT</pubDate>
            <atom:updated>2018-10-10T21:52:21.770Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Java Acronyms &amp; Lingo I Should Have Learned Months Ago</h4><p>Despite spending the last five months building applications in Java and Clojure (a Java Virtual Machine language), I didn’t realize how little I knew about the inner workings of Java until last week.</p><p>Nearly five months ago, I began my apprenticeship at 8th Light, and my first task was to create a Tic Tac Toe game with Clojure — a functional programming language that runs on the Java Virtual Machine. Both terms were pretty new to me, and I focused my effort and excitement on the former term. I let <a href="https://leiningen.org/">Leiningen</a> — an automation tool that helps you quickly test and build a Clojure project — do all of the heavy lifting during the set up, ensuring that virtually all of the difficulty of that project fell on familiarizing myself with functional programming and test-driven development.</p><p>After completing that project, I then began building an HTTP server with Java. As with the previous project, I let <a href="https://gradle.org/">Gradle</a> do all of the heavy lifting involved with setting up (<a href="https://medium.com/@omarnyte/getting-started-with-tdd-in-gradle-for-java-8135504660af">even though I didn’t fully understand what Gradle even was</a>).</p><p>Putting the two pieces together — that is, serving the Tic Tac Toe game on my server — revealed how little I actually knew about Java fundamentals. I wanted to build some momentum and quickly get going with this project, so I initially created a new Clojure project (with Leiningen) and simply copied the Java server source code into the new Clojure project repo. I knew that I’d eventually want to remove the server source code and instead import the server as a dependency.</p><p>When it came time to publish my server to make importing it possible, I ran into virtually no issues. Making use of the imported server, however, posed a few problems. Most notably, because I never researched Java packages, I hadn’t actually packaged a single one of my classes, making them unavailable to my Clojure project. Properly packaging and importing every class (including test classes) before pushing up the server once more delayed my progress by quite a few hours.</p><p>When I implemented continuous integration with Travis CI in order to deploy the game to Heroku, I ran into the following error on my build logs:</p><blockquote>Exception in thread “main” java.lang.UnsupportedClassVersionError: com/omarnyte/handler/Handler has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 52.0, compiling:(web_tic_tac_toe/default_handler.clj:4:1)</blockquote><p>I knew that this wasn’t an issue on my end. After all, both Java and Leiningen appeared to be on version 10.0.1.</p><pre>$ java --version</pre><pre>java <strong>10.0.1</strong> 2018-04-17<br>Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)<br>Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)</pre><pre>$ lein --version<br>Leiningen 2.8.1 on Java <strong>10.0.1</strong> Java HotSpot(TM) 64-Bit Server VM</pre><p>Although it didn’t take long for me to realize that Travis CI defaults to JDK8 when building, I realized that I didn’t actually know what JDK truly meant. Seeing the three different versions (10.0.1 for java, 18.3 for Java(TM) SE Runtime Environment and 18.3 for Java HotSpot(TM) 64-Bit Server VM) side by side finally convinced me to take a step back and go back to the Java basics.</p><h3>JVM v. JDK v. JRE</h3><p>To fully understand the difference between these acronyms, it makes sense to briefly visit Java’s slogan: write once, run anywhere. In order to allow Java to truly run anywhere, the Java platform includes a few intermediary steps between a human writing the program and the computer running it.</p><p>In any Java program, you’ll write source code in plain text .java files. A compiler converts those files into bytecode .class files. Because the bytecode does not contain code native to the computer on which the program will run, it requires a virtual machine to convert the bytecode into machine code specific to the computer. The visual from Oracle below concisely outlines the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*87h4XmVnw6VbWnXs6skI_g.gif" /><figcaption><a href="https://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html">https://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html</a></figcaption></figure><h4>Java Virtual Machine — JVM</h4><p>Because of its abstract nature, we’ll visit the Java Virtual Machine first. The JVM is defined by a specification. That specification includes the requirement, among others, to recognize .class files. Since it’s a specification, different providers are free to implement a JVM in different ways as long as they conform to that specification. More technical details about the specification can be found <a href="https://www.javatpoint.com/internal-details-of-jvm">here</a>.</p><p>Because of the presence of the JVM, different languages can be compiled to Java bytecode. These languages are known as <a href="https://www.baeldung.com/jvm-languages">JVM languages</a>. Applications written in one JVM language can import and make use of classes written in another JVM language.</p><p>In order to make use of the JVM, there needs to be an implementation of that machine. A runtime environment provides that implementation.</p><h4>Java Runtime Environment — JRE</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*i5O0vuTu2vBJn69OYoyEkw.png" /><figcaption><a href="https://www.javatpoint.com/difference-between-jdk-jre-and-jvm">https://www.javatpoint.com/difference-between-jdk-jre-and-jvm</a></figcaption></figure><p>The Java Runtime Environment provides an implementation of the JVM as well as tools and <em>environment</em> necessary to <em>run</em> a Java program. Because the JRE provides the JVM responsible for converting bytecode into machine code, the JRE is platform specific. If you take a look at the <a href="https://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html">Java SE [Standard Edition] Runtime Environment 8 Download website</a>, you’ll notice that the downloads differ between Linux, Mac, Windows, and Solaris.</p><p>The JRE also contains a file called rt.jar<em> </em>(“rt” for Runtime). The file contains all of the compiled classes the JRE requires to run as well as some core classes that make your life as a developer easier. When developing applications in Java, these compiled classes (such as java.lang.String or java.io.InputStream) can be imported without explicitly installing them as dependencies.</p><p>For those wishing to simply run a Java application (most likely from a JAR file), an up-to-date JRE would suffice. However, those developing Java applications will need the aptly-named Java Development Kit.</p><h4>Java Development Kit — JDK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*rdaeRAfN0VoystxmokE18A.png" /></figure><p>As its full name implies, the JDK contains tools to help <em>develop</em> applications in addition to everything included in a JRE. <a href="https://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html">As per the Java SE [Standard Edition] Runtime Environment 8 downloads page</a>:</p><blockquote>Do you want to run Java™ programs, or do you want to develop Java programs? If you want to run Java programs, but not develop them, download the Java Runtime Environment, or JRE™.</blockquote><blockquote>If you want to develop applications for Java, download the Java Development Kit, or JDK™. The JDK includes the JRE, so you do not have to download both separately</blockquote><p>Unlike with the JRE, a JDK can be obtained outside of Oracle. <a href="https://openjdk.java.net/">OpenJDK</a> and <a href="https://www.azul.com/downloads/zulu/">Azul Zulu</a> both provide open-source builds of the JDK. Regardless of the source of the JDK, they all include a number of common tools.</p><p>The compiler (javac) takes a .java file and compiles it into bytecode as a .class file. This step allows Java to be so versatile across platforms. While anyone can write Java plain text files by simply appending .java to a file name, not much can be done with that file without a compiler.</p><p>A JDK also includes a disassembler (javap) that allows you to inspect any .class file. By navigating to the directory of a .class file and running javap &lt;fileName&gt; , you can learn quite a bit about the file. Suddenly I had context for the error I saw way up above.</p><pre>$ javap -verbose Main.class</pre><pre>Classfile /Users/omard/Box Sync/8th Light/http-server/build/classes/java/main/com/omarnyte/Main.class<br>Last modified Oct 4, 2018; size 5185 bytes<br>MD5 checksum b82b94656f029ed420cc8067836b0556<br>Compiled from &quot;Main.java&quot;<br>public class com.omarnyte.Main<br>minor version: 0<br>major version: 54<br>... </pre><p>One of the final pieces in developing Java programs involves creating a shareable, often executable file. A JDK also provides developer with an archiver (jar), which packages a project’s class libraries into a single JAR file.</p><h3>JAR v. Uber JAR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQ7mrcO9s3hMDz1fENJ66Q.jpeg" /></figure><p>Java Archives — or JARs — contain aggregated bytecode and configuration files. In order to make it executable, a JAR file requires a Main-Class entry point, which can be specified in a manifest file. You can actually change the extension of any .jar file to .zip to inspect its contents. You’ll see that it contains all of the classes that make up a project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcwdTqSHaRx16yIFdpIx7g.png" /></figure><p>An Uber JAR — also known as a fat JAR — contains not just the aggregated bytecode for a given project, but also the bytecode for any of a project’s dependencies. Its name will typically end with the word “standalone” to indicate that it can run on its own without installing any additional dependencies.</p><p>After converting my web-tic-tac-toe-standalone.jar to a zip file, you can see that it not only contains the .class files for the project (inside web_tic_tac_toe), but also its dependencies and the dependencies of those dependencies. For example, my web Tic Tac Toe game depends on my custom HTTP server (inside of com/omarnyte), and the server depends on the org/json library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYHDKOz4mZQ1A-LV74zPpA.png" /></figure><p>Creating a JAR is relatively simple:</p><pre>jar cf &lt;jar-file-name<em>&gt; &lt;</em>input-file(s)&gt;</pre><p>As you can probably imagine, though, it can quickly become unmanageable to create a JAR from more than a couple of input files. For that reason, you’re more than likely to use a build automation tool.</p><h3>Building v. Compiling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDNtuBU4XboVchu0hX1PJQ.jpeg" /></figure><p>As mentioned above, compiling involves using javac to convert .java files into .class files. Building, however, accomplishes much more. On top of compiling (which usually includes both source code and test code), building also includes running tests, packaging applications, and potentially deploying to a repository like Maven or Clojars.</p><p>Although it’s good practice for small toy projects, it’s unlikely that you’ll be compiling files yourself with javac or creating jar files with jar. Instead, build automation tools help manage everything from naming and versioning to compiling and publishing. They typically allow customizing every imaginable aspect of your project so that you don’t have to do it by hand.</p><p>Although build tools help you focus on writing code, you probably won’t be able to get away with not knowing much about the Java platform for very long. Creating a single, standalone Java project without any external dependencies keeps you from needing to configure too much of your project. But, because we are developers who write code likely to be consumed by others (even our future selves), it’s best to take the time to understand how a platform handles the code that others will eventually use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15038a4993d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing My Developer Life]]></title>
            <link>https://medium.com/@omarnyte/optimizing-my-developer-life-31aedbb464f9?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/31aedbb464f9</guid>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Fri, 05 Oct 2018 17:44:04 GMT</pubDate>
            <atom:updated>2018-10-05T17:44:04.403Z</atom:updated>
            <content:encoded><![CDATA[<p>This week I made two major decisions that I am hoping will help me increase my productivity as a software developer. First, I began the week (as well as the month) with a commitment to migrate from VSCode to Vim. Second, I decided to take a dive into continuous integration by building and deploying a relatively simple <a href="https://github.com/omarnyte/web-tic-tac-toe">Tic Tac Toe game</a> served on my custom <a href="https://github.com/omarnyte/http-server">HTTP Server</a> using Travis CI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gD1WcXaSp-QFz0UYyqZjKg.jpeg" /></figure><p>As expected, investing in these tools caused a decline in my productivity during the week. Upon reflection, I think that both have been worthwhile investments that will require more time to master before fully paying off.</p><h3>Vim</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1ebBdjloi5HABcKYTLbBA.png" /></figure><h4>Setting Up</h4><p>I expected the major pain point in my transition to Vim to revolve around having to frequently look up commands or operator-motion combinations in the middle of an epiphanic flash of code writing. Instead, my transition started off with painless learning followed by painful setup followed by even more painless learning.</p><p>Vim makes it quick and easy to pick up the fundamentals of the text editor without having to leave your terminal. By simply typing the vimtutor command, you get access to a seven-lesson introduction that can be completed in about 30 minutes. The main takeaway from the tutorial should be that the learning doesn’t stop there. The relatively few operations and motions that you learn can and should be combined to create custom, complex combinations that could never be created so effortlessly in any other text editor.</p><p>One of the primary benefits of learning Vim is that it can be found on all Unix-based systems, allowing you to edit files while accessing a computer via SSH. With such out-of-the-box usability, I assumed that I’d be able to begin enjoying Vim without spending much time configuring my .vimrc file. An insightful <a href="https://medium.com/actualize-network/how-to-learn-vim-a-four-week-plan-cd8b376a9b85">introduction to V</a>im I stumbled upon also suggested using Vim with minimal configuration and no plugins for the first week. I definitely felt short of that goal.</p><p>After going through the tutorial a couple of times over the weekend, I wanted to dive right in with my task for Monday — publishing my HTTP Server to the clojars repository. I had initially failed to package any of my classes in the project. This meant that after publishing the project, I could successfully install it as a dependency on a Clojure project, but I couldn’t actually access or make use of any of the classes. Packaging my classes required moving a lot of files and directories.</p><p>With a clear goal in mind, I wanted to — as much as possible — practice Vim without any plugins. Unfortunately, this proved difficult to accomplish alongside this goal. If you search for “vim directory navigation”, most of the results demonstrate how to navigate <em>within</em> a file. That’s already information that you can obtain from vimtutor. Without a plugin, it seemed like I’d be better off navigating and altering my directories on the terminal. I knew that my productivity would take a dive when starting off with Vim, but I really needed the visual feedback when structuring my directories to reflect my package structure.</p><p>Instead, of a full dive into Vim, I ended up adding Vim keybindings to VSCode. Although this felt like cheating at first, I still practiced a lot of the commands that I know I’ll be using once I conquer file navigation (either natively or with a plug in). For example, I avoided navigating between split windows or tabs with my mouse, and I instead relied on the keyboard commands to make that happen.</p><h4>Debugging</h4><p>While not exactly “debugging”, I spent significantly less time researching Vim commands than I originally expected. This resulted partially from my intentional use of the most basic commands simply to get myself accustomed to them. Sure, typing 10G could take me to the beginning of the 10th line on a file, but I really needed to practice getting there using to the j and k vertical motion commands. So while I understood that there must be more efficient ways to accomplish something that took far too many keystrokes, I wanted to make sure that the most basic commands felt intuitive and wouldn’t require looking down at the keyboard.</p><p>Many of the solutions I found when I did look up a shortcut involved mapping my own shortcuts. As excited as I am about getting to that point, I still want the most basic commands to feel completely intuitive before mapping those shortcuts.</p><h4>Forecast on Productivity</h4><p>Before weighing the success of my less than complete transition, I should probably reflect on my reason for wanting to transition to Vim in the first place.</p><p>As I mentioned above, Vim’s ubiquitous presence makes it a crucial skill to possess. I’ve been thinking about jumping into a Raspberry Pi project. I’ve attended a few meetups where we mob programmed some simple projects (e.g. blinking an LED light; playing a sound), but I haven’t had the opportunity to work on a project alone. During the meetups, we inevitably had to edit some scripts in order to accomplish our project’s goal. Every time, editing with Vim was fastest way to make those changes.</p><p>I’ve also spent enough time programming to realize just how much more time I spend reading and editing code rather than writing code. When implementing design patterns, I often repeat a task many different times across many different files. Vim excels at this task, but only when you’re already familiar with the operations and motions that can condense a repetitive task into a few keystrokes.</p><p>Because I’ve fallen into the habit of refactoring my code after writing tests, I can tell that Vim will help me speed up the refactoring. Unfortunately, the high learning curve led me to hold off on a complete transition before attempting to accomplish complex refactoring patterns.</p><h3>Travis CI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*IP7q20j8JJK6dB2Jy1pcig.png" /></figure><h4>Setting Up</h4><p>Prior to building and deploying my Tic Tac Toe application using Travis CI, I had a introduction to CI/CD using Jenkins. During a two-week workshop introduction to DevOps, I deployed a full stack web application to a number AWS services. Because of the complexity of both AWS and Jenkins — and because of the introduction to a lot of the CI/CD vocabulary — I feel like I absorbed a lot of the high-level concepts surrounding the motivation for these technologies, but I felt lost with the practical details involved in getting everything set up.</p><p>In contrast to Jenkins, Travis was incredibly simple to set up. After creating an account and enabling my Tic Tac Toe repo to integrate with Travis, I simply added a .travis.yml with the following line:</p><pre>language: clojure</pre><p>While my initial build failed, it wasn’t very difficult to tell why or to fix the issue. That naturally leads into the next section.</p><h4>Debugging</h4><p>My first few builds failed because Travis defaults to building JVM projects with JDK8. My Java server had been compiled with JDK10. Because of the discrepancy, Travis would not let my Clojure project access classes imported from my HTTP Server. The Travis tutorial on <a href="https://docs.travis-ci.com/user/languages/clojure/">building Clojure projects</a> conveniently linked to a separate tutorial detailing how to <a href="https://docs.travis-ci.com/user/reference/trusty/">configure an Ubuntu Trusty build environment</a> with a different JDK version. Getting my build to work took only three additional lines:</p><pre>language: clojure</pre><pre>dist: trusty<br>sudo: false<br>jdk: oraclejdk10</pre><p>Deploying to Heroku was also very painless (although getting the app to work properly on Heroku posed its own problems). Following the official <a href="https://docs.travis-ci.com/user/deployment/heroku/">tutorial</a> required adding only four more lines of code to my .travis.yml:</p><pre>language: clojure</pre><pre>dist: trusty<br>sudo: false<br>jdk: oraclejdk10</pre><pre>deploy:<br>  provider: heroku<br>  api_key:<br>    secure: [SECURE API_KEY]<br>  app: toe-tac-tic</pre><p>Throughout the week, there wasn’t too much need to look beyond the official Travis tutorials when I encountered an issue specific to Travis.</p><h4>Forecast on Productivity</h4><p>My biggest takeaway from this week regarding CI/CD was that setting up a CI/CD pipeline requires knowing a lot about the language on which the app is built, especially when it concerns version compatibility. Although setting up Travis to build or deploy took only a few minutes and even fewer lines of code, I spent hours researching Java error codes, and I often failed to understand whether those errors arose from my Java server or my Clojure Tic Tac Toe program. This lack of understanding didn’t stem from Travis, and I’m not sure that the platform could have done much more to help me figure it out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31aedbb464f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Nice to Your Future Self]]></title>
            <link>https://medium.com/@omarnyte/be-nice-to-your-future-self-9de27e2373b5?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de27e2373b5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 17:00:54 GMT</pubDate>
            <atom:updated>2018-09-28T17:00:54.312Z</atom:updated>
            <content:encoded><![CDATA[<p>During the past two weeks, I’ve been combining my custom <a href="https://github.com/omarnyte/http-server">HTTP server</a> (written in Java) and a <a href="https://github.com/omarnyte/Tic-Tac-Clojure">Tic Tac Toe game</a> (built in Clojure). Essentially, I want to create a frontend version of the game that relies on an API served by my HTTP server. That way, the frontend contains only logic for receiving input and and rendering the state of the game.</p><p>I’ve created a few full stack projects before, but I’ve often completed them in a short amount of time when design decisions are still fresh in my mind. In those cases, it was relatively easy to remember that some function behaved strangely or would break if I passed in a certain argument. I hand’t yet read <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a>, so while I knew that my code was fragile, I didn’t always know the best way to improve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWhDB3ZcV4ySIpbyXE9IHA.jpeg" /></figure><p>Now that I’ve revisited a codebase that I wrote months ago, I realize that some of the choices I made slowed down the development of my new project. When reflecting on how I can avoid those setbacks in the future, I realized that it came down to one simple rule: be kind to your future self.</p><h4>Make sure that your variable and method names don’t lie</h4><p>This probably sounds intuitive, but it’s so incredibly easy to write methods that only lie a little. For example, in my frontend JavaScript code, I set the following as a callback to an even listener waiting for the user to select a space on the board.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79d5dac1c348aafd309d4af8783d14b9/href">https://medium.com/media/79d5dac1c348aafd309d4af8783d14b9/href</a></iframe><p>That method lied to me because it wasn’t actually sending a request. It was actually doing two things. First, it was determining whether the selected space contained the “marked” class. It would send the request only if it did not contain it. Otherwise, it would do nothing.</p><p>When debugging later, I shouldn’t have been surprised when I manually called that method and nothing happened. After all, I had written that tiny method hours earlier. To make my method tell the truth, I first moved the check for the “marked” class into a method called #shouldMakeMove. This move has the added benefit of making the move request based on a truthy condition rather than a falsey condition, making the entire method easier to read. After that change, I switched the name of the method to #handleSpaceClick. Together, those changes left the method looking like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/340bc3399c2905b873f896aa52bb283b/href">https://medium.com/media/340bc3399c2905b873f896aa52bb283b/href</a></iframe><p>Just a bit later, I ended up adding two new conditions to #shouldMakeMove. Every additional condition makes it less and less likely that the method is actually sending a request. It would have been a pretty blatant lie to tell ourselves (and anyone else relying on the code) that the method actually made a request.</p><h4>Write methods with few (or no) arguments</h4><p>When I first built my Server class, I needed to pass in a port number, a Router instance to the class constructor. Those were the basic requirements to read and respond to an incoming request. As my Server grew in complexity, this list became longer. When I wanted to log every incoming Request and outgoing Response, I had to pass in an instance of Logger. When I protected routes with authentication, I needed to pass in an instance of Authenticator. When I wanted to add support for CORS, I knew that I‘d have to find a way to avoid passing in five arguments to Server’s constructor.</p><p>After a bit of research, I came across the <a href="https://refactoring.guru/design-patterns/command">Command</a> pattern, which seemed to address the problem I was facing. After an hour-long spike, I realized that it didn’t quite enable me to pass in a single object regardless of how many new pieces of middleware I added to my Server. After some additional research, I encountered the <a href="https://refactoring.guru/design-patterns/chain-of-responsibility">Chain of Responsibility</a> pattern, which solved my exact problem.</p><p>While it’s easy to go down a rabbit hole of design patterns, it’s important to recognize when that time is worth the investment. Suddenly I had no need to touch the code inside of the Server class when I added support for CORS.</p><p>Although the decision to combine all of the Middleware classes into a single parameter made my life building the HTTP Server easier, I didn’t stop to think about how anyone (i.e. me) using my server would implement middleware. Perhaps they wouldn’t want or need a Logger, Authenticator, or CORS support. Which leads me to my next point:</p><h4>Make optional arguments optional</h4><p>As part of the development of my Web Tic Tac Toe, my first feature story simply involved starting the server using only backend, Clojure code. I purposely avoided configuring anything for Tic Tac Toe. Because of the way I set up my Server class, though, I had to extend an instance of Middleware and pass it into the Server constructor. This detour unnecessarily slowed down my process because the sample Middleware class I constructed simply returned whatever it took in.</p><p>Though this example feels relatively trivial, it really helped frame my mindset while coding. For the rest of the project, I thought not just about how I’m currently building my project, but also about how someone else would make use of it.</p><h4>Blog about your progress</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKwbmlz8ejUth6WpPmrHhQ.jpeg" /></figure><p>I’ll admit that I’ve fallen behind on my goal of two weekly blog posts. By being kind to my future self, though, I leave myself more time for blogging!</p><p>In reality, this advice extends beyond being kind to yourself. If you’re struggling with an algorithm, design pattern, or configuration, it’s incredibly likely that someone else has, too. At some point, you’ll probably end up searching for a solution that someone has taken the time to explain. Pay it forward!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de27e2373b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflecting on The Secrets of Consulting]]></title>
            <link>https://medium.com/@omarnyte/reflecting-on-the-secrets-of-consulting-cad42347ddc8?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad42347ddc8</guid>
            <category><![CDATA[software-consulting]]></category>
            <category><![CDATA[consulting]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 17:02:57 GMT</pubDate>
            <atom:updated>2018-09-27T17:02:57.400Z</atom:updated>
            <content:encoded><![CDATA[<p>During the past week, I’ve been reading Gerald M. Weinberg’s <a href="https://leanpub.com/b/secretsofconsulting">The Secrets of Consulting</a>. Weinberg pretty consistently writes in paradoxes, providing one absolute rule before contradicting it with another absolute rule just a few pages later. When he doesn’t contradict his previous rules, he appends corollary rules that often nullify the original rule he presented. He can also conveniently recall anecdotes for many of his rules, and he has a suspiciously sharp talent for remembering every word of a conversation that he had in those anecdotes.</p><p>Despite my qualms with his writing style, I can’t help but compare some of his takeaways to my previous job. Before starting my career as a software developer, I worked as legal representative advising and representing pro-bono clients in immigration cases in New York City. Though I was not a lawyer, I did receive an accreditation from the Department of Justice to represent clients in affirmative cases (meaning that I would help with cases that did not require going in front of an immigration judge). I conducted that work while on a two year fellowship.</p><p>Two chapters in particular stood out to me because they applied to my legal work in New York and because I can already see how I’ll use that experience when working with clients as a software crafter.</p><h3>Seeing What’s There</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSznei-sZFAv1TukPiZAqw.jpeg" /></figure><blockquote>Keep it simple and not too detailed; you’re a consultant, not a district attorney (58).</blockquote><p>This piece of advice truly resonates with me simply because of the astonishing complexity of immigration law. While I had a background in the law from an immigration law class and a senior thesis in college as well as month-long legal training, I continued to learn new aspects of the law until the last day of my job. It didn’t help that many of my cases overlapped with criminal law (of which I had very little knowledge and for which I could not legally provide advice).</p><p>Communicating the complexity of the law in simple terms took a lot of practice. If I left in too many details, a client might not understand why they may be ineligible for an immigration benefit, and they could potentially seek help from someone else until a predatory lawyer told them what they wanted to hear. If I left out too many details, I risked diminishing the importance of the advice, and a client with a criminal history might travel outside of the country and face deportation upon their return.</p><p>With consulting, I can already picture how I’ll apply this advice. The stakeholders that I’ll communicate with may not have a technical background to answer meticulous, technical questions. If they’ve called us in because they need additional support on their software, they may not have the time to answer those questions.</p><p>In essence, I think that Weinberg’s rule above implicitly dictates another: <em>you’re not a district attorney; you’re on the client’s side</em>. Because we’re both on the same team, we might have differing but complementary skills. My job will not be to teach the stakeholder every one of my skills. Rather, I’d asses the specific situation and determine which pieces of my experience would help them solve their problem. That implication naturally leads to his next rule:</p><blockquote>Study for understanding, not for criticism (59).</blockquote><p>As an immigration representative, I often worked with vulnerable clients. Many had been victims of crimes, including domestic violence. Many of these clients were eligible for immigration relief because of their history, but applying for that relief often required them to cooperate with law enforcement in order to prosecute the suspect. Many would also have to revisit painful moments in their lives in order to draft detailed affidavits.</p><p>Certain criminal histories also prevent individuals from applying for a number of immigration benefits. Many of their crimes occurred during a time when the client was undergoing extreme circumstances, often as a result of lacking legal immigration status.</p><p>Prodding into their histories understandably made clients uncomfortable, so it was always necessary to clarify why we had to ask these questions. We gained nothing from criticizing the client’s background, but we gained everything from understanding it.</p><p>Though the stakes are certainly different in a software consultancy, this rule came as a bit of a surprise to me before reading this book. I would have assumed that clients hire consultants precisely for the criticism. After all, their relatively neutral perspective could provide new insights that the internal team could not.</p><p>However, I failed to immediately see that a client who calls in a consultant already understands that something has gone wrong or could be improved. Admitting that their team has gotten to that point merits understanding and compassion. Criticism might shut down future calls for help.</p><blockquote>Clients always know how to solver their problems, and always tell the solution in the first five minutes (67).</blockquote><p>I’ll admit that the dynamic this rule suggests is completely new to me. In my experience, clients often <em>think </em>they know the solution to their problems. But even I often didn’t know the solution until I consulted with my supervising attorney. In fact, one of the biggest challenges I faced during my fellowship was combatting incorrect or misleading immigration information. It didn’t help that the information often came from predatory lawyers.</p><p>I am somewhat doubtful about this rule. If this were true, then our role would be less of a consultant and more of a contractor who has been hired to deliver a task determined in five minutes. Perhaps my thought about this rule might change when I begin working with clients, so I feel the need to point it out to remind myself to revisit the rule.</p><h3>Seeing What’s Not There</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlId9_uhJPfTFKFRI2ACYw.jpeg" /></figure><blockquote>If you cant think of three things that might go wrong with your plans, then there’s something wrong with your thinking (81).</blockquote><p>As a legal representative, it wasn’t hard to think of three things that could go wrong because things often did go wrong. Here are three examples:</p><ul><li>At a citizenship interview, an immigration officer could remind my client — and inform me — about an an undisclosed, surprise arrest in the client’s past.</li><li>At a green card interview, an immigration officer could could remind my client — and inform his current wife — about an an undisclosed, surprise marriage in the client’s past.</li><li>A client with a shaky immigration case and who I’d previously met with in New York might call me from another country.</li></ul><p>I like this piece of advice because in my case, it was one I already followed and found to be grounded in cynical realism. To help come up with three things that might go wrong, Weinberg suggests exploring extremes (“what if we could manufacture these items in zero gravity?”). In my case, it didn’t take long before my view of “extreme” became fairly realistic.</p><p>Because of the nature of building software — as opposed to representing humans — I initially didn’t find this rule very applicable to the work I’ll be doing with clients. I often consider software to be purely logical. This way of thinking leaves out the driving force behind software: humans. The human writing the code has a lot of subjective influence over the application. They can choose terrible variable names that make the code difficult to understand, or they can take the time to refactor their code with a design pattern that makes it easy to revisit and revise the code at a later time. In both cases, the code might work precisely as expected, but it may not easily lend itself to extension or maintainability. When considering what might go wrong, I think that it’ll be important to focus on human actions.</p><p>Though I find Weinberg’s writing style and delivery somewhat haughty, his litany of rules and secrets do contain advice that I’ll be able to apply to my client work soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad42347ddc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Java I/O Streams By Writing Your Own]]></title>
            <link>https://medium.com/@omarnyte/understand-java-i-o-streams-by-writing-your-own-2981f9a2d89?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/2981f9a2d89</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 21:00:18 GMT</pubDate>
            <atom:updated>2018-09-18T15:40:00.884Z</atom:updated>
            <content:encoded><![CDATA[<p>Previously, I wrote an article outlining what I learned by <a href="https://medium.com/@omarnyte/what-i-learned-writing-my-own-mocks-4eb7c40ca289">writing my own mocks</a> without using a mocking library. After writing even more mocks to test my <a href="https://github.com/omarnyte/http-server">HTTP server</a> client thread, I can now add a greater understanding of Input and Output streams to that list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-0hnOaMYebyD_XFniIzZA.jpeg" /></figure><p>Testing my server’s client thread requires mocking three things: a socket, a router, and a middleware chain. The socket links my server to a client, reading the request it receives from the client and writing a response back to it. After parsing the incoming request and creating a Request instance, every Request goes through a middleware chain (which includes logging and authenticating every Request). The router then sends the final, possibly alteredRequest to the proper Handler, which creates and returns aResponse object. Before writing the Request object back to the client, the Request goes through the middleware chain, this time for appending the appropriate <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing Sharing (CORS)</a> header and for logging. After formatting the Response object and converting it to bytes, the thread finally uses the socket to write the response to the client.</p><p>Mocking the router and middleware is a relatively simple task. For the router, we simply create a MockRouter that extends Router. Its constructor receives an expected Response object, which its one public #getResponse method can return. For the middleware, we similarly create a MockMiddleware class which extends Middleware. As with the MockRouter, we can pass in an expected Response to the constructor, which the #applyMiddleware method can return.</p><p>These hard-coded Requests and Responses decouple our client thread test from the function of an actual router or any number of actual Middleware instances. If we want to ensure that multiple middleware classes alter a Response before being written to the client, we can create and link three instances of MockMiddleware, each returning a completely different Response before running assertions against the Response returned by the last in the chain. This prevents use from using an actual implementation of Middleware, which could be broken or — more likely — could change in the future. This client thread unit test would become too fragile if it depended on any number of Middleware instances.</p><p>Mocking the socket isn’t quite as easy. For one, it’s a matter of mocking a core Java library. Up until this point, I had only mocked classes that I had written myself. Second, my client thread wraps the InputStream returned by #getInputStream in an InputStreamReader wrapped by a BufferedReader. I felt like I was a few levels removed from the code I wanted to mock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2bYkZITbrzFF_K8xV2Zxw.jpeg" /></figure><p>My code signaled to me that I’d have to run assertions against the InputStream and OutputStream returned by #socket.getInputStream and #socket.getOutputStream respectively. Unfortunately, the #write method in an OutputStream does not return anything. To make matters more complicated, constructing a Socket with a stream as a parameter was deprecated. Although I spent some time trying to avoid it, I realized that mocking a socket would also require mocking InputStream and OutputStream.</p><h4>MockInputStream</h4><p>Creating your own implementation of InputStream isn’t completely outlandish. The <a href="https://docs.oracle.com/javase/10/docs/api/java/io/InputStream.html">documentation</a> states that:</p><blockquote>Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.</blockquote><p>That method is the abstract method #read. Its documentation states that:</p><blockquote>Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.</blockquote><p>In order to read from the stream, we’d need somewhere from which to read. Just as with MockRouter and MockMiddleware, a mock constructor is the perfect place to inject an expected object. In this case, constructing a MockInputStream with an array of bytes gives us precisely what we need. By saving the inputBytes as an instance variable, the #read method can pop and return the first byte in the array. To ensure that we meet the specification above, we can check the array length and return -1 if it’s already empty. The InputStreamReader (wrapped in a BufferedReader) reading from the MockInputStream will take care of stopping when it receives a -1.</p><p>All together, the code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a81c69267f548c80088de3903328c99c/href">https://medium.com/media/a81c69267f548c80088de3903328c99c/href</a></iframe><p>If you’re familiar with other types of InputStreams, then you might have noticed that we’ve essentially created our own implementation of <a href="https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayInputStream.html">ByteArrayInputStream</a>.</p><h4>MockOutputStream</h4><p>As above, the <a href="https://docs.oracle.com/javase/10/docs/api/java/io/OutputStream.html">documentation</a> also suggests that implementing your own OutputStream is fairly standard.</p><blockquote>Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.</blockquote><p>That method is the abstract #write(int b) method. As mentioned above, this method is void, so we can’t actually run assertions against it. To get around that, we’ll create and expose a method unique to MockOutputStream: #getWrittenBytes. Because this method will ultimately return something, it will be possible to run assertions against it.</p><p>Because two methods (one setting and one getting) will be making use of an object, this class will also make use of an instance variable. In this case, we’ll avoid the primitive array appending and simply instantiate a ByteArrayOutputStream to an instance variable. Now, whenever the socket writes a byte, it can write it directly to the ByteArrayOutputStream instance. Since the method is void, the #write method has no other functionality.</p><p>All together, the code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d56b975343c436a49a1a0cb6b41382/href">https://medium.com/media/52d56b975343c436a49a1a0cb6b41382/href</a></iframe><h4>MockSocket</h4><p>With the two requisite mocks out of the way, the MockSocket seems quite simple. It’s two mocked methods will simply return mock instances of InputStream and OutputStream. To run assertions against whatever the socket writes, we create and expose the #getWrittenString method, which gets MockOutputStream‘s written bytes and converts them to a String.</p><p>All together, the code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e03a3bdcff8ea4eab4de222c59a6640c/href">https://medium.com/media/e03a3bdcff8ea4eab4de222c59a6640c/href</a></iframe><p>Do note that the type for mockInputStream (line 9) must be MockOutputStream and not OutputStream. This is because line 27 calls #getWrittenBytes — a method that exists only in the mock implementation and not any other implementation of OutputStream.</p><p>When testing the client thread (or any class that uses an instance of the Socket class), you’ll know be able to control what a test client “sends” the server (as an array of bytes). Similarly, you’ll be able to run assertions against what the server “sends” (conveniently as a String, but you can alter#getWrittenString method in MockSocket to return a ByteArrayOutputStream or a byte array).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2981f9a2d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POST, PATCH, and PUT: What’s the Difference?]]></title>
            <link>https://medium.com/@omarnyte/post-patch-and-put-whats-the-difference-f455fc4d3458?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/f455fc4d3458</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 17:08:07 GMT</pubDate>
            <atom:updated>2018-09-10T17:08:07.450Z</atom:updated>
            <content:encoded><![CDATA[<h4>And why does it matter?</h4><p>If you’ve used or built a RESTful API, you’ve very likely dealt with GET and POST requests. You’ve probably also dealt with PUT requests. If you’ve encountered PATCH requests, you probably asked yourself how it differs from POST or PUT. The three types of request all contain request bodies, but the similarities start to get more fuzzy from there. Here are some key differences.</p><h4>POST</h4><p>POST requests essentially hand over control to the server, allowing it to decide exactly how resources will be created. That is, the server can decide which fields in the request body to accept, what file type (if any) will be created, and what URI will point to the new resource. As <a href="https://tools.ietf.org/html/rfc2616">RFC 2616</a> puts it:</p><blockquote>The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI.</blockquote><p>Typically, this this means that POST requests are directed at an API endpoint.</p><p>POST requests are necessarily not idempotent. Consider the example below. If we want to create a new Pokemon, we’d send a POST request to an the api/pokedex API endpoint (just note that it’s not a real endpoint). We’d send up some required fields: the Pokemon’s name, type, and array of moves.</p><pre>POST /api/pokedex HTTP/1.1<br>Host: pokemon.com<br>Content-Type: application/json</pre><pre>{<br> &quot;id&quot;: 981<br> &quot;name&quot;: &quot;Eighttales&quot;,<br> &quot;type&quot;: &quot;ice&quot;,<br> &quot;moves&quot;: [<br>    &quot;quick attack&quot;,<br>    &quot;gust&quot;<br>  ]<br>}</pre><p>You can imagine sending the request above twice. While you may get a successful response the first time, the server may send an error the second time. Perhaps the server doesn’t allow more than one Pokemon to have the same name. If the server does respond successfully, the resource created by the the second request would likely contain a different, unique ID and/or URI.</p><h4>PUT</h4><p>Rather than targeting an endpoint, PUT targets either an existing resource that is to be updated or the location where a new resource will be created. In both instances, the request entity must include a full representation of the resource.</p><p>PUT is a necessarily idempotent operation. Whether a request targets an existing or a nonexistent resource, the server should respond with the same content after every identical PUT. For example:</p><pre>PUT /pokedex/130.json HTTP/1.1<br>Host: pokemon.com<br>Content-Type: application/json</pre><pre>{<br>  &quot;id&quot;: 130<br>  &quot;name&quot;: &quot;Jirados&quot;,<br>  &quot;type&quot;: &quot;water&quot;,<br>  &quot;moves&quot;: [ <br>    &quot;splash,<br>    &quot;gust&quot;<br>  ]<br>}</pre><p>If a resource with the URI /pokedex/130.json already exists, the content of the resource will be replaced by the body of the request above. If it did not exist, a resource will be created, and it will contain the content of the request body. No matter how many times we send the request, the server should respond with the same body every time, and the resource should not continue to change.</p><h4>PATCH</h4><p>PATCH probably continues to be the most misunderstood of the requests. It’s relatively new (it’s <a href="https://tools.ietf.org/html/rfc5789">RFC</a> was written in 2010), and it’s often and incorrectly handled the same way that POST or PUT is used. Unlike PUT, the URI of a PATCH request cannot point to a resource that doesn’t exist.</p><p>The most important thing to keep in mind about PATCH is that the request entity should not contain the partial or full representation of an existing resource. <a href="https://tools.ietf.org/html/rfc5789">RFC 5789</a> explains what should be sent instead:</p><blockquote>With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.</blockquote><p>Those set of instructions are called patch documents, and they’re based on the type of resource trying to be PATCHed. For JSON, the entity can contain a <a href="http://jsonpatch.com/">JSON Patch</a> document(Content-Type: application/json-patch+json) or a <a href="https://tools.ietf.org/html/rfc7386">JSON Merge Patch</a> document (Content-Type: application/merge-patch+json).</p><p>Although a JSON Patch document is JSON, it’s a specific type of JSON. Specifically, a JSON Patch document must be an array of comma-separated JSON objects, each of which contains a valid operation (&quot;op&quot; ) and path. For example:</p><pre>[<br>     { &quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/a/b/c&quot; },<br>     { &quot;op&quot;: &quot;add&quot;, &quot;path&quot;: &quot;/a/b/c&quot;, &quot;value&quot;: [ &quot;foo&quot;, &quot;bar&quot; ] },<br>     { &quot;op&quot;: &quot;replace&quot;, &quot;path&quot;: &quot;/a/b/c&quot;, &quot;value&quot;: 42 },<br>     { &quot;op&quot;: &quot;move&quot;, &quot;from&quot;: &quot;/a/b/c&quot;, &quot;path&quot;: &quot;/a/b/d&quot; },<br>     { &quot;op&quot;: &quot;copy&quot;, &quot;from&quot;: &quot;/a/b/d&quot;, &quot;path&quot;: &quot;/a/b/e&quot; }<br>]</pre><p>The restrictions on the document ensure that the server receives concrete instructions that specify how a resource should be updated.</p><h4>Why does it matter?</h4><p>Understanding the different use cases for these methods can help create efficient applications. For example, consider a multi-thousand line JSON resource. If a client uses a PUT request to update a single line in the resource, the entire resource would need to be included in the entity. To avoid updating an old version of a resource, the client would likely first make a GET request to the resource. Suddenly, a one-line change means that the enormous resource must be transferred between the server and client three separate times. Supporting the less-understood PATCH would reduce the size of each request and response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*elG08okO7F82WkpUwlKDPQ.png" /><figcaption>The <a href="https://pokeapi.co/">pokeapi</a> response to a GET request to a single Pokemon contains nearly 10,000 lines of JSON!</figcaption></figure><p>HTTP works as the language of the web because it has been standardized. Clients and servers can communicate because they both use the same, standard language. When servers stray away from the accepted standards, users have to spend additional time reading documentation in order to understand how the server chose to interpret the protocol. Following the accepted standards ensures that everyone continues to communicate with the same language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f455fc4d3458" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding The Time to Refactor Code]]></title>
            <link>https://medium.com/@omarnyte/finding-the-time-to-refactor-code-83baf5cde098?source=rss-1649520c5307------2</link>
            <guid isPermaLink="false">https://medium.com/p/83baf5cde098</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omar De Los Santos]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 21:00:11 GMT</pubDate>
            <atom:updated>2018-09-09T21:00:11.614Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that I’ve been building an <a href="https://github.com/omarnyte/http-server">HTTP Server</a> with an agile methodology for the past two months, I’ve increasingly appreciated the time I’ve taken to refactor my code. Putting in the effort to rename ambiguous or confusing variables, shortening methods, and injecting mockable dependencies into class constructors has helped me quickly add functionality to to my server without causing too many unexpected side effects.</p><p>Admittedly, I am still struggling to always find the time to refactor, especially when stories are beginning to pile up in my backlog. Here are a few of the strategies I’ve been integrating during the past few weeks.</p><h4>Don’t consider a feature complete until it’s refactored</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5exCz3cRM-blywECqLzXw.jpeg" /></figure><p>I still find it a little difficult to strike a balance between refactoring a class to death and the idea of <a href="https://www.martinfowler.com/bliki/Yagni.html">“You’re Not Gonna Need It”</a>. When deciding how much to refactor after I’ve implemented a feature, I try to keep two things in mind:</p><ul><li>Will the change that I’m considering make it easier to understand the code? If so, apply the change. Whether I’m expecting to revisit the code at some in the future — or if I want my mentors or fellow apprentices to look over my code — I want to make it as easy as possible for everyone to understand my code. If I’ve overly abstracted a concept in anticipation of a feature that has not yet been implemented, it’s going to make the code difficult to understand.</li><li>Will the change that I’m considering make it easier to test the code? If so, apply the change. These changes are worthwhile because they help</li></ul><p>When creating estimates for your features, you should always anticipate refactoring before and after the feature has been implemented. That way you’re not out of time and pushing ugly, fragile code.</p><h4>When diving into a new codebase (or extending/modifying code you previously wrote), start off by refactoring the code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8A6fIOdry412TCeDGB7Eg.jpeg" /></figure><p>When I began working on my HTTP Server, I had only been working with Java for a few days. Naturally, I hadn’t been exposed to the language’s best practices. When you revisit old code, you’ll almost inevitably be a wiser developer. You’ll likely have been exposed to new techniques that could help clean up your code. If you passively encountered a technique in a blog post or a talk and never had the opportunity to apply it, this would be the perfect time. You don’t have to rely on dummy or irrelevant examples because you already have a real-world use case.</p><p>By beginning a feature by refactoring existing code, you also force yourself to understand how the code works with the added benefit of simultaneously cleaning the code. I like to think of this approach just as you would tearing apart a computer and putting it back together. You might not have the expertise, time, or capacity to understand how every single piece works inside, but you might as well dust off the inside while the cover is open.</p><p>Of course, this approach assumes that the code base contains robust tests that quickly tell you whether or not your refactoring broke the program. If the program contains no tests, you can simultaneously familiarize yourself with the code base and ensure that you can safely refactor by writing those tests yourself.</p><h4>Expose yourself to new techniques</h4><p><a href="https://refactoring.guru/refactoring/catalog">Refactoring Guru</a> contains a fantastic catalog of common object-oriented design patterns and refactoring techniques. For the former, each pattern includes a real-world analogy to aid your understanding and both a pseudo and concrete implementation to help you visualize the result of the pattern. For the latter, you can browse techniques by code smells. While Refactoring Guru doesn’t provide a great way to quickly browse through design patterns, <a href="https://www.oodesign.com/">Object Oriented Design</a> contains brief summaries (separated by creational, behavioral, or structural patterns) for many of the same patterns.</p><p>I’ve been reading Martin Fowler’s <a href="https://martinfowler.com/books/refactoring.html"><em>Refactoring: Improving the Design of Existing Code</em></a> during the past few weeks. Don’t be fooled by the book’s first archaic example (a program to track video rentals). The substance of the book truly is timeless. The book is driven by examples beginning at the first page, so it’s a great reference for quickly applying a technique to your own codebase.</p><p>Though not at all exclusively populated with refactoring patterns, the <a href="https://www.dailynow.co/">Daily Now Chrome extension</a> aggregates hundreds of technical blog posts, many of which introduce readers to new techniques. The extension replaces your new tab window, so it’s a wonderful way to quickly to stay up-to-date while taking a break from coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83baf5cde098" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>