<?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 James Marks on Medium]]></title>
        <description><![CDATA[Stories by James Marks on Medium]]></description>
        <link>https://medium.com/@jamesmarks?source=rss-e6e26cd79b48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l12zMQ4tjWPy1hO0.jpg</url>
            <title>Stories by James Marks on Medium</title>
            <link>https://medium.com/@jamesmarks?source=rss-e6e26cd79b48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:25:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jamesmarks/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[How to (almost) Never Use Another `for` or `while` Loop in Javascript]]></title>
            <link>https://medium.com/@jamesmarks/how-to-almost-never-use-another-for-or-while-loop-in-javascript-c29657191dc2?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29657191dc2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 00:35:18 GMT</pubDate>
            <atom:updated>2023-03-29T00:35:18.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>Its easier than you think to eliminate for loops and write more powerful code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mJKGTIzZ-34x7Cs" /><figcaption>Photo by <a href="https://unsplash.com/@yogendras31?utm_source=medium&amp;utm_medium=referral">Yogendra Singh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have taken a typical coding course in high school or college in the past decade, you were likely taught the basic programming structures, such as if, for, while and other standard structures.</p><p>What you were probably not taught is that none of these are necessary — particularly in modern Javascript (and thus Typescript).</p><p>There are powerful alternative ways to approach these same problems that can make your code significantly more resilient.</p><h3>What’s Wrong with `for` and `while`?</h3><p>By themselves, for and while are fairly innocent. And once, long ago, when programming languages were in their infancy, these were also the only options for doing what they do.</p><p>They allow you to do the important work of processing your lists according to your business rules. When using them in small, bite sized pieces of code they’re normally quite harmless.</p><p>The problem with these structures is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Mutable">mutability</a>. When using these, you normally do so with the intention of transforming an array, either by changing it directly or by doing something with the data to create a new array or object.</p><p>If this was all that happened, everything might be okay. However, because you have created a mutable array or object outside of your for loop, you expose it to changes elsewhere in your code — and that’s where the damage begins.</p><p>When you work with other developers, and sometimes even with your future self, and a change needs to be made to code with a for loop to add support for new or changing business logic, the next person to touch the code tends to add new logic either inside the original loop (which is actually the better option) or by writing a whole new loop, or some other logic outside that makes additional changes to the original mutable variable you set up.</p><p>After this process repeats a few times, the code becomes overloaded with changes to one variable, almost always making it difficult to understand. If there are bugs, they’re difficult to trace.</p><p>As more changes need to be made, it becomes ever more difficult as reading and comprehending the existing code becomes a heavier and heavier cognitive load.</p><h3>What Should You Do Instead?</h3><p>The answer is in writing immutable, “functional style” code that leverages array prototype methods and other non-mutative strategies.</p><p>The Javacript Array prototype has several powerful non-mutative alternatives that you can use to loop over arrays and other array-like values.</p><p>There are three that you could be considered “all that you need”, and we will focus on these here.</p><ol><li>.map — Loops over an array, returning a new array. Typically the new array is a transformation of some sort from the original.</li><li>.filter — Loops over an array, returning a new array containing only values that match your criteria.</li><li>.reduce — The most intimidating, but possibly the most rewarding of these three essential methods. This loops over an array, allowing you to create something entirely new, step by step, that can be any data type you want, not only an array.</li></ol><blockquote><strong>Note</strong>: Via the .keys, .values, or .entries members we can also use these to process Objects that you are using as hashmaps and Javascript Map structures.</blockquote><h4>What are the Benefits:</h4><ul><li><strong>Immutability. </strong>You can do this by pattern at least, but can also be implemented with Object.freeze to be entirely certain.</li><li><strong>Better self-describing code. </strong>A new variable always needs a new name, which is an opportunity to be specific about what your code intends to do.</li><li><strong>Lower mental cost for future changes. </strong>Makes code easier to read, understand and change.</li><li><strong>Function composition and better extensibility. </strong>Functional style code is designed to be used with composition. <em>(</em><a href="https://www.freecodecamp.org/news/function-composition-in-javascript/"><em>Function composition</em></a><em> is beyond the focus of this article, but in short it is a powerful tool that is arguably more effective than OOP inheritance.)</em></li><li><strong>Testable. </strong>Since code is broken down into small distinctive tasks, you are more easily able to break it apart into smaller callable functions that can be protected from later damage with unit tests.</li></ul><h4>There ARE Some Drawbacks:</h4><ul><li><strong>Functional style can be more processor and memory intensive. <br></strong>You can get carried away always assigning new immutable values to new variables and use far more memory than typical non-functional code. <br>That said, if you’re using functional, it solves a lot of performance problems that you develop because a developer had a difficult time making effective changes to non-functional code.</li><li><strong>Can be unfamiliar at first to many developers… </strong>but then you can’t live without it. Once you get used to reaching for functional first and you have your head wrapped around the less familiar array prototype functions, you will begin to feel the difference in your ability to pump out software. You will produce higher quality product faster because you will have better tools for developing.</li></ul><h4>How to Change from for to Functional Array prototype Methods:</h4><p>The below examples are small due to space, and are too simple to fully showcase the benefit of using these alternatives.</p><p>You’re encouraged to try these strategies in your own code to see how they compare.</p><h4>Example 1:</h4><p>For this example contacts contains an array of database records including address, phone number, email and so on, but we’re just trying to export an email list to our email software as a CSV after displaying it.</p><p>Here’s the Original:</p><pre>const contactList = [];<br>for (const contact of contacts) {<br>  const newContact = `&quot;${contact.firstName}&quot;,&quot;${contact.email}&quot;`;<br>  console.log(newContact);<br>  contactList[contactList.length] = newContact;<br>}<br>await toCSV(contactList.join(&quot;\n&quot;));</pre><p>And here’s how this same code can be written without the for :</p><pre>const contactList = contacts.map((contact) =&gt; {<br>  return `&quot;${contact.firstName}&quot;,&quot;${contact.email}&quot;`;<br>});<br>console.log(contactList.join(&quot;\n&quot;));<br>await toCSV(contactList.join(&quot;\n&quot;));</pre><p>Not so tough, right?</p><h4>Example 2:</h4><p>Often we want to deal with only a subset of a list.</p><p>In this example, we look for invoices that are overdue and trigger an email to the payee.</p><pre>const today = new Date();<br>const lateInvoices = [];<br>for (const invoice of invoices) {<br>  if (!invoice.status === &#39;paid&#39; &amp;&amp; invoice.paymentDate &lt;= today) {<br>    lateInvoices.push(invoice);<br>  }<br>}<br>await sendInvoiceEmails(EInvoiceType.LatePayment, lateInvoices);</pre><p>And here’s an alternate way to write this:</p><pre>const today = new Date();<br>const lateInvoices = invoices.filter(<br>  (inv) =&gt; (!inv.status === &#39;paid&#39; &amp;&amp; inv.paymentDate &lt;= today)<br>);<br>await sendInvoiceEmails(EInvoiceType.LatePayment, lateInvoices);</pre><p>By now, you may have noticed that the code in the suggested array prototype style tends to be a little shorter, too.</p><h4>Example 3:</h4><p>In this example, we want to build some demographic statistics about students in a school — this could be for any reason; perhaps for optimizing bus routes.</p><pre>const distances = {<br>  A: 0, // Within 2 miles<br>  B: 0, // More than 2 miles<br>};<br><br>const grades = {<br>  K: 0,<br>  A: 0, // Grade 1 to 3<br>  B: 0, // Grade 4 to 6<br>  C: 0, // Grade 7 and 8<br>};<br><br>for (const student of students) {<br>  const studentDistance = getDistanceBetween(student.addressCoords, schoolCoords);<br>  if (studentDistance &lt;= 2) {<br>    distances.A = distances.A + 1;<br>  } else {<br>    distances.B = distances.B + 1;<br>  }<br>  if (student.grade &lt; 1) {<br>    grades.K = grades.K + 1;<br>  } else if (student.grade &gt;= 1 &amp;&amp; student.grade &lt;= 3) {<br>    grades.A = grades.A + 1;<br>  } else if (student.grade &gt;= 4 &amp;&amp; student.grade &lt;= 6) {<br>    grades.B = grades.B + 1;<br>  } else if (student.grade &gt;= 7) {<br>    grades.C = grades.C + 1;<br>  }<br>}</pre><p>This alternative reads better and reduces both for and if statements. (<a href="https://medium.com/@jamesmarks/these-alternatives-to-if-will-make-your-code-100x-better-1a77a1792e29">See this article for an tour of the alternative strategies for conditionals</a>.)</p><pre>const startDistances = {<br>  A: 0, // Within 2 miles<br>  B: 0, // More than 2 miles<br>};<br><br>const distanceGroupers = [<br>  { key: &#39;A&#39;, isValid: (distance) =&gt; (distance &lt;= 2) },<br>  { key: &#39;B&#39;, isValid: (distance) =&gt; (distance &gt; 2) },<br>];<br>const distances = students.reduce((acc, student) =&gt; {<br>  const grouper = distanceGroupers.find((dg) =&gt; dg.isValid(<br>    getDistanceBetween(student.addressCoords, schoolCoords)<br>  );<br>  return {<br>    ...acc,<br>    [grouper.key]: acc[grouper.key] + 1,<br>  };<br>}, startDistances);<br><br>const startGrades = {<br>  K: 0,<br>  A: 0, // Grade 1 to 3<br>  B: 0, // Grade 4 to 6<br>  C: 0, // Grade 7 and 8<br>};<br><br>const gradeGroupers = [<br>  { key: &#39;K&#39;, isValid: (grade) =&gt; (grade &lt; 1) },<br>  { key: &#39;A&#39;, isValid: (grade) =&gt; (grade &gt;= 1 &amp;&amp; grade &lt;= 3) },<br>  { key: &#39;B&#39;, isValid: (grade) =&gt; (grade &gt;= 4 &amp;&amp; grade &lt;= 6) },<br>  { key: &#39;C&#39;, isValid: (grade) =&gt; (grade &gt;= 7) },<br>];<br>const grades = students.reduce((acc, student) =&gt; {<br>  const grouper = distanceGroupers.find((gg) =&gt; gg.isValid(student.grade));<br>  return {<br>    ...acc,<br>    [grouper.key]: acc[grouper.key] + 1;<br>  };<br>}, startGrades);</pre><p>This alternative breaks apart the multiple responsibilities of the for loop into separate tasks. It puts like code with like code and it executes its job in a way that can be read in a few lines for each part.</p><p>If you’re not familiar with .reduce() yet, you may find it a little intimidating at first. After seeing a few of these and really “getting” it, you’ll find this code is a much quicker and clearer alternative to the original.</p><p><strong>Get Coding!</strong></p><p>If I have come across as against OOP in this article, I’d like to emphasize that I am actually pro OOP <strong><em>and</em> </strong>pro Functional.</p><p>Use the right tool for the job and you’ll get better results.</p><p>I think that most developers get carried away with OOP style only, and end up using it by itself in many instances when there are more effective choices that can be made.</p><p>Javascript is multi-paradigm, so we should write multi-paradigm code. Use both Functional and OOP strategies together for your projects. Let each development style do what it does best.</p><p>Happy Coding!</p><p>More articles like this:</p><ul><li><a href="https://medium.com/@jamesmarks/these-alternatives-to-if-will-make-your-code-100x-better-1a77a1792e29">These Alternatives to `if` Will Make Your Code 100x Better</a></li><li><a href="https://medium.com/@jamesmarks/i-use-this-alternative-to-switch-to-make-javascript-10-times-better-f1058f16c30e">I Use This Alternative to `switch` to Make Javascript 10 Times Better</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29657191dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Things You Should Avoid Doing with TypeScript]]></title>
            <link>https://medium.com/bitsrc/5-things-you-should-avoid-doing-with-typescript-25a3439687a5?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a3439687a5</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 06:56:52 GMT</pubDate>
            <atom:updated>2023-03-27T00:37:42.019Z</atom:updated>
            <content:encoded><![CDATA[<h4>Just because you can do these, doesn’t mean you should.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wt5zY0SO9HJh4-4diUYrww.png" /><figcaption>Photo by Tim Mossholder on Unsplash</figcaption></figure><p>Most of us are aware that in JavaScript, you can do many things you shouldn’t. Many people first starting with TypeScript and nearly as many who have been using TypeScript for a long time may not have considered that the same thing applies in TypeScript, too.</p><p>While TypeScript can be an effective tool to protect against human error and thoughtlessness or forgetfulness, it has to try to facilitate doing all things in JavaScript that people have always been able to do. Both the good and the bad.</p><p>On top of that, it needed some ways to ensure that they weren’t slowing down development in cases such as rapid prototyping or unit testing. Thus, it provides some features that allow developers to circumvent its otherwise powerful ability to save you from yourself.</p><p>These “escape hatches” that TypeScript allows you to use are sometimes related to things you can do in JavaScript with or without TypeScript, but you may not be aware of their detrimental effect on your projects.</p><blockquote>Well written code is easy to understand and easy to change. Continuously seek to break down complexity into smaller simpler parts. Reduce tech-debt, increase code comprehension and maintainability.</blockquote><h3>1. Union Types</h3><p>While you can’t control what data is being passed around outside of your own code, inside your code you can get more certain about your own data.</p><p>Union types are a means of allowing data to take many shapes, which sounds great in concept.</p><p>However, In practice, you usually end up dealing with each shape of that data differently.</p><p>In fact, what typically ends up happening is that you write overly complicated code, which becomes a difficult-to-maintain mess.</p><p>Don’t make one-size-fits-all functions or methods!</p><p>Instead of trying to write a clever function that does everything, write code that handles each case separately and clearly to gain a happier and more productive developer experience.</p><p>Avoid using union types. Be explicit and purposeful about how you handle data.</p><p>Here are some common ways that I’ve seen union types being used and how they can be improved.</p><h4>Union types for function parameters</h4><p>Sometimes you want to write a “catch-all” function that will take whatever you give it and do something different depending on what you’re given.</p><p>While this is not the most dangerous offender in this article, it is unhealthy for your code, and for most people, it doesn’t feel like a real problem until well after it is a big drain on resources to fix.</p><p>At some point in the future, you may want to diverge how you respond when given a particular type or two as input, perhaps providing a completely different type of return value.</p><p>The only way to make this change is to write a new function that accepts the single parameter type and provides a new return type and then sift through all calls to the original function to ensure that any using that particular parameter type are changed to call the new one. This is sticky and dangerous and can be difficult to guarantee is done right.</p><p>The better choice is simply to write multiple publicly exposed functions with distinct names and similar but differently typed parameters as input. You can delegate each of these to call your original function (which should be private) internally to ensure you adhere to DRY principles.</p><h4>Union types for return values</h4><p>This issue often goes hand-in-hand with union types for parameters, but might also be found on its own. Both cases come from similar sentiments. The developer, with the best of intentions, is merely trying to create a single function that somebody can use for many purposes.</p><p>Excluding `null` (T | null), if a function returns more than one data type as its response value, then you are likely overloading it with too much responsibility.</p><p>Returning multiple potential types from your function requires your consumer code to do a great deal more branching, increasing the complexity of your code <strong>everywhere</strong> that you use the offending multiple-returner function.</p><p>One function that returns multiple types causes additional complexity throughout your code, not only within itself.</p><p>In my experience, you can almost always split your single, high-complexity function into several multiple, simplified, functions. Give those functions good self-described names and now your consumers can use them in a way that is more obvious and specific.</p><h4>Union types for variables</h4><p>Whether or not you ascribe to the belief that you should avoid mutation in your code, there is no good reason to have the exact same variable potentially contain data from different sources that might be a string or a number, or an array.</p><p>Instead of this, use type-narrowing and type-guards to ensure that your source data is being delegated to small single-purpose functions meant to handle data of a distinct type.</p><p>This keeps your code well organized and reduces the instances of branching and sub-branching that might occur at the code-block level.</p><blockquote><em>💡</em> Along with TypeScript you could also use an open-source toolchain like <a href="https://bit.cloud/"><strong>Bit</strong></a>. With Bit you can easily share, discover, and reuse individual components across different projects, which can significantly reduce code duplication and improve code quality.</blockquote><h4>Find out more:</h4><p><a href="https://bit.dev/blog/sharing-types-between-your-frontend-and-backend-applications-l5qih48g">Sharing Types Between Your Frontend and Backend Applications</a></p><h3>2. Using `any`</h3><p>TypeScript’s any is a necessary evil for TypeScript itself to satisfy the demands of the masses. It&#39;s useful for rapid prototyping, or just for getting the initial code started before taking some time to do things more correctly.</p><p>But in your production applications, it is <strong>highly damaging </strong>for <strong><em>you</em></strong> to use any. Ban it. Destroy it. Exorcise it from your commits and merge requests!</p><p>any is a tool that essentially escapes all of the type safety that TypeScript attempts to provide, making it so that the associated value can be of literally any type.</p><p>You can use it in any way you want, any time you want, often without regard for whether you successfully or specifically enforced typing via type guards.</p><p>In practice, when you decide to make something an any type, it is normally for one of two reasons:</p><p>Either, you don’t want to take the time to figure out how to do it right.</p><p>Or, you have some assumptions about the possible types that the value might hold, but you don’t have any way of knowing for sure what type it is beforehand.<br> <br>In this case, instead of setting the type to any, use unknown instead and then rely on type narrowing and type guards to handle the use cases you intend to handle. Optionally include a fallback.</p><p>This most certainly takes more code, but your code becomes more robust and less prone to runtime error.</p><p>Whether you want to do something different for something that is a number type than you want to do if it is a string type, or you want to do the same thing for both string and number types, you can use features such as type guards and assertions to ensure that the correct code is executed for the correct data type.</p><h3>3. Using `as`</h3><p>When I first started using TypeScript I didn’t understand that there were more effective, more correct alternatives to using as to tell the TypeScript parser what type of data I received from an API call.</p><p>In general, a developer’s intention when using as is to validate that something is a particular shape and to hint to TypeScript about what that shape is.</p><p>In reality, as silently does more than provide a hint. It can also coerce data to look like a given type and only provide a partial match.</p><p>It can effectively lie about your data, leading to cascading logic errors and difficult-to-track run-time bugs.</p><p>Because of as&#39;s ability to lie to TypeScript, there are circumstances even with a seemingly innocent .reduce where this might cause damage. And when you do end up with a runtime error as a result, it is often very difficult to trace.</p><p>Here’s an example:</p><pre>const response = await fetch(&#39;http://someendpoint.com/api/thing/1&#39;);<br>if (response.status === 200) {<br>  const responseData = await response.json() as TMyType;<br>}</pre><p>Responsible code is pessimistic and does not trust I/O from external sources under any circumstances.</p><p>Even if it was you who created that API endpoint and you feel 100% certain that you’ll always provide the correct response type, don’t trust it. Some day, you or some other developer will return and change that code — and your consuming application should be prepared to handle the possibility that a mistake will be made.</p><p>On top of that internet data transfer protocols always have a small chance of error, internet connections go out, and so on. You can not count on outside input being correct 100% of the time.</p><p>When you receive an API response, you should be using type-guards and/or type assertions to ensure that the data you received.</p><pre>// For this example, TMyType must have a property &#39;foo&#39; that is a string.<br>type TMyType = {<br>  foo: string;<br>};</pre><pre>const assertMyType = (data: unknown): TMyType =&gt; {<br>  if (<br>    data<br>    &amp;&amp; typeof data === &#39;object&#39;<br>    &amp;&amp; &#39;foo&#39; in data<br>    &amp;&amp; typeof data.foo === &#39;string&#39;<br>  ) {<br>    return data as TMyType;<br>  }<br>  throw new Error(&#39;TMyType Assertion failed.&#39;);<br>};</pre><pre>const doAThing = async () =&gt; {<br>  const response = await fetch(&#39;http://someendpoint.com/api/thing/1&#39;);<br>  if (response.status === 200) {<br>    const responseData = assertMyType(await response.json());<br>    doSomethingWithResponse(responseData);<br>  }<br>};</pre><p>Firstly, you’ll notice I still used as here. Unfortunately, this is a strange quirk with TypeScript.</p><p>If you maintain the rule that the only time you’ll use as is inside the context of an assertion function, it will serve you well. Also, just be certain to validate that the function does as intended. Use unit testing whenever you can.</p><p>Yes. This is definitely a little more work than the original example, particularly if you consider that most type assertions will need more than one property to be validated (consider a validation framework).</p><p>However, it is important to keep in mind that this is work that <em>should </em>be done with or without TypeScript if you want a complete, professional, self-documenting, and secure application.</p><p>TypeScript doesn’t cause the need for the added work, it simply exposes and enforces the need.</p><h4>Another common use case for `as`</h4><p>Another way that I used to use as is to lazily add types to the result in the Array prototype function `reduce`&#39;s second argument.</p><pre>const fruitSalad = fruits.reduce((acc, current) =&gt; {<br>  return [...acc, current.name];<br>}, [] as string[]);</pre><p>.map, .reduce, and .filter among countless other functions use generics and TypeScript’s built-in type inferencing to implement meaningful type restrictions on code.</p><p>When inferencing, TypeScript does its best to narrow down to the most likely possible type with the information it has, and that means it isn’t always what you intend. In the above, had I not provided a hint that the array was an array of strings, TypeScript would have considered it to be a never[] .</p><p>Don’t do as I did. Provide the type using the type generic system in angle brackets &lt;&gt; .</p><pre>const fruitSalad = fruits.reduce&lt;string[]&gt;((acc, current) =&gt; {<br>  return [...acc, current.name];<br>}, []);</pre><p>This avoids the small, but all too human chance of accidentally using as to enforce an incorrect type.</p><h3>4. Using the Definite Assertion Operator: `!`</h3><p>TypeScript wants to help by ensuring you are protected against missing data. It analyzes your code, tells you that there is a chance that you might be missing data, and then you go ahead and say “I promise the value is there”.</p><p>Why, oh why would you do this to yourself?</p><pre>// Person has a .middleName property that is optional, so it might be `undefined`<br>const middleInitial = (person.middleName!)[0];</pre><p>It takes a few moments more to use a type guard and provide some logic to handle a case where the value doesn’t actually exist, no matter how much of a longshot that is.</p><p>You may choose to put up an alert, throw an error or something else. It&#39;s up to you, how you want to respond.</p><pre>if (person.middleName === undefined) {<br>  // Your choice of user feedback.<br>  return;<br>}<br>const middleInitial = (<br>  person.middleName<br>    ? person.middleName[0]<br>    : &#39;&#39;<br>);</pre><p>Doing this creates code that doesn’t just claim that something exists. You have effectively proved to TypeScript that you have a defined value.</p><p>Just make sure that the code after the if block doesn’t execute when your value is undefined. An early return is a common way to handle this, but throwing an Error is another option. I’m sure you can find others.</p><h3>5. Writing Unit Tests Restricted by TypeScript Rules</h3><p>TypeScript is WONDERFUL, but it is not perfect. It acts as a deterrent to issues with data types, but there is no 100% guarantee that all of the types it will assume are true at compile time will continue to be true at run time.</p><p>If you write your tests using TypeScript — and particularly if you write using a disciplined set of style rules such as those described above — the rules of TypeScript may keep you from writing effective tests.</p><p>Write your tests in plain JavaScript OR break the rules above and use as or any to bypass type restrictions in your unit tests in order to write failing code.</p><p>For unit testing to be fully effective you must write failing tests as well as successful ones. That way when somebody makes a change to your tested code later, it will be much more difficult for them to break.</p><p><strong>Get Coding!</strong></p><p>I hope you found this article helpful, useful, and interesting!</p><p>Keep an eye out for my next few articles where we’ll explore alternative strategies to other common paradigms.</p><p>My goal is to make the world’s code more beautiful, useful, and effective, one developer at a time.</p><p>I’m always excited to share more ways to improve your code and make it more maintainable, readable, and productive.</p><p>Happy coding!</p><p>Check out one of my other articles below:</p><ul><li><a href="https://medium.com/@jamesmarks/these-alternatives-to-if-will-make-your-code-100x-better-1a77a1792e29">These Alternatives to `if` Will Make Your Code 100x Better</a></li><li><a href="https://blog.bitsrc.io/why-typescript-is-better-than-javascript-for-team-projects-6c5987dae5da">Why Typescript is Better than JavaScript for Team Projects</a></li></ul><h4>Build Apps with reusable components, just like Lego</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8uH_Kugp1e9yZp4N.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h4>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h4><h4>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h4><h4>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h4><h4>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h4><h4>Learn more:</h4><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></li><li><a href="https://blog.bitsrc.io/5-ways-to-build-a-react-monorepo-a294b6c5b0ac">5 Ways to Build a React Monorepo</a></li><li><a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">How to Create a Composable React App with Bit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a3439687a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/5-things-you-should-avoid-doing-with-typescript-25a3439687a5">5 Things You Should Avoid Doing with TypeScript</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Team Management Skills Learned as a Software Developer]]></title>
            <link>https://medium.com/@jamesmarks/team-management-skills-learned-as-a-software-developer-86e350e38344?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/86e350e38344</guid>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 12:30:15 GMT</pubDate>
            <atom:updated>2023-03-24T12:30:15.186Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software development ideas I leverage to frame how I manage my development team as an ex-developer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Yi8fQ6YypLtdTLF" /><figcaption>Photo by <a href="https://unsplash.com/es/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a one-time software developer, the transition to managing a team of developers was difficult but rewarding.</p><p>At first, much of the work was unfamiliar and uncomfortable. Even a little scary. Early on, I regularly suffered from imposter syndrome. I’d been many things, before. Among other positions I’d held, I had been a part-time college professor, a steel worker, a data entry manager, and of course a software developer many times over.</p><p>But being a manager of this type of team was scary until I learned what was needed and how similar to software development it was if I looked at it from the proper angle.</p><h3>What a Manager Does</h3><h4>Efficiency &amp; Productivity</h4><p>By implementing the right systems, I aim to make work easy and fulfilling for the developers on my team, and profitable for our business.</p><p>In these systems, efficiency comes from ensuring that all the parts of the team are able to consistently work at their highest sustainable productive level.</p><p>Productivity is the result and the measurement of this efficiency.</p><h4>Team Health</h4><p>This aspect of the work entails actively caring for the health of both the individuals and the overall team.</p><p>While the mental and physical health of both each individual team member and of the team are important pillars, team health refers to more than the individual.</p><p>A healthy team is good for the health of the business, too.</p><p>When the team is not doing well, there are some things we can do to improve:</p><p>Sometimes this means training. Sometimes putting developers that complement each other into teams. Sometimes it means hiring for the skill sets we need… and yes, sometimes this regrettably means removing members from our ranks (though this is always a last resort when other methods fail).</p><p>This aspect of the job means vigilantly searching for weaknesses and finding ways to strengthen, support, and otherwise bolster the areas that are weak so that they don’t get in the way of our business goals.</p><h4>Accountability</h4><p>When my team fails. I fail.</p><p>When my team is under the gun, I stand in the line of fire.</p><p>I am responsible to help ensure their success and when they are not successful, it’s my responsibility to determine why this happened and how we can do better in the future.</p><h3>The Coding Skills</h3><h4>The result is only as good as the algorithm that created it</h4><p>What you get as output from your functions in your code projects is the result of an algorithm. No matter how involved that function is, given any input, your code dictates the output through the logic that you have set forth.</p><p>The same is true for managing a team of developers. The differences are actually not many. You can have a variety of input given to your team — often in the form of tasks presented in the form of tickets — your process is the algorithm that determines what the output of that input is in the form of features and changes to your software.</p><p>If your process is tweaked just right for your input, you will get efficient, productive output from a team that is happy, healthy, and able to continue to maintain the same day after day.</p><p>There is a caveat though. One that presents new challenges that are not as common in development.</p><p>In code, with only a few exceptions, you can expect that the input to your function is generally going to change infrequently and you can leave it as-is for an indefinite period of time.</p><p>In process management for a team of developers, you can definitely expect that over time, your inputs or targets will frequently change. New projects will be introduced as old projects are completed and released. You’ll have different stakeholders for different projects with different expectations. Business objectives will evolve with the economy and circumstances.</p><p>This makes the work dynamic and exciting, continually providing new types of problems to solve.</p><p>The systems and processes used to manage my team are like little functions that expect input and provide output, and because of the dynamic nature of business, they need changes to maintain and improve their effectiveness every day.</p><h4>Simplify complexity by breaking large complex processes into small simple processes</h4><p>Systems can get really complex and demanding if you let them.</p><p>Over time, after implementing process after process, you will find that you have to layer processes on top of each other.</p><p>Dependencies grow and your whole system gets clogged up by the well-meaning systems that you introduced.</p><p>Before you know it, you’re creating processes to handle other processes.</p><p>This is not very different from what we commonly refer to as “tech debt” in the software development world.</p><p>You can and will create “process debt”.</p><p>Just like tech debt, you have to make time to pay it down. Regularly stop to find areas where you’ve added processes to a system too much and caused it to slow because of too much “red tape”.</p><p>Determine what is least effective and remove it, or find simpler ways to accomplish the same task. Reduce paperwork and “busy work” so that your team can be freed up to do the jobs they were hired to do.</p><p>Solicit regular feedback from your team members to ensure that you capture any issues caused by your system and seriously consider the feedback you’re given. Your team members often have great ideas that can help. Don’t be afraid to try them.</p><h4>Refactor, Refactor, Refactor</h4><p>Always be looking for ways to improve. Work, business rules, and even the people who are responsible for doing the work change. As they do, the parameters of the work also change, requiring you to re-evaluate and change your systems to better fit to the circumstances and actors.</p><p>Even when you hit on the right thing, you may have opportunities to optimize and automate. The next skill, testing, should help you to maintain your results while making these changes.</p><p>We all know that compounding small improvements over time adds up to high value over time. This is why we have to consistently make small, meaningful and helpful changes.</p><p>However, you don’t want to make changes haphazardly. Make sure you try changes on things that are not working or not working well. Don’t fix what aint broke, as they say.</p><p>That leads me to the next point…</p><h4>Test, Test, Test</h4><p>Always solicit feedback from your team and stakeholders.</p><p>Create systems to receive feedback and pay close attention to subtext when you hear your team speak. Listen and learn.</p><p>Yes, sometimes the feedback is griping and complaining, but <em>listen</em>!</p><p>If something is a real problem, you’ll know. It’ll be delivered by somebody with a lot of trust and who has provided valuable feedback in the past, or you may hear it from multiple team members.</p><p>Whatever you do, involve your team in the process of discovering issues and don’t allow your own opinions to be the only reason for change.</p><p>Importantly, after you decide to act on a problem area introducing a change, make sure to return to the people who gave feedback and get their opinion on how well the change is working to resolve the problem.</p><h4>Continuous Learning</h4><p>Finally — and this part is as much about your team as about yourself — learning is extremely important. As a manager of a team, you need to be able to speak their language forever. Learn what they know. Learn from them. Learn <em>for</em> them.</p><p>Additionally, constantly hone your abilities as a leader and team maintainer by reading and using other sources of media to learn ways that you can be even better at what you do. Your learning has the same compounding effect as the changes to your team’s processes.</p><p>In software development, perhaps more than any other industry, continuous self-development is a survival requirement. In management, I feel the same is true. I am constantly learning, both on the job and through proactively seeking out learning sources, such as online courses and books.</p><p>There are thousands of sources that you can learn from. Ask your mentors and your own superiors if they have any recommendations. Take courses.</p><p>Whatever you do, keep up with the industry. There will always be new ideas and you’re sure to have team members suggest implementing them. Be ready, armed with knowledge to discuss from a place of knowledge.</p><h3>Be awesome.</h3><p>The above is a breakdown of some simple ideas, but they make useful frames for understanding some of the most important parts of a managerial or leadership position.</p><p>We must create and maintain effective systems for productivity by making small changes frequently in response to inefficiencies in our processes. To do this effectively we must ensure we gain the perspectives of the people who make up our systems and work together to determine the best ways to improve those areas.</p><p>I sincerely hope the ideas above have helped to frame these responsibilities for you and have helped you to see other ways you might look at how you can be more effective as a manager or leader.</p><p>I write about my passions, including opinionated thoughts about code, life and work. If you enjoy my style or just want to see what I have to say next, hit me up with a follow.</p><p>Until next time.</p><p>Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86e350e38344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Use This Alternative to `switch` to Make Javascript 10 Times Better]]></title>
            <link>https://medium.com/@jamesmarks/i-use-this-alternative-to-switch-to-make-javascript-10-times-better-f1058f16c30e?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1058f16c30e</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 01:44:01 GMT</pubDate>
            <atom:updated>2023-03-19T01:44:01.196Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make your Javascript code more flexible, readable and maintainable with this one simple alternative to `switch`.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SXYZRieptShSfhEb" /><figcaption>Photo by <a href="https://unsplash.com/@carlheyerdahl?utm_source=medium&amp;utm_medium=referral">Carl Heyerdahl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Javascript, switch is a code construct that does a one-to-one comparison of a variable against a definite list of possible values.</p><p>Although more organized than if , switch has some drawbacks that can be overcome with the strategy I’ll cover below.</p><ul><li>It is limited. If you want to do more than simple one-to-one comparisons, you have to “hack” it, or revert to if (or if you’ve been paying attention, one of our other alternative strategies.)</li><li>The strange fall-through rules necessitate the use of break and can be the source of difficult to track bugs — especially for that new junior on your team.</li><li>It makes the code harder to read and maintain.</li><li>Considered an anti-pattern by some, if you add new cases you will have to edit the code in place further bloating the function.</li><li>If you’re like me, you might also find that you don’t like that it has unique syntax as compared to other statements in Javascript. It doesn’t “fit in”.</li><li>It doesn’t lend itself well to composition, extension and clean architecture in an application that might have an large set of permutations to handle.</li></ul><p>If switch has so many failings, what should we do instead?</p><p>Replace it with a Javascript Object that maps results to the same enumerable keys that you would use in the switch statement.</p><p>It functions just as well as a switch statement, only now you’ll get the ability to use a type system (such as Typescript) as well as more flexibility when it comes to where and how you place your code.</p><p>Let’s look at some examples.</p><p>This first one might look familiar. We want to assign a value to one variable, based on some other value.</p><pre>function getProductCategoryName(categoryNumber) {<br>  let categoryName = &#39;&#39;;<br>  switch(categoryNumber) {<br>    case 1:<br>      categoryName = &#39;Smartwatch&#39;;<br>      break;<br>    case 2:<br>      categoryName = &#39;SSD Drive&#39;;<br>      break;<br>    case 3:<br>      categoryName = &#39;Gaming mouse&#39;;<br>      break;<br>    case 4:<br>      categoryName = &#39;Keyboard&#39;;<br>      break;<br>    default:<br>      categoryName = &#39;INVALID&#39;;<br>      break;<br>  }<br>  return categoryName;<br>}</pre><p>Innocent enough, but this can be improved:</p><pre>const categoryMap = {<br>  1: &#39;Smartwatch&#39;,<br>  2: &#39;SSD Drive&#39;,<br>  3: &#39;Gaming Mouse&#39;,<br>  4: &#39;Keyboard&#39;,<br>};<br><br>function getProductCategoryName(categoryNumber) {<br>  return categoryMap[categoryNumber] || &#39;INVALID&#39;;<br>}</pre><p>By handling the logic with an object map, we’ve manage to make the code a much quicker read and extension of the code becomes an obvious configuration based change to a data object instead of extending code. Both of these are key factors in maintainability.</p><p>Additionally, you can further expand on this method by filling your object from an external source, simply by calling your REST API and loading data into memory.</p><p>“But,” you might say, “that’s a really simple example. switch isn’t always as straightforward as that. How would this work with a more complex use case?”</p><p>Good question. Let’s look at a more complex (but derived) example that let’s the caller know whether the data they have is valid.</p><pre>function isDataValidForCategory(categoryCode, metaData) {<br>  let categoryName = &#39;&#39;;<br>  switch(categoryNumber) {<br>    case &#39;SMARTWATCH&#39;:<br>      if (!metaData.os || (typeof metaData.heartMonitor !== &#39;boolean&#39;)) {<br>        return false;<br>      }<br>    case &#39;SSDDRIVE&#39;:<br>      if (!metaData.brand || !metaData.storageCapacity) {<br>        return false;<br>      }<br>    case &#39;KYBDMOUSE&#39;:<br>      if (!metaData.brand || (typeof metaData.wireless !== &#39;boolean&#39;)) {<br>        return false;<br>      }<br>    default:<br>      return true;<br>  }<br>}</pre><p>This is almost the same. The difference is that rather than mapping out values, we map out functionality.</p><pre>const categoryValidators = {<br>  &#39;SMARTWATCH&#39;: (metaData) =&gt; { <br>    return (metaData.os &amp;&amp; (typeof metaData.heartMonitor === &#39;boolean&#39;));<br>  },<br>  &#39;SSDDRIVE&#39;: (metaData) =&gt; { <br>    return (metaData.brand &amp;&amp; metaData.storageCapacity);<br>  },<br>  &#39;KYBDMOUSE&#39;: (metaData) =&gt; { <br>    return (metaData.brand &amp;&amp; (typeof metaData.wireless === &#39;boolean&#39;));<br>  },<br>};<br><br>function isDataValidForCategory(categoryCode, metaData) {<br>  return categoryValidators[categoryCode](metaData) || false;<br>}</pre><p>Once again, this method produces somewhat less code, and its a bit of a quicker read. The function itself will not need to be changed to add configuration for future category codes.</p><p><strong>Get Coding!</strong></p><p>I hope you found this article helpful, useful, and interesting!</p><p>Look at all of your switch statements and give this a go.</p><p>Keep an eye out for my next few articles where we’ll explore alternative strategies to other common paradigms.</p><p>I’m excited to share more ways to improve your code and make it more maintainable, readable, and productive.</p><p>Happy coding!</p><p>Check out one of my other articles below:</p><ul><li><a href="https://medium.com/@jamesmarks/these-alternatives-to-if-will-make-your-code-100x-better-1a77a1792e29">These Alternatives to `if` Will Make Your Code 100x Better</a></li><li><a href="https://blog.bitsrc.io/why-typescript-is-better-than-javascript-for-team-projects-6c5987dae5da">Why Typescript is Better than JavaScript for Team Projects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1058f16c30e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[These Alternatives to `if` Will Make Your Code 100x Better]]></title>
            <link>https://medium.com/@jamesmarks/these-alternatives-to-if-will-make-your-code-100x-better-1a77a1792e29?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a77a1792e29</guid>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 14:05:16 GMT</pubDate>
            <atom:updated>2023-03-19T01:44:32.036Z</atom:updated>
            <content:encoded><![CDATA[<h4>Traditional conditionals can be highly damaging to your code. A few simple strategies can help protect you from harm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bE891qjoLprZ9p2B" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem:</h3><p>Code that is easy to understand and easy to change is key to productivity and success. While performance is important, a codebase that can’t evolve with your business is working against you.</p><p>By focusing on code that reads like a book, with each passage having meaning in itself and told in sequence, you can achieve easy-to-understand code. Traditional conditional structures such as if and switch can lead to issues as your code base evolves.</p><p>However, there are alternative methods to conditionally handle code that are more extensible, powerful, and beautiful.</p><p>Let’s look at how we can write code differently to reduce complexity and increase ease of understanding!</p><h3>Case A: Simple `max` function:</h3><p>In our first case, we have a small and seemingly innocent function.</p><p>This first example has 9 total lines of code. On this smaller scale, it doesn’t seem so dangerous — but it will serve as a way to see how we might make different micro decisions in a way that can apply in larger or more complex context.</p><h4>Start:</h4><pre>function max(a, b) {<br>  let x;<br>  if (a &gt; b) {<br>    x = a;<br>  } else {<br>    x = b;<br>  }<br>  return x;<br>}</pre><p>Much of the issue with if is in the else block.</p><p>Having an else almost always leads to variables that are changed in more than one place.</p><p>Again, at this smaller scale it doesn’t seem very harmful, but in practice, this typically leads to multiple developers making multiple changes to the same variable throughout your code, making it more difficult to trace a change.</p><h4>“Good” Improvement: Early return:</h4><p>One solution is to not assign to a variable at all. return short circuits a function, so let’s just check if one number a is greater, and if it is return that number. Otherwise we can return the other number, b.</p><pre>function max(a, b) {<br>  if (a &gt; b) {<br>    return a;<br>  }<br>  return b;<br>}</pre><p>This is a quicker read. Now we’re down to 6 lines of code. With fewer characters on the screen, our brains can more quickly understand what is happening. This small thing repeated over your code hundreds of time already results in quicker code comprehension, and thus higher productivity over the long run.</p><p>However, early returns are not always an option with an if statement. Sometimes your if statement isn’t packed so neatly inside a function. For those instances, we need something different.</p><h4>“Better” Improvement: Ternary expression</h4><p>Another alternative is to use a ternary expression. It works in almost every case where you have only two possible actions you want to take. When you want to branch either one way or the other in your logic, this is a perfect go-to.</p><pre>function max(a, b) {<br>  return (a &gt; b) ? a : b;<br>}</pre><p>We’re now down to just 3 lines, one return and a fairly simple and obvious branch.</p><p>Just keep in mind that ternaries are intended to perform assignment. I’ve seen people try to use them to execute side effects. In those cases, ternaries may make your code more difficult to read or change. If your ternary doesn’t come after an = or a return , you may want to question if you’ve taken this too far.</p><h4>Bonus “Best” Improvement: Arrow function</h4><p>As a bonus, I’m adding the arrow function version. Its a bit more concise and looks great on a single line.</p><pre>const max = (a, b) =&gt; ((a &gt; b) ? a : b);</pre><h3>Case B: If/else-if/else</h3><p>Here is a more complex example of an if statement. It too looks innocent at first — especially when you don’t have a great deal of experience.</p><pre>/**<br> * `content` is expected to be a string containing text from a document.  <br> **/<br>function guessDocumentType(content) {<br>  let contentType;<br>  if (content.startsWith(&#39;&lt;!doctype html&gt;&#39;)) {<br>    contentType = &#39;html&#39;;<br>  } else if (content.startsWith(&#39;---\\n&#39;)) {<br>    contentType = &#39;yaml&#39;;<br>  } else if (content.includes(&#39;##&#39;)) {<br>    contentType = &#39;markdown&#39;;<br>  } else {<br>    contentType = &#39;text&#39;;<br>  }<br>  return contentType;<br>}</pre><p>In a small-sized, proof-of-concept product, like a school project, this doesn’t have any apparent problems. It usually doesn’t in these cases.</p><p>But hopefully, you will find yourself on a team working collaboratively on a much larger code base and at that time, your code choices will matter a great deal. Organization, portability, readability and maintainability will become the most important things to consider when writing your code.</p><p>If you want to create high quality code, you have to think about the simple things you do in more detail and begin to understand their weaknesses, as well as other strategies for solving the same problems.</p><h4>A “Good” (sort of) Alternative:</h4><pre>const docTypeComparers= {<br>  html: (content) =&gt; (content.startsWith(&#39;&lt;!doctype html&gt;&#39;)),<br>  yaml: (content) =&gt; (content.startsWith(&#39;---\\n&#39;)),<br>  markdown: (content) =&gt; (content.includes(&#39;##&#39;)),<br>}</pre><pre>function guessDocumentType(content) {<br>  const matchedKey = Object.keys(docTypeComparers).find((key) =&gt; docTypeComparers[key](content));<br>  return matchedKey ?? &#39;text&#39;;<br>}</pre><p>This first alternative is a step in the right direction.</p><p>Looking at this snippet may help you to see conditional problems from another angle. I won’t recommend using this option, as there is a better alternative, but I do think its worth looking at this just to add some fodder for the way you think about your code.</p><p>It isn’t truly a great solution on its own, but it does do some positive things compared to the code we started with.</p><ul><li>It demonstrates how the code can become more concise and readable through the use of arrow functions.</li><li>The code is made more readable by isolating comparison logic into a clear area of the code, separate from the business logic that uses them.</li><li>Makes it easier to add or remove document types without making extensive changes to the function.</li><li>When another developer comes to this page to add a new document type comparer, it will be <em>immediately</em> clear where and how to do that, without modifying the existing business logic.</li></ul><p>But it does have its weaknesses:</p><ul><li>Most Javascript developers know what Object.keys() is and does, but using it in this way can make the code a bit difficult to see at a glance, which means it isn’t as easy to understand as we’d like.</li><li>Additionally, the duplicate use of docTypeComparers on the same line along with some other “extra” code, makes the line a bit repetitive - nearly “ugly. It probably makes more nit-picky developers stop-up because all they want to do is “clean it up”.</li><li>There is a mental “hiccup” looking at the code. As with your start point, this doesn’t seem like a big deal in isolation, but in a larger app where another developer has to parse hundreds of lines of code like this, it can take much longer to get their head around what is happening before they can begin work on a new task.</li></ul><h4>A “Better” Alternative:</h4><pre>const docTypeComparers = [<br>  { docType: &#39;html&#39;, isDocType: (content) =&gt; (content.startsWith(&#39;&lt;!doctype html&gt;&#39;)) },<br>  { docType: &#39;yaml&#39;, isDocType: (content) =&gt; (content.startsWith(&#39;---\\n&#39;)) },<br>  { docType: &#39;markdown&#39;, isDocType: (content) =&gt; (content.includes(&#39;##&#39;)) },<br>];</pre><pre>function guessDocumentType(content) {<br>  const matchedItem = docTypeComparers.find(({ isDocType }) =&gt; isDocType(content));<br>  return matchedItem?.docType ?? &#39;text&#39;;<br>}</pre><p>This solution is similar to the “Good” one above, except that we’ve now arranged the comparers into an array of individual objects rather than an object. Each array item comes with a docType field indicating the document type if matched and an isDocType field containing the comparer function.</p><p>It is still fairly obvious to a developer how to add new comparers and the guessDocumentType function becomes much easier to read.</p><p>As an added bonus, naming the fields of the comparers, helps them to be “self-documenting”.</p><h4>Bonus “Best” Alternative:</h4><pre>import { comparers } from &#39;./comparers&#39;;</pre><pre>function guessDocumentType(content) {<br>  const matchedItem = comparers.find(({ parse }) =&gt; isDocType(content));<br>  return matchedItem?.docType ?? &#39;text&#39;;<br>}</pre><p>This is simply a further extension of the previous array alternative. But, instead of holding the details of the functions in this file, you import them from another file for organization purposes. This opens the door to further separation of concerns, which would be incredibly useful for a growing list of potential alternatives that each may have heavier complexity.</p><p>Much of the time, if you have a shorter list of items to compare, you’d stick with the “better” alternative. So long as you’ve prepared it in that way, it isn’t very difficult to refactor your work to progress to this.</p><p>(In a future article, I may provide an in-depth look at how this might be done by example.)</p><p><strong>Get Coding!</strong></p><p>I hope you found this article helpful, useful, and interesting!</p><p>Keep an eye out for my next few articles where we’ll explore alternative strategies to other common paradigms. We’ll start by taking a closer look at switch.</p><p>I’m excited to share more ways to improve your code and make it more maintainable, readable, and productive.</p><p>Happy coding!</p><p>Check out one of my other articles below:</p><ul><li><a href="https://medium.com/@jamesmarks/i-use-this-alternative-to-switch-to-make-javascript-10-times-better-f1058f16c30e">I Use This Alternative to `switch` to Make Javascript 10 Times Better</a></li><li><a href="https://blog.bitsrc.io/why-typescript-is-better-than-javascript-for-team-projects-6c5987dae5da">Why Typescript is Better than JavaScript for Team Projects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a77a1792e29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Typescript is Better than JavaScript for Team Projects]]></title>
            <link>https://medium.com/bitsrc/why-typescript-is-better-than-javascript-for-team-projects-6c5987dae5da?source=rss-e6e26cd79b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c5987dae5da</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript-vs-typescript]]></category>
            <dc:creator><![CDATA[James Marks]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 00:59:50 GMT</pubDate>
            <atom:updated>2023-03-13T09:47:45.255Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Unending Debate: Why Use Typescript?</h4><p>It always upsets me when I come across a person or an article that is strongly anti-Typescript. I find it extremely difficult to understand why a tool that does so much good in larger applications shared by multiple developers can be so detested…</p><p>Yet there are countless articles refuting the usefulness of Typescript, and refusing to acknowledge its benefits or the time-saving effect of having the limits and automatic self-documentation that Typescript enforces. These restrictions and tools <strong>enhance </strong>your code base, making it <strong>easy </strong>for other developers to contribute.</p><h4>Typescript, used effectively, results in code that is:</h4><ul><li><strong>More manageable and readable</strong><br>With good settings, Typescript ensures that code intention becomes explicit. Looking at the code, you will immediately understand what it is intended to do.<br> <br>It is definitely easy to get wrong at first. But, like any other coding language you’ve learned, you just need to get better by making mistakes, fixing them, and then trying again. <br> <br>One mistake that neophyte Typescript developers make is trying to add types to everything. Typescript inference is incredible. If you don’t try to force it, you’ll often find that Typescript provides types passively and you get to benefit.</li><li><strong>Easier to understand</strong><br>This is a lot like the previous point, but importantly, you’ll find that as Typescript hints about the little mistakes that you make, you’ll gradually continue to improve the quality of your code automatically.<br> <br>In fact, I will argue that as you push through the first stages of Typescript, you’ll begin to truly understand what is happening under the hood of your Javascript code. You will become clearer about how your code works.</li><li><strong>Better supported by IDEs</strong><br>IDEs like Visual Studio, VS Code, and Rider all play very well with Typescript. In a larger-sized Javascript code base, it can be difficult to use refactoring and developer convenience tooling. <br> <br>If you do nothing more than install Typescript, set up tsconfig.json, and change your extensions to .ts, Typescript will first give you a hard time about your Javascript typing issues, and then once you’ve addressed the issues you’ll find that your IDE magically knows a lot more about your project than it did before.</li><li><strong>Less Buggy<br></strong>There isn’t a programming language that allows us to write code that has no possibility of mistakes, accidents, or bugs. However, Typescript adds a layer of security that can help to prevent many of them.</li><li><strong>More Transferrable</strong><br>While there are many factors that make your code reusable and transferrable from project to project, being able to place your strongly typed code into a library will give it self-documentation along with the portability we all love, which will allow you to easily use it in other projects for many years to come without having to try to keep all your code memorized. <br> <br>JSDoc is still helpful, but knowing exactly what type of data your package expects in a function call will be a big time saver over the many reuses of a package.</li></ul><blockquote><em>💡</em> Note: Portability is something an open-source toolchain like <a href="https://bit.cloud/"><strong>Bit</strong></a> can help with. With Bit, you can identify and isolate components within your codebase, defining them as independent entities that can be developed and tested separately, then versioned, documented, and shared via a central registry. Learn more <a href="https://bit.dev/blog/-extracting-and-reusing-pre-existing-components-using-bit-add-l28qlxpz/"><strong>here</strong></a>.</blockquote><h4>Arguments Against Typescript:</h4><ul><li><strong>Makes Code More Difficult to Read</strong><br>Yes, this can definitely be a problem when you use Typescript incorrectly or don’t yet understand it. However, this is not exclusive to Typescript. You can make nearly as many mistakes in Javascript that make your code ridiculously difficult to read.<br> <br>It takes a little time and effort to learn to use the tool effectively, then it increases readability — especially over a larger code base.</li><li><strong>Makes Code More Difficult to Write</strong><br>Initially, when you’re learning Typescript, this is certainly true for most developers. It’s just as easy to learn as Javascript was in the beginning. In fact, you caught a break learning Javascript first and having time to absorb and learn the basics of programming through the flexible Javascript language. Typescript can be a level-up and usually very much worth it when your code base is large enough.</li><li><strong>I Can’t do the Same Things in Typescript that I can in Javascript</strong><br>That’s by design. Typescript goes to great efforts to keep track of the data types in your code to help you avoid accidental errors — or for that matter potentially buggy logic on purpose which might otherwise result in errors that are very difficult to trace.</li><li><strong>Typescript is Hard to Learn</strong><br>For some people, learning to drive a vehicle is difficult, or to ride a bike. Yes, it can be difficult, but it&#39;s worth the effort. The benefits far outweigh the effort, and I don’t only mean the benefits in your code. Knowing how to wield Typescript effectively can directly impact your marketability and salary range.</li><li><strong>It’s a LOT of Extra Work to Implement Typescript When I can Just use Javascript Directly.</strong><br>If your code base is really small, you’re not wrong. I won’t argue here.<br> <br>But the reality is that when you are working on a project that has code in more than a handful of files and you are working with a team of more than one person, Typescript is an investment that pays large dividends over time.<br> <br>I also think that when you know Typescript well enough, it will save you a great deal of time using it on a solo project too. I certainly do.</li></ul><blockquote><em>💡</em> This is where <a href="https://bit.cloud/"><strong>Bit</strong></a> is once again going to be useful. It provides a platform for sharing and collaborating on code components. It allows you to publish and share your custom library with other developers and teams, and easily manage <a href="https://bit.dev/docs/getting-started/collaborate/snap-component-changes/">versioning</a>, <a href="https://bit.dev/blog/advanced-bit-dependency-management-and-configs-l5jnioog">dependencies</a>, and <a href="https://bit.dev/blog/introducing-component-compare-easily-review-component-changes-l4qyxtoo">updates</a>.</blockquote><h4>Learn more here:</h4><p><a href="https://bit.dev/docs/getting-started/composing/creating-components/">Create components | Bit</a></p><h4>Is It The Perceived Difficulty of Learning Typescript that’s Holding You Back?</h4><p>Are you just intimidated by having to learn Typescript?</p><p>Are you just not willing to learn it right now for your current project because you can’t see the justification in the extra work to learn and apply it?</p><p>Are you perhaps thinking that it is faster and more immediate to just do it in Javascript where you’re comfortable right now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*8Gc5ca2-mCXVs5l9UOiPqg.jpeg" /></figure><p>Whatever your reason, whatever your goals, if you don’t know Typescript well, then you owe it to yourself to at least learn it before you completely discard it. If you’ve tried to learn it and failed; or, if you’ve “tried” learning it for a few minutes or a few hours and haven’t given it an honest chance to see the benefit yet; take a little while to understand what to do and what NOT to do in Typescript.</p><p>There are many online resources to help you learn.</p><p>Check out the <a href="https://www.typescriptlang.org/docs/">Typescript Docs</a>. Also, look at <a href="https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html">Typescript Tooling in 5 minutes</a>. If you’re feeling particularly adventuresome, find a Youtube course.</p><p>I will regularly publish articles here about TypeScript, JavaScript, other programming concepts, and high-level coding ideas.</p><p>Thank you for reading. Catch you next time!</p><h3>Build Apps with reusable components, just like Lego</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*YmZ7jwHIqwyjV5YC.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h4>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h4><h4>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h4><h4>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h4><h4>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h4><h4>Learn more:</h4><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></li><li><a href="https://blog.bitsrc.io/5-ways-to-build-a-react-monorepo-a294b6c5b0ac">5 Ways to Build a React Monorepo</a></li><li><a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">How to Create a Composable React App with Bit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c5987dae5da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/why-typescript-is-better-than-javascript-for-team-projects-6c5987dae5da">Why Typescript is Better than JavaScript for Team Projects</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>