<?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 Cvetanov Goce on Medium]]></title>
        <description><![CDATA[Stories by Cvetanov Goce on Medium]]></description>
        <link>https://medium.com/@cvetanov?source=rss-74188c0bf1ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*mPS5Gcd9w6iNUKPrZmydpg.png</url>
            <title>Stories by Cvetanov Goce on Medium</title>
            <link>https://medium.com/@cvetanov?source=rss-74188c0bf1ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 06:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cvetanov/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[AWS Event Bridge Scheduler as a workaround to SQS Fifo queue limitations]]></title>
            <link>https://tech.trustpilot.com/aws-event-bridge-scheduler-as-a-workaround-to-sqs-fifo-queue-limitations-1500726be1b2?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1500726be1b2</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[trustpilot]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[sqs]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 21:05:40 GMT</pubDate>
            <atom:updated>2024-04-22T21:05:40.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>At Trustpilot, we rely heavily on AWS SQS for making our systems more robust and processing the operations that we can in an async manner. In most of these scenarios, the producer pushes a message to a queue, a consumer picks it up immediately and starts processing it. In other cases, we might want to wait a bit between the time the message is produced and it is consumed.</p><p>AWS offers the concept of <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-delay-queues.html"><em>delay queues</em></a><em> </em>where one can configure a SQS queue to delay the initial processing of a message by making it <em>invisible</em> to consumers. This is a setting that applies on the queue level. If one needs to delay only a subset of the messages and not all of the messages in a queue, then one can use <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-timers.html"><em>message timers</em></a> where the producer sets a delivery delay on the individual messages.</p><h3>Problem</h3><p>The problem that we ran into was a use-case where we wanted to trigger a delayed processing of some messages that were being produced to a fifo queue. Setting the delay on the entire queue was not an option as these use-cases were rare and we did not want to penalize the rest. We were also not able to make use of individual message delays because this feature is not available for fifo queues.</p><blockquote><em>FIFO queues don’t support timers on individual messages. [</em><a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-timers.html"><em>SQS docs</em></a><em>]</em></blockquote><p>One might argue that this use-case we had on our hands is not exactly fitting in the architecture of having a fifo queue in place, but that’s beyond the scope of this blog post. Let’s just say that in these cases, we do not really care about the message ordering and just want to get this through to the consumer, but with a delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*yFzqysSPDKZa5SDJIVgIcA.png" /></figure><h3>Solution</h3><h4>EventBridge Scheduler</h4><p><a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html">EventBridge Scheduler</a> sounded like the perfect solution to our problem. We need to post a message to a fifo queue at a specific time and we are not that concerned with the message ordering. The <a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html#one-time">one-time schedule type</a> is exactly what we need.</p><p>EventBridge Scheduler has some <a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/scheduler-quotas.html">quotas</a> that one needs to keep in mind. In our case, we considered the following quotas:</p><ul><li>Quota for 50 requests per second for creating schedules. This is not something that bothered us at all because our use-case is a rare one and we will not come even close to this limitation.</li><li>Quota for a million schedules per region in total. This is also not something that we will come close to hitting anytime soon, but in any case, since we have proper monitoring in place in the consumer, we were completely fine with deleting the schedules once they are complete (ie. they have sent the message to the queue).</li></ul><p>We set up a <a href="https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule-group.html">ScheduleGroup</a> so that all of the schedules we create for this use-case are grouped together. In our case, this might not have been necessary because we immediately delete the schedules after completion, but it still might come in handy for looking at cost explorer for example, or if we introduce another use-case for the scheduler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*t1RtaBbHJ5mMRzbrlB0kCA.png" /></figure><p>At the end of the article, you can find some code snippets around how we set up and used the AWS resources mentioned. These code snippets have been added for illustrative purposes and are there simply for guidance.</p><h4>Other</h4><p>We had some other ideas to solve our problem and were ready to explore them further, but since the EventBridge Scheduler solution got the job done, we did not take these other ideas into consideration. Nevertheless, one might find them useful for other similar problems, so here they are.</p><p>Introduce a new (standard) queue for the rare use-case producer to send messages to (with the proper delays). The we either add a new Lambda consuming the messages from the standard queue and forwarding them to the fifo queue, or we update the fifo queue consumer to consume messages from both queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*HCNxNmA53QTXr6K-YDzG_g.png" /></figure><p>Add a new field in the message body to the fifo queue and have the fifo queue consumer handle the delay. In our specific case the delays are small (a minute), so we can have the consumer sleep for that amount, or play around with the visibility timeout of the message and send it back to the queue for a retry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Sb3sx15kXbJslqCtfUB8lQ.png" /></figure><h4>Code</h4><p>Code snippets for the EventBridge Scheduler solution.</p><p>CDK code for setting up the AWS resources:</p><pre>import * as cdk from &quot;aws-cdk-lib&quot;;<br>import * as iam from &quot;aws-cdk-lib/aws-iam&quot;;<br>import * as lambda from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import * as scheduler from &quot;aws-cdk-lib/aws-scheduler&quot;;<br>import * as sqs from &quot;aws-cdk-lib/aws-sqs&quot;;<br><br>// Set up EventBridge Scheduler-related resources<br>const scheduleGroup = new scheduler.CfnScheduleGroup(this, &#39;SchedulerGroup&#39;, {<br>  name: &#39;SQSMessageDelayer&#39;,<br>});<br>const schedulerRole = new iam.Role(this, &#39;SchedulerRole&#39;, {<br>  assumedBy: new iam.ServicePrincipal(&#39;scheduler.amazonaws.com&#39;),<br>});<br>// DLQ for messages that the Scheduler can not deliver<br>const schedulerDlq = new sqs.Queue(this, &#39;SchedulerDLQ&#39;, {<br>  retentionPeriod: cdk.Duration.days(14),<br>});<br>schedulerDlq.grantSendMessages(schedulerRole);<br><br>// Pre-existing fifo queue, grant send permissions to the scheduler role<br>const queue = new sqs.Queue(this, &#39;Queue&#39;, {<br>  fifo: true,<br>  contentBasedDeduplication: true,<br>});<br>queue.grantSendMessages(schedulerRole);<br><br>// Lambda function that handles our rare use-case<br>const rareUseCaseProducer = new lambda.Function(this, &#39;RareUseCaseProducer&#39;, {<br>  // ... other props<br>  environment: {<br>    QUEUE_ARN: queue.queueArn,<br>    SCHEDULER_ROLE_ARN: schedulerRole.roleArn,<br>    SCHEDULER_DLQ_ARN: schedulerDlq.queueArn,<br>  },<br>});<br>rareUseCaseProducer.role?.addManagedPolicy(<br>  iam.ManagedPolicy.fromAwsManagedPolicyName(<br>    &#39;AmazonEventBridgeSchedulerFullAccess&#39;<br>  )<br>);</pre><p>Code in our rare use-case producer:</p><pre>import { randomUUID } from &quot;crypto&quot;;<br>import { SchedulerClient, CreateScheduleCommand } from &quot;@aws-sdk/client-scheduler&quot;;<br>import { config } from &quot;./config&quot;;<br><br>const scheduler = new SchedulerClient({<br>  region: config.region,<br>  maxAttempts: 3,<br>});<br><br>export async function scheduleMessage(<br>  messageBody: MessageBody,<br>  delayInMs: number = 1000 * 60,<br>) {<br>  const now = new Date();<br>  const scheduledAt = new Date(now.getTime() + delayInMs);<br>  const scheduledAtIso = scheduledAt.toISOString();<br>  const scheduledAtWithoutMS = scheduledAtIso.substring(0, scheduledAtIso.length - 5);<br><br>  const message = JSON.stringify({<br>    ...messageBody,<br>    // force message uniqueness through content-based deduplication<br>    dedup: randomUUID(),<br>  });<br><br>  const scheduledCommand = new CreateScheduleCommand({<br>    Name: `Delayed-message-${messageBody.id}-${scheduledAt.getTime()}`,<br>    GroupName: &quot;SQSMessageDelayer&quot;,<br>    ScheduleExpression: `at(${scheduledAtWithoutMS})`,<br>    FlexibleTimeWindow: {<br>      Mode: &quot;OFF&quot;,<br>    },<br>    Target: {<br>      Arn: config.queueArn,<br>      RoleArn: config.schedulerRoleArn,<br>      Input: message,<br>      SqsParameters: {<br>        MessageGroupId: messageBody.id,<br>      },<br>      DeadLetterConfig: {<br>        Arn: config.schedulerDlqArn,<br>      },<br>    },<br>    ActionAfterCompletion: &quot;DELETE&quot;,<br>  });<br>  await scheduler.send(scheduledCommand);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1500726be1b2" width="1" height="1" alt=""><hr><p><a href="https://tech.trustpilot.com/aws-event-bridge-scheduler-as-a-workaround-to-sqs-fifo-queue-limitations-1500726be1b2">AWS Event Bridge Scheduler as a workaround to SQS Fifo queue limitations</a> was originally published in <a href="https://tech.trustpilot.com/">Trustpilot Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consider writing an RFC]]></title>
            <link>https://tech.trustpilot.com/consider-writing-an-rfc-6359a850611c?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6359a850611c</guid>
            <category><![CDATA[ideas]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[improvement]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[open-mind]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 13:01:34 GMT</pubDate>
            <atom:updated>2020-04-28T13:01:34.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improve your idea-conversion-funnel by writing an RFC</h3><p>How to come up with better solutions for your company, while improving your skill sets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uaBvKQtUb0YaTJxZ" /><figcaption>“A tulip in its early stages” — Photo by <a href="https://unsplash.com/@joshuafuller?utm_source=medium&amp;utm_medium=referral">Joshua Fuller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With remote work on the rise, it’s become increasingly important for people to express their opinions and concerns with team members through efficient communication channels and collaborative processes.</p><p>Clear communication between team members leads to better understanding, making it possible for people to supplement and critique each other’s work in an efficient manner. Not only does this often lead to better results for the company, but it also gives team members the opportunity to learn from each other and improve their skills.</p><h3>Collaboration at Trustpilot</h3><p>At Trustpilot, all employees are encouraged to share ideas on how we can improve processes, organizational structure, technical solutions, product offerings, etc, and these ideas trigger important dialogues between employees, which often result in more robust and efficient solutions.</p><p>Different departments and teams have different ways of sharing their ideas. It usually depends on what the challenge is and how we are trying to solve, or improve it. Some people discuss ideas within their teams, others discuss it with their manager, and some use larger groups of people with common interests or competencies within specific technologies (e.g. our front-end group).</p><p>If an employee’s idea involves fundamentally changing the way we use a type of technology or the way we deliver a product, they are encouraged to write a proposal in a Request For Comments (RFC) document. The RFC is then shared with relevant stakeholders who are asked to share their thoughts about the proposed changes and provide feedback on the proposal. The RFC is then used as a point of reference throughout the implementation phase.</p><h3>The RFC process</h3><p>Using the RFC process can improve idea generation before the document even reaches other stakeholders in a number of ways:</p><h4>It encourages you to look at past research</h4><p>First, the author of the RFC is encouraged to reflect on and document why a specific technology or approach could bring additional value to our product. They’ll need to review past research and check to see if the idea hasn’t already been considered (and rejected) in the past. Possible reasons for rejecting past ideas could be that cost outweighed the benefits at the time, the new technology wasn’t mature enough, the product wasn’t a priority, the product team wanted to prototype a fast solution in order to test a hypothesis (which then turned into a product that was never revisited), and so on. Once the author has read up on ideas from the past, they can move forward with a new, fresh point of view and think about what the most important aspects are to include in the new proposal. Looking at past ideas may also give the author an understanding of the flaws of the current setup, and this may encourage them to come up with an even better idea.</p><h4>It helps you structure and outline your idea</h4><p>Once the author has ensured that the new idea is worth exploring, they can start outlining their proposal. The author should include past ideas as well, and explain why their solution better addresses past and present challenges.</p><p>It’s important that the author stays objective when presenting the ideas, putting forth facts and figures, instead of personal opinions and preferences. By putting their ego aside and questioning and criticizing their own idea, the proposal becomes even more robust.</p><p>Depending on the scope of the idea, a proof of concept is encouraged, so that stakeholders are aware that the idea is achievable in practice. This means the author may have to spend engineering work hours developing their proof of concept. Luckily, at Trustpilot we have 20% time, meaning that all engineers are allowed to spend 20% of their work hours improving their skills, researching new technology, improving processes or, in this case, coming up with a solid proof of concept.</p><h4>It allows you to objectively compare ideas</h4><p>The proposal should include a clear comparison between the current solution and the intended one. The author should list the pros and cons of both approaches (hopefully, the pros outweigh the cons by large) so that stakeholders are less likely to show familiarity bias. Familiarity bias is a phenomenon where people tend to opt for the more familiar options (“the old” solution), even though “the new” solution may have favorable outcomes. Adding this comparison to the proposal anticipates and eliminates this bias before it can even be fully formed.</p><p>A detailed breakdown of the implementation steps can help to further convince stakeholders that the idea is worth moving forward with. By supplementing everything stated above with a detailed breakdown of the implementation plan, the author shows that they’ve thought the idea through and considered all scenarios. They’ve also shown that they’re respectful of everyone’s time, and they’re not just casually “bouncing ideas off of” their team members (which they probably already did at an earlier, more appropriate time).</p><h4>It gets you time-saving input from others</h4><p>While going through all these steps may feel time-consuming, it will save you time in the long run and has a higher probability of getting you the best results for the company. Requesting comments from teammates will show that you’re open-minded, and in return, your teammates will most likely point out crucial details that will make your proposed solution even more of a success.</p><blockquote>“If someone is able to show me that what I think or do is not right, I will happily change, for I seek the truth, by which no one was ever truly harmed. It is the person who continues in his self-deception and ignorance who is harmed.” — Marcus Aurelius</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9GKz0a0HrBegVQvX" /><figcaption>“A blooming tulip” — Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Not all of the ideas we come up with prove to be mature enough to bear fruit, but the value they offer to us is priceless. Think of it as an idea-conversion-funnel. You start off with a dozen ideas, then you end up killing half of them because you realize they’re not practical or have been disregarded in the past for valid reasons. Then, after going through the proposal process described above, you discard a few more ideas, and in the end, you are only left with one really good, solid, bias-free idea.</p><p>It’s true that many ideas don’t make the cut using this method, but you learn from the experience (and the ideas that do make it through will be stronger for it). Every time you go through a new proposal process for a new idea, you’ll discover patterns on what works and what doesn’t. Your idea-conversion-funnel will improve each time, and you’ll become faster at picking up valuable ideas and discarding invaluable ones.</p><p>In the end, using the RFC process will allow you to become more efficient at developing solid solutions for your company while developing and sharpening your own skills and qualifications at the same time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6359a850611c" width="1" height="1" alt=""><hr><p><a href="https://tech.trustpilot.com/consider-writing-an-rfc-6359a850611c">Consider writing an RFC</a> was originally published in <a href="https://tech.trustpilot.com/">Trustpilot Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Respect the DOM]]></title>
            <link>https://tech.trustpilot.com/respect-the-dom-2bbdf1deeff8?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bbdf1deeff8</guid>
            <category><![CDATA[dom]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 10:39:33 GMT</pubDate>
            <atom:updated>2019-03-18T21:07:23.207Z</atom:updated>
            <content:encoded><![CDATA[<p>Thoughts on shared responsibilities of library users and maintainers</p><h4>Who owns the DOM</h4><p>Nowadays most of the software products being shipped are single page applications which have a completely different structure than the server side rendered web pages before. One of the main differences is the shared DOM. One single page application is active beyond the initial render and the complete DOM is not recreated on every action or navigation.</p><p>The DOM is one common thing that we, the core contributors and authors of a project, share with all the maintainers of the libraries we are using. In that sense, the DOM becomes this sacred thing that we should all respect and take care of.</p><p>In a sense of ownership of the DOM, each team gets their own part of the DOM to take care of, but it’s the team that owns the project that is responsible for the DOM as a whole. This means that if you, as a library author, need to step out of your context and make changes to the DOM which are out of your scope, you are trespassing in some territory which is not primarily in your ownership. Now, if we are restrictive in regards to what parts of the DOM we can change, we will probably not have all of these nice little libraries to work with which allow us to reach our business goals with a lot less effort than if we were to do everything ourselves and that is the good part. However, if we are touching something which is not fully ours, common understanding and good manners applied, it is expected that we put it back as we found it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IAnYMOKc7AJPlODO" /><figcaption>“Nice and Clean” Photo by <a href="https://unsplash.com/@oks_ong95?utm_source=medium&amp;utm_medium=referral">Khai Sze Ong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why do we need to own the DOM</h4><p>A very common use case is when we are injecting DOM elements outside of the scope of our library, such as loading a third party script in the body, injecting a stylesheet in the head, making styling changes or attaching event listeners to elements which we did not create in the first place, and so forth. In some use cases, implementing the main feature that our library offers will obviously lead to having to interact with the context in which it is used, so we would reach out of our scope to achieve this. However, that does not give us the right to just achieve the goal we claim our library achieves and then just assume that our library stops being used at the same time as the parent app stops being used. There is a high probability that our library will be injected in the parent app dynamically which means that it might also be unmounted and destroyed at some point in time. Therefore, reaching out of our library’s context and fiddling around with the DOM means that we are leaving stuff behind after our library ends up in the parent project’s garbage (unmounted, not used, destroyed, whatever term fits). Those leftovers are now falling under the jurisdiction of the author of the project and owner of the DOM as a whole to clean up.</p><h4>Example</h4><p>In order to better illustrate what I mean, I will share an example. I was particularly careful when thinking about what example I should share. If I have chosen an npm library from a single, or a team of contributors, it wouldn’t have had that big of an impact since there are so many libraries out there and it could be that that particular one is just flawed. That is why, I have picked the Google Autocomplete widget as an example.</p><p>Here is a short explanation of the use case. You want to have a form and in there you need to enter a valid address, so what is the API that is best suited for working with addresses? First thought, it’s gotta be something that Google offers since their Maps are what we use on daily basis for navigating. So you go over to the Google Developers section and search for something that suits your needs and you find their <a href="https://developers.google.com/maps/documentation/javascript/places-autocomplete">Google Places Autocomplete widget</a>. Pretty good documentation on how to set it up and you end up with a fully functional autocompletable input field for entering an address in your form. Your form is of course rendered conditionally in your SPA (when you choose to add or edit an item). But what happens after a few invocations and usages of this widget? Here are two screenshots of the DOM after adding and updating a couple of items by using that form (which means the form got rendered and then unmounted several times, thus, the widget got created and destroyed several times as well).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*WS1UMftwwUolRLpOLuyjtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uXkU3MCWtlKKBt6QFOm5Q.png" /><figcaption>Aftermath of using the autocomplete widget — unused elements and styles in the DOM</figcaption></figure><p>The widget does not offer any on destroy callbacks or unmount events which means you end up with a bunch of items that, although hidden, are not used at all and are polluting the DOM. Now it is your responsibility, as the author and owner of the project, to clean that up by using some DOM manipulation yourself (maybe by targeting the elements based on their class, which is not documented anywhere, meaning they are internal and may change at any moment, thus breaking your clean up logic).</p><p>There are plenty of other libraries and widgets which are pretty creative in manipulating the DOM to achieve their goals that leave the DOM in a similar, or even worse situation (imagine if those div elements were not hidden 😱).</p><h4>Summary</h4><p>Let’s take more ownership of the stuff we build and clean up after ourselves.</p><p>We can start by searching for document. in our project and make sure that all of our appendChild, addEventListener , addClass , style and other DOM mutating calls are reversed and cleaned up when our code has done its purpose and is no longer needed. We can utilise the framework specific opt-ins for doing this, such as Vue’s <a href="https://vuejs.org/v2/api/#beforeDestroy">beforeDestroy</a> and React’s <a href="https://reactjs.org/docs/react-component.html#componentwillunmount">componentWillUnmount</a> (or the returning callback in case you already embraced hooks and <a href="https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect">useEffect</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bbdf1deeff8" width="1" height="1" alt=""><hr><p><a href="https://tech.trustpilot.com/respect-the-dom-2bbdf1deeff8">Respect the DOM</a> was originally published in <a href="https://tech.trustpilot.com/">Trustpilot Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supporting React pre 16.3 versions]]></title>
            <link>https://medium.com/@cvetanov/supporting-react-pre-16-3-versions-f4624f3e10e?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4624f3e10e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Sun, 27 May 2018 12:13:37 GMT</pubDate>
            <atom:updated>2018-05-27T12:13:37.253Z</atom:updated>
            <content:encoded><![CDATA[<p>How to update your React library and support older versions while utilizing all the new APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BEvCzsMxmnUwjhqH." /><figcaption>Photo by <a href="https://unsplash.com/@jacalynbeales?utm_source=medium&amp;utm_medium=referral">Jacalyn Beales</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Intro to what led me to writing this post</h4><p>A few weeks ago I was thinking about how hard (or easy) would it be to have your application support multiple languages. While thinking about this, I looked up a few existing libraries and was amazed of all the options out there. Then I broke down the problem and concluded that in order to support multiple languages in a simple manner, I need to have a map for every language where the key would be the identifier which will be used in the application and the value would be the translation for that key. This led me to thinking about making my own implementation instead of choosing a library with hope that maybe I can learn something along the way. The implementation was pretty straight forward and in the end so decoupled from the application that I thought there was definitely a chance I was going to use this in a future project as well, so why not publish this as a separate package on npm. This process of polishing the implementation and publishing it as a separate package is what led me to learning about the npm ecosystem in more details (how npm dependencies work, what type of dependencies are there, how to link local packages, etc.) and learning about some subtle differences in the React versions throughout the years which I was not aware of.</p><p>In this post I will be focusing on the library I worked on for supporting multiple languages in a React application and the process through which I went, including some, now obvious, setbacks which I ran into.</p><h4>Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3X7nxHcOWqnjc52P." /><figcaption>“Hammers and other tools arranged in a row” by <a href="https://unsplash.com/@mr_sherez?utm_source=medium&amp;utm_medium=referral">Adam Sherez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the process of building this library, I used <a href="https://github.com/transitive-bullshit/create-react-library">create-react-library</a> which is basically <a href="https://github.com/facebook/create-react-app">create-react-app</a> for libraries. You even have a create-react-app app scaffolded in the /examples folder, so you can create a link of your library by using <a href="https://yarnpkg.com/lang/en/docs/cli/link/">yarn link</a> an then add a dependency to your library from your example app by using yarn link your-library-name and see your library in action without the need of publishing it.</p><h4>Implementation details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mLEIffCDw2MLL5T5." /><figcaption>Photo by <a href="https://unsplash.com/@igorovsyannykov?utm_source=medium&amp;utm_medium=referral">Igor Ovsyannykov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The library uses React’s new <a href="https://reactjs.org/blog/2018/03/29/react-v-16-3.html">Context API</a> which came out with version 16.3 so putting a peer dependency to React version 16.3 was the first logical thing to do. After designing the final API of the library and actually implementing it, I moved to the example app to try how (and if) my library works. The example app had a dependency to React version 16.3 as well and everything seemed to click and work out of the box. Great!</p><p>Then I remembered about <a href="https://github.com/jamiebuilds/unstated">unstated</a> and how it can support older versions of React even though it uses the Context API under the hood. I remember reading somewhere something from <a href="https://medium.com/u/cc2eaf4f2cd2">Jamie Kyle</a> saying something like “If you are using an older version of React, don’t worry, I got ya.” (turned out it was right there in the README of unstated), so it intrigued me to take a look on how he does that. It turns out, he implemented the new Context API by using the old Context API and simulating event emitters which know to update a Consumer when a Provider’s value is updated. Not the point of this story, but it gave me an idea that maybe if I use his solution (which is of course in a separate package and not bundled in unstated itself, called <a href="https://github.com/jamiebuilds/create-react-context">create-react-context</a>), maybe I can also support older versions of React with my library. I couldn’t wait to come back home and give it a go, but then there was another setback called getDerivedStateFromProps which I was using as well.</p><p>A few days later, Twitter to the rescue! I came upon a <a href="https://twitter.com/ryanflorence/status/998418720912392194">thread</a> where <a href="https://github.com/reactjs/react-lifecycles-compat">react-lifecycles-compat</a> was mentioned. react-lifecycles-compat polyfills your component by supporting new lifecycle methods in old versions of React by combining the deprecated lifecycle methods from the previous versions (componentWillMount, componentWillReceiveProps and componentWillUpdate) and sprinkling some tricks over them. Having found polyfills (or ponyfills) for the two things which are React v16.3 specific, I was able to proceed with my wish to support older React versions.</p><p>Step 1: update the peer dependencies of the library to ^0.14.9 || ^15.0.0 || ^16.0.0 (0.14.9 being the oldest one supported by react-lifecycles-compat).</p><p>Step 2: install create-react-context and react-lifecycles-compat and polyfill the implementation to be pre-v16.3 compliant.</p><p>Step 3: try the example application with the updated library — it worked.</p><p>Step 4: downgrade the React version in the example application to a version which does not support Context API and getDerivedStateFromProps — it didn’t work. So what can be the problem?</p><p>Problem 1: I was using React.Fragment in the example application where I downgraded React’s version to 15 so I replaced that with a div.</p><p>Problem 2: having multiple children directly in the provider when arrays as children are supported from React v16 onwards. Again, I did the thing we React developers do best, I wrapped them all in div.</p><p>Problem 3: Similar to problem 2, related to features of the React library itself. This one, being harder to debug, was actually the translations being rendered as plain strings which is not supported in previous versions of React, so I decided to wrap them in a span, but this had to be done in the library and not in the example application, so I did not really like that, but for the sake of making it work, I compromised. Then again, I came back to the twitter <a href="https://twitter.com/ryanflorence/status/998418720912392194">thread</a> which introduced me to react-lifecycles-compat and stole <a href="https://medium.com/u/162352c45b6e">Ryan Florence</a>’s trick for determining the React version and only added that extra span when needed.</p><p>A method which I used while debugging the problems was moving the library implementation inside the example application and use it directly instead of linking it. On “why I had to do this?”, the linked package was bundled and minified which led to not that great of an error message stack trace when browsing the console. So I created a /local-lib folder where I put everything from the library, imported the provider and the translation components from there, and debugged the more descriptive error messages.</p><p>Next step would be publishing the library and trying it out directly instead of using local links to it, but unfortunately, the name I chose for it triggered a spam detection filter on npm and I can not try this yet 😔.</p><h4>Conclusion</h4><p>I can say that I’ve come out with two things out of this entire process.</p><p>One is that you should always go for trying out something new yourself (writing that library) because chances are you will almost certainly learn at least one new thing 🤓.</p><p>The other is that the React community is awesome and all of them (both core team members and other OSS developers) really care about the library and the ecosystem and contribute to making it a better place for us all 🙏.</p><p>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4624f3e10e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should we use static typing in JavaScript?]]></title>
            <link>https://medium.com/netscape/should-we-use-static-typing-in-javascript-d9631af9d221?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9631af9d221</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[v8]]></category>
            <category><![CDATA[flowtype]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Sat, 28 Oct 2017 17:21:43 GMT</pubDate>
            <atom:updated>2017-10-28T17:21:43.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Using static typing in JavaScript has many benefits which you might already know. However, there is one hidden benefit which is not so easy to spot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4FCkHqfJTG4e13AT8H3pg.jpeg" /></figure><p>Before we mention the hidden benefit which is often overlooked because it is not so obvious, let’s make a short list of all the other benefits static typing offers. The first and probably most evident is:</p><h4>Compile time error detection</h4><p>By using static typing, it is much easier for the type checker to detect errors which might occur from wrong parameter types. Here is a snippet for that from the official <a href="https://flow.org/en/docs/getting-started/">FlowType</a> getting started guide:</p><pre><em>// @flow</em><br>function square(n: number): number {<br>  return n * n;<br>}<br><br>square(&quot;2&quot;); <em>// Error! </em></pre><p>FlowType easily detects that the parameter with which the square function is invoked is not the same type as the function expects and therefore shouts out an error.</p><h4>Elimination of type checking for input parameters</h4><p>This might be related to the first one. By using types for your input parameters, you avoid the verbose (and often repeating) logic for ensuring the function is used in the right way. Verifying that the input parameters are in the format the author of the function expects is a not so hard task from a programmer’s perspective so it can, and should, be automated by delegating it to the type checker.</p><h4>Avoiding verbose documentation</h4><p>You might have probably seen some not so helpful documentation where only the type of the parameter is written:</p><pre>/**<br>* Does some transformation to the given word.<br>*<br>* @param {string} foo - The word to transform.<br>* @returns {string} The transformed word.<br>*/<br>function transform(foo) {<br>  // transform `foo` to something<br>}</pre><p>The documentation here is not really useful and might take up more lines than the function itself and take away the attention of the developer who is looking up the function. By introducing static typing to the input parameters and the return type of the function, we can omit the documentation altogether moving the focus when reading the snippet to the function itself.</p><pre>function transform(foo: string): string {<br>  // transform `foo` to something<br>}</pre><h4>Transition to using immutable objects</h4><p>Before ES6, var was the only variable type that could be used in JavaScript. After the addition of let and const, we surely are in a better state. Adding custom types of objects using static typing would be the next step to avoid variable reassignments which is a code smell. Using const and custom object types could lead developers to practice immutability and avoid mutating variables which is one of the principles in functional programming. This benefit leads us to the hidden benefit which I mentioned previously.</p><h4>Performance improvements in V8</h4><p>V8 is an open source JavaScript engine which is used in Google Chrome and in NodeJS (which covers way more than half of the environments for which JavaScript applications are written). The performance improvement in using static typing for an application which runs on V8 is in the way it handles access to properties on an object. The main motivation for writing this article came after reading an <a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e">article</a> about how JavaScript works and some insights into the way the V8 engine parses/compiles/optimizes the code. The thing that caught my attention were the hidden classes.</p><p>Before reading the mentioned article, I was almost certain that accessing a property on an object is a constant O(1) operation, something like a hash map, and therefore I ended up having lots of commits in our project which were transforming Array.prototype.indexOf() calls to creating an object where the keys would be some id and just looking up the value from the created object. As it turns out, due to JavaScript being a dynamically typed language, this might not always be the case.</p><p>Hidden classes in V8 are responsible for accessing properties of objects. For every property added to an object, a new hidden class is created which contains info about where can that property be found (associates an offset to a property). So if we have two objects which represent a person, but their properties are assigned in a different order, accessing the properties on these objects might not behave in the same way due to the different hidden classes which got created (different offsets for the properties). Consider the following snippet:</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>}</pre><pre>const player = new Person(&#39;Jane&#39;, 22);<br>const referee = new Person(&#39;Joe&#39;, 22);<br>// here both variables have a shared hidden class</pre><pre>referee.nationality = &#39;Germany&#39;;</pre><p>Up until the assignment of nationality to the referee both variables were sharing the same hidden class generated by V8 so the engine has generated optimized assembly code for accessing and assignment of properties on the player and referee variables. When a new property was introduced, V8 ends up generating a new hidden class for the referee object and therefore accessing properties on objects of the allegedly same class will be done in different ways which will add some overhead to it.</p><p>By using static typing, the type checker supplies enough information to the compiler of what are the available properties an object can have which will make it easier for the engine to generate shared hidden classes for all objects of that type and optimize the generated assembly for accessing/modifying those properties.</p><h4>Summary</h4><p>Taking into consideration all the advantages mentioned above, static typing is something which should seriously be considered when starting a new project in JavaScript. The only disadvantage I could think of to introducing static typing to your project and your team is that it will be yet another thing to learn for your colleagues.</p><p>So the question you should be asking is not “Why should we use static typing?”, but <strong>“Why are we not using static typing?”</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9631af9d221" width="1" height="1" alt=""><hr><p><a href="https://medium.com/netscape/should-we-use-static-typing-in-javascript-d9631af9d221">Should we use static typing in JavaScript?</a> was originally published in <a href="https://medium.com/netscape">Netscape</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[redux mapStateToProps optimization]]></title>
            <link>https://medium.com/@cvetanov/redux-mapstatetoprops-optimization-5880078a8a7a?source=rss-74188c0bf1ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5880078a8a7a</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cvetanov Goce]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 19:09:22 GMT</pubDate>
            <atom:updated>2017-03-20T19:10:41.845Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, what is <a href="https://github.com/reactjs/redux">redux</a>?</p><p>Redux is an open source implementation (aren’t they all?) of the flux architecture suggested by Facebook as a compliant standard for working with data in large React applications.</p><p>Created by <a href="https://twitter.com/dan_abramov">Dan Abramov</a>, who now works on the <a href="https://github.com/facebookincubator/create-react-app">create-react-app</a> (by the way, the best generator for scaffolding production ready React apps), it contains everything suggested from the flux pattern in an easy-to-use manner and also contains some JS tricks (like defining an empty function and later checking it’s name to determine if the <a href="https://github.com/reactjs/redux/blob/master/src/index.js">code</a> has been minified) which is not the main content of this article.</p><p>Redux itself is a very simple implementation and there was an interesting <a href="https://medium.com/front-end-hacking/redux-reimplemented-in-12-lines-of-code-2c20fd7b151c#.yn2e0uhtm">article</a> which points out that the patterns used in the implementation of redux can be done in as few as 12 lines of code. This is of course without all of the optimization redux offers and the sanity checks it provides for better developer experience.</p><p>For using redux in React applications, the <a href="https://github.com/reactjs/react-redux">react-redux</a> module is available in npm and it provides a very simple connect function which (you guessed it) connects your component to the redux store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xaxaXOn-mCsSS9r3m9tW6Q.png" /></figure><p>The main content of this article is how to obtain a minor optimization on connected components which use their own props for querying the redux state.</p><p>Let’s say that we have a blog application and we want a particular component MyBlogs to display all the blogs for the logged in user. We have the logged in user somewhere else in our application and we pass it down to the MyBlogs component as a prop. Now we want to display all of the blogs whose author is the logged in user. Redux’s mapStateToProps offers the props of the component as a second argument. We can use them to query the redux state and return a slice of it depending on some prop of the component. This will look something like this:</p><pre>function mapStateToProps(state, ownProps) {<br>  return {<br>    blogs: state.blogs.filter(blog =&gt; blog.author === ownProps.user)<br>  };<br>}</pre><pre>export default connect(mapStateToProps)(MyBlogs);</pre><p>We create a mapStateToProps implementation which uses the user from the component’s own props and returns all of the blogs from the redux state for that particular user.</p><p>Fortunately for us, the guys contributing to redux and react-redux are great, open to new ideas and always making contribution to the library’s performance and documentation and therefore, they offer us an option to perform a minimal optimization here.</p><h4>mapStateToProps can now return a function instead of an object.</h4><blockquote>Note: in advanced scenarios where you need more control over the rendering performance, mapStateToProps() can also return a function. In this case, <em>that</em> function will be used as mapStateToProps() for a particular component instance. This allows you to do per-instance memoization. [from the official docs]</blockquote><p>If redux receives an implementation which returns a function it performs a closure for wrapping the own props of the component and therefore bypasses the invocation of the mapStateToProps every time the component changes it’s props received from the parent component. It creates a so called <em>purePropsSelector</em>. How this is done can be seen <a href="https://github.com/reactjs/react-redux/blob/master/src/connect/wrapMapToProps.js">here</a>.</p><p>We can now rework our implementation of the MyBlogs component in the following way and achieve a minor performance boost.</p><pre>function mapStateToPropsFactory(initialState, ownProps) {<br>  // a closure for ownProps is created<br>  // this factory is not invoked everytime the component<br>  // changes it&#39;s props</pre><pre>  return function mapStateToProps(state) {<br>    return {<br>      blogs:<br>        state.blogs.filter(blog =&gt; blog.author === ownProps.user)<br>    };<br>  };<br>}</pre><pre>export default connect(mapStateToPropsFactory)(MyBlogs);</pre><h4>TL;DR;</h4><p>When using the component’s own props inside mapStateToProps, wrap the mapStateToProps function with a mapStateToPropsFactory which will return the function itself instead of the object directly and redux will not invoke your mapStateToPropsFactory for every parent prop changes.</p><p>Thanks to my mentor <a href="https://medium.com/u/e246c08fd8e4">Oliver Lazoroski</a> for pointing this out to me and I will share his TL;DR; remark on this:</p><blockquote>Think of it like this, if redux receives a mapStateToProps which has ownProps as second argument and it returns an object, it switches off every optimization it makes for your connected component.</blockquote><p>This was my first of many articles on medium and I hope you will find it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5880078a8a7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>