<?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 Augusto Barreira on Medium]]></title>
        <description><![CDATA[Stories by Augusto Barreira on Medium]]></description>
        <link>https://medium.com/@barreira?source=rss-14405318642a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PWUMFFWSa0wZsNCx.</url>
            <title>Stories by Augusto Barreira on Medium</title>
            <link>https://medium.com/@barreira?source=rss-14405318642a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:31:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barreira/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[Let the UI Ask, Let Bloc Decide]]></title>
            <link>https://medium.com/@barreira/let-the-ui-ask-let-bloc-decide-3c939dfe6772?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c939dfe6772</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-10-19T12:31:01.805Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How Bloc helps separate Flutter widgets from business logic</strong></h3><p>When an app is small, putting a little logic inside a `StatefulWidget` feels natural. A button is pressed, `setState` updates a value, and the screen updates immediately. For a toggle or a simple state that is attached to the same file, that can be all you need.</p><p>The headache starts when the widget has to do more than just display things. It may validate input, apply business rules, coordinate a request, handle errors, and decide what the user sees next. As those responsibilities accumulate, the screen becomes harder to understand and harder to change safely.</p><p>Bloc offers a simple boundary: <strong>The UI describes what happened; the Bloc decides what that means.</strong></p><h3><strong>When the widget owns everything</strong></h3><p>Imagine a screen that lets a user add one to a balance. With `setState`, the UI and the rule live together:</p><pre>class BalancePage extends StatefulWidget {<br>  const BalancePage({super.key});<br><br>  @override<br>  State&lt;BalancePage&gt; createState() =&gt; _BalancePageState();<br>}<br><br>class _BalancePageState extends State&lt;BalancePage&gt; {<br>  int balance = 12;<br><br>  void addOne() {<br>    setState(() {<br>      balance++;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Text(&#39;$balance&#39;),<br>        ElevatedButton(<br>          onPressed: addOne,<br>          child: const Text(&#39;Add one&#39;),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>There is nothing wrong with this. The widget is small, the behaviour is simple and local, the code is easy to follow.</p><p>Now imagine the rule changes: the balance cannot go below zero, updates must be recorded, another screen needs to display the same value… To much pal, too much…</p><h3><strong>Give the rule a home</strong></h3><p>With Bloc, the button sends an event. The Bloc handles the event and emits a new state:</p><pre>sealed class BalanceEvent {}<br><br>class AddOne extends BalanceEvent {}<br><br>class BalanceState {<br>  const BalanceState(this.value);<br><br>  final int value;<br>}<br><br>class BalanceBloc extends Bloc&lt;BalanceEvent, BalanceState&gt; {<br>  BalanceBloc() : super(const BalanceState(12)) {<br>    on&lt;AddOne&gt;((event, emit) {<br>      emit(BalanceState(state.value + 1));<br>    });<br>  }<br>}</pre><p>The widget’s job becomes expressing user intent and rendering the result:</p><pre>BlocBuilder&lt;BalanceBloc, BalanceState&gt;(<br>  builder: (context, state) {<br>    return Column(<br>      children: [<br>        Text(&#39;${state.value}&#39;),<br>        ElevatedButton(<br>          onPressed: () =&gt; context.read&lt;BalanceBloc&gt;().add(AddOne()),<br>          child: const Text(&#39;Add one&#39;),<br>        ),<br>      ],<br>    );<br>  },<br>)</pre><p>The flow is explicit:</p><p><strong>Tap → ‘AddOne’ event → Bloc applies the rule → new `BalanceState` → UI rebuilds</strong></p><p>That separation gives each part one clear responsibility:</p><p>- <strong>The widget</strong> translates interaction into an event and displays state.</p><p>- <strong>The Bloc</strong> owns the decision-making for that feature.</p><p>- <strong>The state</strong> describes the current result the UI needs to show.</p><h3><strong>Why this helps as an app grows</strong></h3><p>When behaviour lives in a Bloc, it can be tested without building the screen. A test can start with a balance of 12, add `AddOne`, and verify that the next state contains 13. If a rule changes later, the test helps identify whether the behavior changed as intended.</p><p>Instead of searching through a large widget for every place a value might be modified, a developer can look for the events that affect that feature.</p><p>The UI no longer needs to know how the business rule works. It asks for an action; the Bloc owns the response. That makes screens easier to keep focused on presentation as requirements expand.</p><h3><strong>Structure has a cost</strong></h3><p>Bloc is not automatically better for every piece of state. It introduces concepts, files, and some boilerplate. For a one-off local animation toggle or a quick prototype, `setState` may be clearer and quicker.</p><p>Use the structure when it solves a real problem: behavior is growing, multiple parts of the app need the same state, or the rules need independent tests. Keep simple, local UI details local.</p><p>The goal is not to remove logic from every widget. It is to give important business rules a clear home — so the UI can stay focused on what it does best: helping people interact with the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c939dfe6772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Vite + TypeScript App to GitHub Pages Using GitHub Actions (Without Tracking the…]]></title>
            <link>https://medium.com/@barreira/deploying-a-vite-typescript-app-to-github-pages-using-github-actions-without-tracking-the-8c6d7a6db979?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c6d7a6db979</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 12:41:01 GMT</pubDate>
            <atom:updated>2026-08-04T12:41:01.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Vite + TypeScript App to GitHub Pages Using GitHub Actions (Without Tracking the `/dist` Folder)</h3><p>In modern web development, continuous integration and deployment (CI/CD) have become essential practices. When building a frontend application with Vite and TypeScript, one common challenge is deploying to GitHub Pages without cluttering your repository with build artifacts. This article walks you through setting up a seamless deployment pipeline using GitHub Actions, where the built files never touch your main branch.</p><h3>Why Avoid Tracking the `dist` Folder?</h3><p>Before diving into the implementation, let’s understand why you shouldn’t track the `dist` folder:</p><p>1. <strong>Repository bloat</strong>: Build files can be large and numerous, increasing your repository size. Sometimes you can even reach the limit for your repo doing so, specially in mobile Apps.<br>2. <strong>Merge conflicts</strong>: Generated files often cause unnecessary merge conflicts<br>3. <strong>Confusion</strong>: It becomes unclear which files are source code and which are build artifacts, since you don’t interact with the builded files your git will track a bunch of incomprehensive files<br>4. <strong>CI/CD best practices</strong>: Build artifacts should be ephemeral and generated on-demand</p><h3>Project Setup</h3><p>First, let’s create a new Vite project with TypeScript support:</p><pre>npm create vite@latest my-app - - template react-ts<br>cd my-app<br>npm install</pre><p>Your project structure will look like this:</p><pre>my-app/<br>├── src/<br>│ ├── App.tsx<br>│ ├── main.tsx<br>│ └── …<br>├── index.html<br>├── package.json<br>├── tsconfig.json<br>├── vite.config.ts<br>└── .gitignore</pre><h3>Configure Vite for GitHub Pages</h3><p>Vite needs to know the base path for your GitHub Pages deployment. Update your `vite.config.ts`:</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>export default defineConfig({<br> plugins: [react()],<br> base: &#39;/your-repo-name/&#39;, // Replace with your repository name, in my case: &quot;github-pages-deploy&quot;<br>})</pre><h3><strong>Add Base URL to Your Router (If Using React Router)</strong></h3><p>If you’re using React Router, you’ll need to set the `basename` property:</p><pre>import { BrowserRouter } from &#39;react-router-dom&#39;<br><br>function App() {<br>  return (<br>    &lt;BrowserRouter basename=&quot;/your-repo-name/&quot;&gt;<br>      {/* Your routes */}<br>    &lt;/BrowserRouter&gt;<br>  )<br>}</pre><h3>Update .gitignore</h3><p>Ensure the `dist` folder is excluded from version control:</p><pre># .gitignore<br>node_modules<br>dist<br>dist-ssr<br>*.local</pre><h3>Create the GitHub Actions Workflow</h3><p>Now, let’s set up the deployment pipeline. Create a `.github/workflows/deploy.yml` file:</p><pre>name: Deploy to GitHub Pages<br><br>on:<br>  push:<br>    branches: [&#39;main&#39;]  # or &#39;master&#39;<br>  workflow_dispatch:    # Allow manual trigger<br><br>permissions:<br>  contents: read<br>  pages: write<br>  id-token: write<br><br>concurrency:<br>  group: &#39;pages&#39;<br>  cancel-in-progress: true<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br>        <br>      - name: Setup Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: 20<br>          cache: &#39;npm&#39;<br>          <br>      - name: Install dependencies<br>        run: npm ci<br>        <br>      - name: Build<br>        run: npm run build<br>        <br>      - name: Upload artifact<br>        uses: actions/upload-pages-artifact@v3<br>        with:<br>          path: ./dist<br><br>  deploy:<br>    environment:<br>      name: github-pages<br>      url: ${{ steps.deployment.outputs.page_url }}<br>    runs-on: ubuntu-latest<br>    needs: build<br>    steps:<br>      - name: Deploy to GitHub Pages<br>        id: deployment<br>        uses: actions/deploy-pages@v4</pre><h3>Understanding the Workflow</h3><p>Let’s break down what this workflow does:</p><p>1. <strong>Trigger</strong>: The workflow runs on every push to the main branch and can also be triggered manually<br>2. <strong>Build job</strong>: Installs dependencies and builds the project, generating the `dist` folder<br>3. <strong>Artifact upload</strong>: Uploads the `dist` folder as a deployment artifact (not stored in the repository)<br>4. <strong>Deploy job</strong>: Deploys the artifact to GitHub Pages</p><p>Key points:<br>- The `dist` folder is never committed to the repository<br>- Build artifacts are stored temporarily by GitHub Actions<br>- The deployment uses GitHub’s Pages deployment API</p><h3>Configure GitHub Pages</h3><p>1. Go to your repository on GitHub<br>2. Navigate to <strong>Settings</strong> → <strong>Pages</strong><br>3. Under “Build and deployment,” select <strong>GitHub Actions</strong> as the source: <a href="https://docs.github.com/assets/cb-40340/images/help/pages/actions-source-settings.png"><strong>GitHub Pages Configuration</strong></a></p><h3>Test Your Deployment</h3><p>Now you can test the full deployment process:</p><p>1. Push your changes to the main branch:</p><pre>git add .<br>git commit -m &quot;Initial setup with GitHub Actions deployment&quot;<br>git push origin main</pre><p>2. Go to the <strong>Actions</strong> tab in your repository to watch the workflow run<br>3. Once completed, visit `<a href="https://your-username.github.io/your-repo-name/%60">https://your-username.github.io/your-repo-name/`</a></p><h3>Conclusion</h3><p>You now have a complete CI/CD pipeline that:</p><p>- Builds your Vite + TypeScript app automatically<br>- Deploys to GitHub Pages without tracking build artifacts<br>- Maintains a clean repository with only source code<br>- Provides automated deployments for every push</p><p>This setup follows industry best practices and keeps your repository clean and maintainable. The separation of source code and build artifacts makes collaboration easier and reduces the risk of deployment-related issues.</p><p>Remember to always test your deployment after significant changes and keep your workflow file updated as your project evolves. Happy deploying!</p><p>#git #github #deploy #react #vite</p><p><strong>Source code</strong>: <a href="https://github.com/barreiradlc/github-pages-deploy/">https://github.com/barreiradlc/github-pages-deploy/</a></p><p><strong>Hosted App</strong>: <a href="https://barreiradlc.github.io/github-pages-deploy/">https://barreiradlc.github.io/github-pages-deploy/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c6d7a6db979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Types and Interfaces in TypeScript]]></title>
            <link>https://medium.com/@barreira/understanding-types-and-interfaces-in-typescript-039d04b36491?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/039d04b36491</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[type]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 03:28:06 GMT</pubDate>
            <atom:updated>2025-10-07T03:28:06.776Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is a dynamically and weakly typed language, so it comes <strong><em>TypeScript.</em></strong></p><p>TypeScript is a powerful superset of JavaScript that introduces static typing to improve code quality and developer productivity.</p><p>When you start diving into TypeScript that introduces static typing to enhance code quality and developer productivity, two ways for defining the shape of your data are type and interface.</p><p>JavaScript itself is dynamically and weakly typed, so TypeScript’s strong typing features, particularly types and interfaces, play a crucial role in building robust and maintainable applications.</p><p>If you’ve ever wondered, “which one is better, typeor interface?&quot; the real question should be: &quot;Should I use type or interface here?&quot;. Why? Because both have their particular use cases.</p><p>While they often serve similar purposes and can be interchangeable, understanding their nuances, strengths, and limitations is essential for writing clean, effective, and scalable TypeScript code.</p><h3>What Are Types and Interfaces?</h3><p>At a high level, types and interfaces in TypeScript are type formats used to define the shape of data. They tell the compiler what properties an object should have, what types functions should accept and return, and more.</p><blockquote><em>Essencially, both </em><em>type and </em><em>interface are used to describe the structure of objects.</em></blockquote><h3>Example:</h3><pre>// Using `interface`<br>interface PersonInterface {<br>  name: string;<br>  age: number;<br>}<br><br>// Using `type`<br>type PersonType = {<br>  name: string;<br>  age: number;<br>};<br><br>// Both can be used to type a variable<br>const person1: PersonInterface = { name: &quot;Alice&quot;, age: 30 };<br>const person2: PersonType = { name: &quot;Bob&quot;, age: 25 };</pre><p>In this basic example, there’s no functional difference. The choice is mostly stylistic. However, as your needs become more complex, their distinct capabilities start to show.</p><h3>Key differences between types and Interfaces and when to use them</h3><h4>1. Extending and Intersecting</h4><p><strong><em>Interface: Uses </em></strong><strong><em>extends</em></strong></p><p>Interfaces are great for declaration merging and classical object-oriented inheritance. They are explicitly designed to be extended.</p><pre>interface Animal {<br>  name: string;<br>}<br><br>interface Bear extends Animal {<br>  honey: boolean;<br>}<br><br>const bear: Bear = {<br>  name: &quot;Winnie&quot;,<br>  honey: true,<br>};</pre><p><strong><em>Type: Uses </em></strong><strong><em>&amp; (Intersection)</em></strong></p><p>Types use the intersection operator &amp; to combine existing types.</p><pre>type Animal = {<br>  name: string;<br>};<br><br>type Bear = Animal &amp; {<br>  honey: boolean;<br>};<br><br>const bear: Bear = {<br>  name: &quot;Winnie&quot;,<br>  honey: true,<br>};</pre><blockquote><em>While you could achieve similar results with type intersections (</em><em>&amp;), the interface approach provides:</em></blockquote><pre>// With interfaces - clear hierarchy<br>interface Animal { <br>	name: string <br>}<br><br>interface Bear extends Animal  { <br> color: string <br>}<br><br>interface Panda extends Bear { <br> kungFu: boolean <br>}<br><br>// With type intersections - less clear<br>type Animal = { <br> name: string <br>}<br><br>type Bear  = Animal &amp; { <br> color: string <br>}<br><br>type Panda = Bear &amp; { <br> kungFu: boolean <br>}<br><br>// The interface approach wins when you need to override or extend<br>// the same interface multiple times with declaration merging</pre><p>The key advantage is that interface extending creates a <strong>declarative, hierarchical structure</strong> that’s much easier to understand and maintain as your type system grows in complexity.</p><p>The syntax clearly communicates the “is-a” relationship, making your code more self-documenting.</p><h3>2. Adding Fields Post-Definition</h3><p><strong><em>Interface: Declaration Merging</em></strong></p><p>This is a unique feature of interface. If you declare an interface with the same name multiple times, TypeScript will merge them into a single interface.</p><pre>interface User {<br>  name: string;<br>}<br><br>interface User {<br>  age: number;<br>}<br><br>// The User interface now has both `name` and `age`<br>const user: User = {<br>  name: &quot;Alice&quot;,<br>  age: 30, // This is valid because of merging<br>};</pre><p>This is incredibly useful for augmenting existing types, such as those from third-party libraries or built-in objects like Window.</p><p><strong><em>Type: A type cannot be changed after being defined.</em></strong></p><p>A type alias, once declared, is fixed. You cannot have two types with the same name in the same scope.</p><pre>type User = {<br>  name: string;<br>};<br><br>// 🚨 ERROR: Duplicate identifier &#39;User&#39;<br>type User = {<br>  age: number;<br>};</pre><h3>3. Defining Primitives, Unions, and Tuples</h3><p><strong><em>Type: The Versatile Choice</em></strong></p><p>The type keyword is more flexible for defining types that are not just object shapes.</p><pre>// **Union Types**<br><br>type ID = string | number;<br>type Status = &quot;success&quot; | &quot;error&quot; | &quot;pending&quot;;<br>// **Tuples**<br>type Data = [number, string]; // e.g., [404, &quot;Not Found&quot;]<br>// **Primitives**<br>type Name = string;</pre><p><strong><em>Interface: Limited to Object Shapes</em></strong></p><p>An interface can only describe the shape of an object. It cannot be used to define a union, tuple, or primitive.</p><pre>// 🚨 ERROR: An interface cannot define a union type<br>interface ID = string | number;</pre><h3>So now there’s the question: Which One Should You Choose?</h3><p>Considering the limitations of each and the personal choices that I make:</p><h3>Use interface for...</h3><ol><li><strong>Object-Oriented Design:</strong> When you are modeling object hierarchies with classical inheritance (extends). This is their natural domain.</li><li><strong>Library and API Definitions:</strong> Declaration merging is a killer feature for extending types you don’t control. If you’re writing a library, providing an interface allows your users to extend it if needed.</li><li><strong>Consistency in a Codebase:</strong> If your team prefers the more “declarative” and OOP-style syntax.</li></ol><h3>Use type for...</h3><ol><li><strong>Union Types:</strong> This is the most common and compelling reason to reach for type. type Status = &quot;success&quot; | &quot;error&quot; is concise and clear.</li><li><strong>Tuples:</strong> Defining fixed-length arrays with specific types for each position.</li><li>Complex types such as functions and umore complex utility ones.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*ZsSjokkf4ZsNx_FPNK5agQ.png" /></figure><h3>Conclusion</h3><p>There is no single “correct” answer, and you will likely use both. The key is to be consistent within your project.</p><p>By understanding the strengths and limitations of each, you can leverage both type and interface to write TypeScript that is not only type-safe but also elegant and maintainable.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=039d04b36491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Only One Level of Indentation Per Method: A Key Principle in Object Calisthenics]]></title>
            <link>https://medium.com/@barreira/only-one-level-of-indentation-per-method-a-key-principle-in-object-calisthenics-43f5f4d5b15b?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f5f4d5b15b</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[object-calisthenics]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 26 May 2025 12:02:26 GMT</pubDate>
            <atom:updated>2025-06-05T12:43:11.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Object Calisthenics is a set of programming exercises designed to improve software design skills by imposing constraints that encourage better coding practices. Among its nine rules, “Only One Level of Indentation Per Method” stands out as a powerful technique for creating cleaner, more maintainable code. This article explores this principle, its benefits, and how to apply it effectively.</p><h3>Understanding the Rule</h3><p>The “Only One Level of Indentation Per Method” rule states that within any given method, there should be no more than one level of indentation. This means:</p><p>- No nested `if` statements<br>- No loops within loops<br>- No complex conditional blocks</p><p>If you find yourself needing to indent again (adding a second level), that code should be extracted into a new method.</p><h4>Why This Matters</h4><p>1 -. Improved Readability<br>Methods with single indentation levels are easier to read and understand at a glance. The cognitive load is reduced when you don’t have to mentally parse multiple nested structures.</p><p><strong>2 - Better Abstraction<br></strong>Forcing yourself to extract nested code into separate methods encourages proper abstraction. Each method does one thing and does it well. Like SRP i<em>n SOLID</em></p><p><strong>3 - Easier Maintenance<br></strong>Smaller methods with single responsibilities are easier to modify, test, and debug. Changes are less likely to introduce unexpected side effects.</p><p><strong>4 - Reduced Complexity<br></strong>Deeply nested code often indicates high cyclomatic complexity. Flattening the structure makes the code’s logic more straightforward.</p><h3>How to Apply the Rule</h3><h4><strong>Before (Violation):</strong></h4><pre>public void processOrder(Order order) {<br>    if (order.isValid()) {<br>        for (Item item : order.getItems()) {<br>            if (item.isInStock()) {<br>                item.reserve();<br>                if (order.isPriority()) {<br>                    item.markForExpressShipping();<br>                }<br>            } else {<br>                item.backorder();<br>            }<br>        }<br>        order.confirm();<br>    } else {<br>        order.reject(&quot;Invalid order&quot;);<br>    }<br>}</pre><h4>After (Compliant):</h4><pre>public void processOrder(Order order) {<br>    if (!order.isValid()) {<br>        order.reject(&quot;Invalid order&quot;);<br>        return;<br>    }<br>    <br>    processItems(order);<br>    order.confirm();<br>}<br><br>private void processItems(Order order) {<br>    order.getItems().forEach(this::processItem);<br>}<br><br>private void processItem(Item item) {<br>    if (item.isInStock()) {<br>        reserveItem(item);<br>    } else {<br>        item.backorder();<br>    }<br>}<br><br>private void reserveItem(Item item) {<br>    item.reserve();<br>    if (item.getOrder().isPriority()) {<br>        item.markForExpressShipping();<br>    }<br>}</pre><h4>Techniques to Achieve Single Indentation</h4><p>1. <strong>Early Returns</strong>: Use guard clauses to handle edge cases at the start of methods<br>2. <strong>Method Extraction</strong>: Break down complex logic into smaller methods<br>3. <strong>Polymorphism</strong>: Replace conditional logic with polymorphic behavior<br>4. <strong>Streams</strong>: Use functional programming constructs to flatten iteration<br>5. <strong>Null Objects</strong>: Replace null checks with null object pattern</p><h4>Common Challenges and Solutions</h4><p><strong>Challenge</strong>: “But my logic is inherently nested!”<br><strong>Solution</strong>: The nesting might indicate your method is doing too much. Break it down into smaller steps.</p><p><strong>Challenge 2 </strong>“I’ll end up with too many small methods!”<br><strong>Solution</strong>: Small, well-named methods are preferable to large, complex ones. They’re easier to test and reuse.</p><p><strong>Challenge 3</strong>: “This seems like it will make my code longer!”<br><strong>Solution</strong>: While you may have more methods, each will be simpler. The overall cognitive complexity is reduced.</p><h4>Benefits in Practice, I’ll be able to</h4><p>Teams that adopt this practice often report:</p><ul><li>Fewer bugs in conditional logic</li><li>Easier onboarding for new developers</li><li>More flexible code that’s easier to modify</li><li>Easier to debug</li><li>Better test coverage as smaller methods are easier to test</li></ul><h3>Conclusion</h3><p>The “Only One Level of Indentation Per Method” rule is more than just a stylistic preference — it’s a practical technique that encourages developers to create simpler, more maintainable code. Although it may seem restrictive initially, particularly when dealing with complex business logic, the long-term benefits to code quality make it worth the effort.Like any exercise, Object Calisthenics works best when practiced consistently. Start applying this rule in your next coding session, and over time you’ll find your methods becoming cleaner, more focused, and more maintainable.</p><h3>Refs</h3><ol><li><strong>“One Level of Indentation per Method” — William Durand. </strong>A practical breakdown of why this rule matters. - <a href="https://williamdurand.fr/2013/06/03/object-calisthenics/#4-only-one-level-of-indentation-per-method">Blog Post</a></li><li><a href="https://medium.com/@rafaelcruz_48213/desenvolva-um-c%C3%B3digo-melhor-com-object-calisthenics-d5364767a9ba"><strong>“</strong></a><strong>Desenvolva um código melhor com Object Calisthenics</strong><a href="https://medium.com/@rafaelcruz_48213/desenvolva-um-c%C3%B3digo-melhor-com-object-calisthenics-d5364767a9ba"><strong>” — </strong></a><strong><br>Rafael Cruz</strong><a href="https://medium.com/@rafaelcruz_48213/desenvolva-um-c%C3%B3digo-melhor-com-object-calisthenics-d5364767a9ba"> - </a><a href="https://medium.com/@rafaelcruz_48213/desenvolva-um-c%C3%B3digo-melhor-com-object-calisthenics-d5364767a9ba">Blog post</a></li><li><strong>“Object Calisthenics” - Jeff Bay</strong><a href="https://bolcom.github.io/student-dojo/legacy-code/DevelopersAnonymous-ObjectCalisthenics.pdf">- PDF Link</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f5f4d5b15b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the JavaScript Event Loop: Call Stack, Microtasks, and Macrotasks]]></title>
            <link>https://medium.com/@barreira/understanding-the-javascript-event-loop-call-stack-microtasks-and-macrotasks-badb9231db5a?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/badb9231db5a</guid>
            <category><![CDATA[macrotask]]></category>
            <category><![CDATA[javascript-call-stack]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[microtask-queue]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 26 May 2025 04:15:33 GMT</pubDate>
            <atom:updated>2025-05-26T04:15:33.271Z</atom:updated>
            <content:encoded><![CDATA[<p>Some past application ask me about some concepts that I never searched about before, so now I’ve decided to do so.</p><p>So, as you (possibly know) JavaScript’s a single-threaded programming lan guage relying on an event loop to handle asynchronous operations. To master JavaScript’s asynchronous behavior, it’s crucial to understand how the call stack, microtask queue, and macrotask queue work together.</p><h3>The Call Stack</h3><p>The call stack is a LIFO (Last In, First Out) structure that tracks function execution in your program.</p><pre>function first() {<br>  console.log(&#39;First&#39;);<br>  second();<br>}<br><br>function second() {<br>  console.log(&#39;Second&#39;);<br>  third(); <br>}<br><br>function third() {<br>  console.log(&#39;Third&#39;);<br>}<br><br>first();</pre><p>Output:</p><pre>First<br>Second<br>Third</pre><p>The stack grows as functions are called and shrinks as they return.</p><p>When the stack is empty, the event loop checks the task queues.</p><h3>Macrotasks and Microtasks</h3><p>JavaScript has two main task queues:</p><ol><li><strong>Macrotask Queue</strong> (or just Task Queue). <br>Includes: setTimeout, setInterval, I/O operations, UI rendering, etc.</li><li><strong>Microtask Queue<br></strong>Includes: Promises, queueMicrotask(), MutationObserver .</li></ol><h3>Key Differences:</h3><ul><li>Microtasks have higher priority than macrotasks</li><li>The event loop processes all microtasks after each macrotask before moving to the next macrotask</li><li>If microtasks add more microtasks, they’ll all be processed before the next macrotask</li></ul><h3>Execution Order Example</h3><pre>console.log(&#39;Script start&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;setTimeout&#39;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&#39;Promise 1&#39;);<br>}).then(() =&gt; {<br>  console.log(&#39;Promise 2&#39;);<br>});<br><br>console.log(&#39;Script end&#39;);</pre><p>Output:</p><pre>Script start<br>Script end<br>Promise 1<br>Promise 2<br>setTimeout</pre><h3>Detailed Breakdown</h3><ol><li><strong>Synchronous code executes first </strong>(“Script start”, “Script end”)</li><li>The Promise microtask runs <strong>before </strong>the setTimeout macrotask</li><li>Even though setTimeout has 0 delay,<strong> it goes to the macrotask queue</strong></li><li>The event loop processes <strong>all microtasks</strong> (both Promise callbacks) before macrotasks</li></ol><h3>Nested Example</h3><pre>console.log(&#39;Start&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Timeout 1&#39;);<br>  Promise.resolve().then(() =&gt; console.log(&#39;Promise inside Timeout&#39;));<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&#39;Promise 1&#39;);<br>  setTimeout(() =&gt; console.log(&#39;Timeout inside Promise&#39;), 0);<br>});<br><br>console.log(&#39;End&#39;);</pre><p>Output:</p><pre>Start<br>End<br>Promise 1<br>Timeout 1<br>Promise inside Timeout<br>Timeout inside Promise</pre><h3>Real-world Implications</h3><p>Understanding this helps avoid common pitfalls:</p><blockquote><strong>Starving the Event Loop</strong>: Microtasks that keep adding more microtasks can prevent macrotasks (like UI updates) from running.</blockquote><pre>function recursiveMicrotask() {<br>  Promise.resolve().then(recursiveMicrotask);<br>}<br><br>recursiveMicrotask();<br>// setTimeout callbacks will never execute</pre><blockquote><strong>Performance Optimization</strong>: Break up CPU-intensive tasks with macrotasks to allow UI updates.</blockquote><pre>function processChunk() {<br>  // Process a portion of data<br>  if (moreToProcess) {<br>    setTimeout(processChunk, 0); // Allow UI updates between chunks<br>  }<br>}<br><br>processChunk();</pre><h3>Best Practices</h3><ol><li>Use microtasks for <strong>promise-based operations</strong> that need <strong>immediate resolution</strong></li><li>Use macrotasks for<strong> operations that can wait</strong> (like non-critical UI updates)</li><li>Be mindful of <strong>infinite microtask loops</strong></li><li>Use queueMicrotask() for explicit microtask scheduling</li></ol><pre>queueMicrotask(() =&gt; {<br>  console.log(&#39;This runs as a microtask&#39;);<br>})</pre><h3>Conclusion:</h3><p>Understanding JavaScript’s event loop and task queues is essential for writing efficient, predictable asynchronous code. The key takeaway is that microtasks always execute between macrotasks, and within each cycle, all available microtasks are processed before moving to the next macrotask.</p><p>When you undestand those you can create and debug your Apps with no issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=badb9231db5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before Code Steps in Domain-Driven Design (DDD) Methodology]]></title>
            <link>https://medium.com/@barreira/before-code-steps-in-domain-driven-design-ddd-methodology-7671074d7280?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7671074d7280</guid>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Fri, 23 May 2025 13:01:01 GMT</pubDate>
            <atom:updated>2025-05-23T13:01:01.948Z</atom:updated>
            <content:encoded><![CDATA[<p>Domain-Driven Design (DDD) is a software development approach that emphasizes deep collaboration between domain experts and developers to create a shared understanding of the business domain. Before jumping into coding, there are several critical steps that help ensure the success of a DDD project.</p><p>In this article, we’ll explore the essential <strong>pre-coding steps</strong> in DDD that help teams align on the domain model and set a strong foundation for development.</p><p>—</p><h3><strong>1 - Understand the Business Domain</strong></h3><p>Before writing any code, developers and stakeholders must <strong>deeply understand the business domain</strong>. This involves:<br>- <strong>Engaging with domain experts</strong> (business analysts, product owners, or end-users) to learn the key concepts, rules, and workflows.<br>- <strong>Identifying core business problems</strong> that the software needs to solve.<br>- <strong>Avoiding technical assumptions</strong> — focus on business language first.</p><blockquote><strong>Key Questions to Ask</strong>:<br><strong>- What are the main business processes?<br>- What are the key entities and their relationships?<br>- What business rules must be enforced?</strong></blockquote><figure><img alt="This helps visualize the main subdomains and workflows." src="https://cdn-images-1.medium.com/max/1024/1*njxWIVzCLrUT6ZSM2_393w.png" /><figcaption><em>This helps visualize the main subdomains and workflows.</em></figcaption></figure><p>—</p><h3>2 - Define the Ubiquitous Language</h3><p>One of the core principles of DDD is the <strong>Ubiquitous Language</strong> — a common, consistent vocabulary shared by everyone involved in the process such as developers and domain experts.</p><h4>How to Establish It:</h4><p>- <strong>Collaborate closely</strong> with domain experts to define terms.<br>- <strong>Document key terms</strong> in a shared glossary (e.g., “Order,” “Customer,” “Inventory”).<br>- <strong>Avoid technical jargon</strong> — use business terminology.<br>- <strong>Ensure the language evolves</strong> as the domain understanding grows.</p><p>This language will be used in <strong>code, documentation, and discussions</strong>, reducing misunderstandings.<br>There’s some examples here about it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*0ashmO4nRHC6KIFIW4e7jg.png" /></figure><p>---</p><h3>3 - Bounded Contexts</h3><p>A Bounded Context is a logical boundary where a particular domain model applies. Different parts of a business may have different definitions for the same term (e.g., “Customer” in Sales vs. “Customer” in Support).</p><h4>Steps to Define Bounded Contexts:</h4><ul><li><strong>Analyze domain complexity</strong> — look for natural divisions in business processes.</li><li><strong>Map out interactions</strong> between different contexts (Context Mapping).</li><li><strong>Define clear boundaries</strong> to avoid ambiguity in the model.</li></ul><h4>Example:</h4><ul><li><strong>Sales Management Context</strong> (Handles order creation, payment)</li><li><strong>Inventory Context</strong> (Manages stock levels, reservations)</li><li><strong>Warehouse Context </strong>(Manages the availability for sending items, shipping)</li></ul><p>A <strong>context map</strong> (showing interactions between contexts).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*_SQifo4cJG3F1zTOpWcqKA.png" /><figcaption><em>Defines clear boundaries between different parts of the system.</em></figcaption></figure><p>---</p><h3><strong>4 - Core Domain vs. Subdomains</strong></h3><p>Not all parts of the system are equally important. The <strong>Core Domain</strong> is where the most critical business logic resides.</p><h4>How to Identify the CoreDomain:</h4><ul><li><strong>Focus on the most valuable business differentiators</strong> (What makes the system unique?).</li><li><strong>De-prioritize supporting subdomains</strong> (e.g., reporting, notifications).</li><li><strong>Use Strategic DDD patterns</strong> (e.g., Aggregates, Entities, Value Objects) to model the core.</li></ul><p>Eg.</p><blockquote>CORE DOMAIN -&gt; (Order Processing)</blockquote><blockquote>SUPPORTING -&gt; (User Management)</blockquote><blockquote>GENERIC -&gt; (Email Notifications)</blockquote><p><em>This helps focus development efforts on the most critical areas. With the correct priority for different parts of the system.</em></p><p>---</p><h3>5 - High-Level Domain Model</h3><p>Before coding, teams should draft a <strong>conceptual domain model</strong> (often using diagrams like UML or Event Storming). The tool to be chosen should be something clear for all parts of the team, for better inclusion.</p><h3>Key Elements to Model:</h3><ul><li><strong>Entities</strong> (Objects with a unique identity, e.g., Order, User).</li><li><strong>Value Objects</strong> (Immutable objects defined by attributes, e.g., Address, Money).</li><li><strong>Aggregates</strong> (Clusters of related objects treated as a single unit).</li><li><strong>Domain Events</strong> (Important business occurrences, e.g., OrderPlaced).</li></ul><h3>Tools to Help:</h3><ul><li><strong>Event Storming</strong> (A workshop technique to model domain events).</li><li><strong>Class Diagrams</strong> (To visualize relationships).</li></ul><p><strong>Class Diagram example in UML format:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ap4XMEhmdb0Snze8wyFSKQ.png" /><figcaption><em>Shows relationships between key entities.</em></figcaption></figure><p>---</p><h3><strong>6 - Model Validation with Domain Experts</strong></h3><p>Before implementation, the model should be <strong>reviewed and refined</strong> with domain experts to ensure accuracy.</p><h4>Validation Techniques:</h4><ul><li><strong>Scenario Walkthroughs</strong> (Does the model handle real business cases?).</li><li><strong>Adjust based on feedback</strong> (Iterate on the model as needed).</li></ul><h4>Such process can come with some agrrements and disagrements about what is what in the system like this:</h4><blockquote><strong>Defining an “Order” in E-Commerce:</strong></blockquote><blockquote>— —</blockquote><blockquote><strong>Developer:</strong> “An Order should include a PaymentStatus field to track transactions.&quot;</blockquote><blockquote><strong>Domain Expert:</strong> “No, Payment is a separate process—it shouldn’t overload the Order model.&quot;</blockquote><p><strong>Resolution:</strong></p><p><strong>Agreement:</strong> Use <strong>Ubiquitous Language</strong> to clarify:</p><p>Order = Customer’s request (items, shipping address).</p><p>Payment = Separate aggregate (linked via OrderId).</p><p><strong>Outcome:</strong> Split into two aggregates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUD4kIvNdGg3mchY4ltJTg.png" /></figure><p>---</p><h3>7. Plan the Implementation Approach</h3><p>Finally, before coding, decide on:</p><ul><li><strong>Tactical DDD patterns</strong> (Repositories, Services, Factories).</li><li><strong>Technology choices</strong> (e.g., ORM, Event Sourcing).</li><li><strong>Team responsibilities</strong> (Who owns which Bounded Context?).</li><li><strong>Project architecture </strong>(How the project will be structured, which patterns, methodologies)</li></ul><h4>Example of code architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lqlcpJlvx4NVejb8ZG5hQ.png" /></figure><p>— -</p><h3>Conclusion</h3><p>DDD is not just about coding — it’s about <strong>understanding and modeling the business first</strong>. By following these <strong>before-code steps,</strong> teams can:</p><p>✅ Develop a <strong>shared understanding</strong> of the domain. <br>✅ Define a <strong>clear and consistent</strong> Ubiquitous Language. <br>✅ Identify <strong>Bounded Contexts</strong> to avoid ambiguity. <br>✅ Model the <strong>Core Domain</strong> effectively. <br>✅ Reduce <strong>miscommunication</strong> and <strong>refactoring</strong> later.</p><p>By investing time in these preparatory steps, developers can build software that <strong>truly aligns with business needs</strong> and remains maintainable as complexity grows.</p><p>Each team should find it’s own way to do it, find the one that suits better for yours.</p><h3>Refs:</h3><ol><li><a href="https://domainlanguage.com/ddd/"><strong>Domain-Driven Design: Tackling Complexity in the Heart of Software (Official Site)</strong></a><strong> — </strong>Eric Evans’ original DDD concepts, including Ubiquitous Language and Bounded Contexts.</li><li><a href="https://martinfowler.com/bliki/BoundedContext.html"><strong>Introducing Bounded Contexts (Martin Fowler)</strong></a><strong> — </strong>A concise explanation of Bounded Contexts with examples.</li><li><a href="https://www.infoq.com/articles/ddd-contextmapping/"><strong>Context Mapping: Strategic DDD (InfoQ)</strong></a><strong> — </strong>Patterns for mapping interactions between Bounded Contexts (e.g., Partnership, Anti-Corruption Layer).</li><li><a href="https://eng.uber.com/microservice-architecture/"><strong>Splitting the Monolith: DDD Lessons (Uber Blog)</strong></a><strong> — </strong>Real-world case study on applying DDD to decompose a monolith.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7671074d7280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate AI Images for Free via API Using Vite + React + TypeScript]]></title>
            <link>https://medium.com/@barreira/generate-ai-images-for-free-via-api-using-vite-react-typescript-72a37148f021?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a37148f021</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 12 May 2025 12:02:27 GMT</pubDate>
            <atom:updated>2025-05-12T12:02:27.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>🖼️</h3><p>AI-generated images are now more accessible than ever, thanks to free APIs and modern frontend tooling. In this tutorial, we’ll build a React + TypeScript app using <strong>Vite</strong> that lets users generate AI images from a prompt — all for free.</p><h3>⚡ Tech Stack</h3><ul><li><strong>Vite</strong> (for blazing-fast dev experience)</li><li><strong>React + TypeScript</strong></li><li><strong>Hugging Face Inference API</strong> (or other free image generation APIs)</li></ul><h3>🛠️ Step 1: Set Up a Vite + React + TS Project</h3><p>Open your terminal:</p><pre>npm create vite@latest ai-image-generator -- --template react-ts<br>cd ai-image-generator<br>npm install @runware/sdk-js<br>npm install<br>npm run dev</pre><p>Your dev server will be live at <a href="http://localhost:5173.">http://localhost:5173.</a></p><h3>🧠 Step 2: Get a Free AI Image API</h3><p>For this demo, we’ll use Runware model.</p><ol><li>Create a free account at <a href="https://runware.ai/">https://runware.ai/</a></li><li>Generate a token: <a href="https://my.runware.ai/keys">https://my.runware.ai/keys</a></li></ol><h3>🎨 Step 3: Create the Interface</h3><p>Replace src/App.tsx with the following code:</p><pre>import { useState, type DetailedHTMLProps, type InputHTMLAttributes } from &#39;react&#39;;<br>import &#39;./App.scss&#39;;<br>import { generateFromText } from &#39;./utils/generateImages&#39;;<br><br>function App() {<br>  const [prompt, setPrompt] = useState(&#39;&#39;);<br>  const [imageUrl, setImageUrl] = useState(&#39;&#39;);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  const generateImage = async () =&gt; {<br>    if (!prompt.trim()) {<br>      setError(&#39;Please enter a prompt.&#39;);<br>      return;<br>    }<br>    setLoading(true);<br>    setImageUrl(&#39;&#39;);<br>    setError(&#39;&#39;);<br><br>    try {<br>      const response = await generateFromText(prompt)<br><br>      if(!response) throw new Error(&#39;Error generating image&#39;)<br><br>      setImageUrl(response);<br>    } catch (err) {<br>      setError((err as Error).message);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  function handleOnKeyDown({ key }: DetailedHTMLProps&lt;InputHTMLAttributes&lt;HTMLInputElement&gt;, HTMLInputElement&gt;){<br>    if(key === &quot;Enter&quot;){<br>      generateImage() <br>    }<br>  }<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;AI Image Generator&lt;/h1&gt;<br>      {error &amp;&amp; &lt;p style={{ color: &#39;red&#39; }}&gt;{error}&lt;/p&gt;}<br>      {imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Generated AI&quot; /&gt;}<br>      &lt;div className=&#39;inputContainer&#39;&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={prompt}<br>          onKeyDown={handleOnKeyDown}<br>          onChange={({ target: { value } }) =&gt; setPrompt(value)}<br>          placeholder=&quot;Describe your image...&quot;<br>        /&gt;<br>        &lt;button onClick={generateImage} disabled={loading}&gt;<br>          {loading ? &#39;Generating...&#39; : &#39;Generate&#39;}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>And separate the method for generating the image</p><pre><br><br>import { Runware, type ITextToImage } from &quot;@runware/sdk-js&quot;;<br><br>const runware = new Runware({ apiKey: &quot;you-api-key&quot; });<br><br>async function generateFromText(prompt: string) {<br>  const [ image ] = await runware.requestImages({<br>    positivePrompt: prompt,<br>    width: 320,<br>    height: 320,<br>    numberResults: 1,<br>    model: &quot;civitai:102438@133677&quot;<br>  }) as ITextToImage[]<br><br>  return image.imageURL<br>}<br><br>export { generateFromText };</pre><h3>🔒 Step 5: Secure Your API Key</h3><p>For production:</p><ul><li>Use environment variables (.env) with VITE_ prefix:</li><li>VITE_HF_API_KEY=your_key_here</li><li>Then access via import.meta.env.VITE_HF_API_KEY.</li><li>Or proxy the API via your own backend to avoid exposing keys to users.</li></ul><blockquote>With just a few lines of code, you’ve created a functional AI image generator using <strong>Vite</strong> and a free API.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7QT8gjBnWbL_qCNbXnK02Q.gif" /></figure><p>It’s simple, but functional. Try using better ai models and other SDK’s for better results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a37148f021" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to Use Single Functions, Jobs, and Cron Jobs in Node.js: A Practical Guide]]></title>
            <link>https://medium.com/@barreira/when-to-use-single-functions-jobs-and-cron-jobs-in-node-js-a-practical-guide-ef83bd1826e5?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef83bd1826e5</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[system-analysis]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 13:11:57 GMT</pubDate>
            <atom:updated>2024-09-23T13:17:05.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Each tool serves a purpose, find the correct one for the ones that you got." src="https://cdn-images-1.medium.com/max/1024/1*gpBQnFEFxOZr8yroVHh15g.jpeg" /></figure><p>Recently I’ve applied for a role of Node Developer at <a href="https://kronoos.com/">kronoos</a> and during the coding challenge I’ve encounter a resource handling issue, a performance one, if you prefer.</p><p>When deciding how to handle a process in a single function, delegate it to a job, or schedule it with a cron job is crucial for building scalable and maintainable applications. Here we’ll explore the differences between these approaches using <strong>Node.js</strong>, and specifically, tools like <strong>Bull</strong> for job queues and <strong>node-cron</strong> for scheduling tasks.</p><h3>1. Handling Processes in a Single Function</h3><h3>When to Use:</h3><p>In general, you should process tasks in a single function when:</p><ul><li><strong>Simplicity</strong>: The task is simple, small, and quick to complete.</li><li><strong>Synchronous nature</strong>: The result of the task is needed immediately to proceed to the next step.</li><li><strong>Limited Resources</strong>: The task does not involve intense operations or heavy computations.</li><li><strong>No Background Processing</strong>: The task doesn’t need to run asynchronously or in the background.</li></ul><h3>Example, Authentication:</h3><pre>const handleAuth = (payload) =&gt; {<br>  // Simple synchronous task<br>  const { email, password } = payload	<br>    try {<br>	const { token } = handleAuthUser({<br>           email,<br>	   password<br>	})<br>	<br>	return token;<br>    } catch (e) {<br>        throw new Error(&#39;Invalid credentials&#39;)<br>    }<br>};</pre><blockquote>In this scenario we need the response immediately. The user is authorized or not? The response should have this information.</blockquote><h3>Pros:</h3><ul><li>Easy to implement and debug.</li><li>Results are immediately retrieved.</li></ul><h3>Cons:</h3><ul><li>Can block the event loop if the task is resource-heavy.</li><li>Poor scalability for long-running/heavy tasks.</li></ul><h3>2. Handling Processes Using Jobs (with Bull)</h3><h3>When to Use:</h3><p>Job queues, like those managed by <strong>Bull</strong>, are ideal when:</p><ul><li><strong>Asynchronous Tasks</strong>: Tasks need to be executed in the background, allowing the main application thread to continue running without delay.</li><li><strong>Heavy Lifting</strong>: The task involves CPU-intensive operations, large-scale database processing, or third-party API calls that can take time.</li><li><strong>Retries</strong>: Jobs that may fail need a retry mechanism.</li><li><strong>Task Scheduling</strong>: You want to schedule tasks to run later, at specific times or under certain conditions.</li></ul><h3>Example Using Bull:</h3><p>First, install Bull: npm install bull</p><pre>// queue/mail/index.ts<br>const Queue = require(&#39;bull&#39;);// Create a queue<br><br>const mailQueue = new Queue(&#39;mailQueue&#39;);<br><br>// // Producer - Adding a job to the queue<br>// usecases/admin/createAdmin.ts<br>async function createAdmin(payload) {<br>  const { companyId, name, email, username } = payload<br><br>  const adminCreated = await userAdminCreator({ companyId, name, email, username })<br><br>  adminCreated.employers.map((employer) =&gt; {<br>   /* <br>      Up to 2500 employers in that company, <br>      there&#39;s no use to wait for that response <br>   */<br>    mailQueue.add({ employer });    <br>  })<br>}<br><br>// // Consumer - Processing jobs in the queue<br>// queue/mail/index.ts<br>mailQueue.process(async (job) =&gt; {<br>  const { employer } = job.data<br>  <br>  try {<br>    await employerMailer(employer)<br>  } catch (error) {<br>    throw new Error(`Error sending email to employer: ${error.message}`);    <br>  }<br>});</pre><blockquote>With lots of calls for this function there&#39;s no way to wait for all responses asynchronously, plus deal with retries and error handling.</blockquote><h3>Pros:</h3><ul><li>Offloads heavy or time-consuming processes to background workers.</li><li>Does not bloco the event loop.</li><li>Supports job retries, delays, and concurrency control.</li><li>Scales well with larger applications.</li></ul><h3>Cons:</h3><ul><li>Additional complexity in setting up job queues and workers.</li><li>Requires a Redis instance for managing jobs.</li><li>Harder to debug</li></ul><h3>3. Handling Scheduled Tasks Using Cron Jobs (with node-cron)</h3><p>Cron jobs are appropriate when:</p><ul><li><strong>Recurring Tasks</strong>: Tasks that need to run periodically, like sending daily emails, cleaning up databases, or generating reports at a specific time.</li><li><strong>Time-Based Scheduling</strong>: You need to schedule tasks to run at specific intervals (e.g., every minute, hour, or day).</li><li><strong>Automated Maintenance</strong>: Running tasks such as database backups, log rotation, or sending notifications at regular intervals.</li></ul><h3>Example Using node-cron:</h3><p>First, install node-cron: npm install node-cron</p><pre>const cron = require(&#39;node-cron&#39;);<br>const { PrismaClient } = require(&#39;@prisma/client&#39;);<br><br>// Initialize Prisma Client<br>const prisma = new PrismaClient();<br><br>// Function to check inventory and send alerts<br>async function checkInventory() {<br>  try {<br>    const lowStockProducts = await prisma. product.findMany({<br>      where: {<br>        quantity: {<br>          lt: prisma.product.threshold, // Check if quantity is below threshold<br>        },<br>      },<br>    });<br><br>    if (lowStockProducts.length &gt; 0) {<br>      console.log(&#39;Low stock detected for the following products:&#39;);<br><br>      // lowStockProducts.forEach((product) =&gt; {<br>      for (const product of lowStockProducts) {<br>        console.log(`${product.name} is below the threshold. Current Quantity: ${product.quantity}`);              <br><br>        try {<br>          await sendMailToManager()<br>        } catch (error) {<br>          throw new Error(&quot;Error sending mail to the manager&quot;);            <br>        }        <br>      }<br>      <br>    } else {<br>      console.log(&#39;All products have sufficient stock.&#39;);<br>    }<br>  } catch (error) {<br>    console.error(&#39;Error checking inventory:&#39;, error);<br>  }<br>}<br><br>// // Set up a cron job to run every hour<br>// crons/stock/checkInventory.ts<br>cron.schedule(&#39;0 * * * *&#39;, () =&gt; {  <br>  console.log(`Running inventory check at ${new Date().toLocaleTimeString()}`);<br>  checkInventory();<br>});</pre><h3>Pros:</h3><ul><li>Easy to set up and use for recurring tasks.</li><li>Simple and effective for periodic jobs.</li><li>Does not require Redis or other heavy dependencies.</li></ul><h3>Cons:</h3><ul><li>Can’t easily handle large, resource-heavy tasks without blocking the main thread.</li><li>Lacks built-in retry mechanisms, unlike job queues.</li></ul><h3>When to Choose Each Approach</h3><p>Quick, simple, synchronous task -&gt; <strong>Single Function</strong></p><p>Background task with no immediate need -&gt; <strong>Bull Job Queue</strong></p><p>Task requiring retries on failure -&gt; <strong>Bull Job Queue</strong></p><p>Recurring tasks at regular intervals -&gt; <strong>Cron Job</strong></p><p>CPU-intensive or long-running task ❌ ✔️ ✔️ -&gt; <strong>Bull Job Queue </strong>(And <strong>Cron Job </strong>for scheduling)</p><p>Time-based automation or reporting ❌ ❌ ✔️ -&gt; <strong>Cron Job</strong></p><h3>Conclusion</h3><p>Choosing the right method for handling processes in Node.js is essential for creating efficient, scalable applications. <strong>Single functions</strong> are perfect for simple, synchronous tasks, while <strong>Bull job queues</strong> excel in managing background, asynchronous jobs that require retries and concurrency. On the other hand, <strong>cron jobs</strong> are best for scheduling recurring tasks that need to run at specific times or intervals.</p><p>By leveraging the right approach for the right task, you can ensure your application remains performant, reliable, and maintainable as it scales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef83bd1826e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identifying Application Entities in Verbs Using Domain-Driven Design (DDD)]]></title>
            <link>https://medium.com/@barreira/identifying-application-entities-in-verbs-using-domain-driven-design-ddd-8e1703461142?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e1703461142</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 12:44:06 GMT</pubDate>
            <atom:updated>2024-07-29T12:45:31.930Z</atom:updated>
            <content:encoded><![CDATA[<p>As I mention in my previous article (<a href="https://medium.com/@barreira/briefly-ddd-490b74f8ada9">https://medium.com/@barreira/briefly-ddd-490b74f8ada9</a>) DDD is a fascinating way to Design an application. But a major issue that I found trying to study DDD is the part of identifying the verbs needed to make it work as expected. So here I am trying to help you out on that past</p><h3>Understanding Verbs in the Context of DDD</h3><p>Verbs represent actions, processes, and events in a system. In other words, each interaction comes from a verb.</p><p>In the context of DDD, verbs help uncover the dynamic aspects of the domain, illustrating how different parts of the system interact and change over time.</p><p>Focusing on verbs, developers can identify the key activities and processes that define the domain, leading to the discovery of core entities and their responsibilities.</p><h3>Steps to Identify Entities Using Verbs</h3><ol><li><strong>Domain Exploration and Ubiquitous Language:</strong> Begin by collaborating with domain experts to understand the business processes and workflows. Engage in conversations to capture the domain’s language, focusing on verbs that describe actions and interactions. For example, in an e-commerce domain, verbs like “place order,” “process payment,” and “ship product” are crucial.</li><li><strong>Identify Core Processes and Actions:</strong> List all the significant verbs related to the domain. These verbs often indicate processes that involve multiple entities. For instance, “register user” involves entities like User and Account, while “process payment” involves Payment, Order, and possibly Invoice entities.</li><li><strong>Analyze Verbs for Entity Candidates:</strong> Examine each verb to determine the entities involved. Verbs usually imply one or more entities performing actions or undergoing changes. For example, the verb “ship product” suggests entities like Order, Product, and Shipping.</li><li><strong>Define Boundaries and Responsibilities:</strong> Once entities are identified, define their boundaries and responsibilities. Verbs can help delineate what each entity is responsible for. For instance, “process payment” might clarify that the Payment entity handles transactions, while the Order entity manages order details.</li><li><strong>Create Domain Models:</strong> Develop domain models that incorporate the identified entities and their relationships. Use verbs to define methods and behaviors within these entities. For example, the Order entity might have methods like placeOrder(), cancelOrder(), and shipOrder().</li><li><strong>Refine Through Iteration:</strong> Continuously refine the model by revisiting the verbs and their associated entities. As you gain a deeper understanding of the domain, new verbs and entities may emerge, necessitating updates to the domain model.</li></ol><h3>Conclusion</h3><p>Identifying entities through the analysis of verbs provides a concise way to understand and model the business domain in DDD. By focusing on actions and interactions, developers can find essential entities and define their responsibilities more effectively. This method ensures that the software model remains adaptable and reflective of real-world operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e1703461142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using tsup Over Other JavaScript Compilers: An In-Depth Look]]></title>
            <link>https://medium.com/@barreira/using-tsup-over-other-javascript-compilers-an-in-depth-look-fcdcf29d9925?source=rss-14405318642a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcdcf29d9925</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tsup]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[bundler]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Augusto Barreira]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 22:57:23 GMT</pubDate>
            <atom:updated>2024-07-24T22:57:23.495Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript development has come a long way since its inception, and the ecosystem of tools and compilers has grown significantly. Among the great amount of options available to developers, tsup has emerged as a popular choice for compiling TypeScript and JavaScript projects. But why choose tsup over other compilers like Babel, webpack, or TypeScript&#39;s own compiler (tsc)? This article explores the advantages of using tsup and why it might be the right choice for your next project.</p><h3>What is tsup?</h3><p>tsup is a TypeScript bundler powered by esbuild, designed to be simple, fast, and out-of-the-box ready. It aims to provide a zero-config experience while supporting modern JavaScript and TypeScript features.</p><h3>Key Advantages of Using tsup</h3><h3>1. Performance</h3><p>One of the standout features of tsup is its performance. Built on top of esbuild, tsup leverages the incredible speed of esbuild&#39;s Go-based architecture. This results in significantly faster build times compared to traditional JavaScript compilers like Babel or webpack. For large projects, this performance boost mean a substantial time savings during development and deployment.</p><h3>2. Ease of Use</h3><p>tsup prides itself on being zero-config, meaning it works out of the box with minimal configuration. This simplicity is a breath of fresh air compared to other compilers, which often require extensive setup and configuration. With tsup, you can get started quickly, allowing you to focus more on writing code rather than configuring your build tools.</p><h3>3. Built-in Features</h3><p>Despite its simplicity, tsup comes packed with powerful features that cover most of the needs of modern JavaScript and TypeScript projects. These include:</p><ul><li><strong>Tree Shaking:</strong> Automatically removes unused code, reducing the final bundle size.</li><li><strong>Code Splitting:</strong> Allows you to split your code into smaller chunks, which can be loaded on demand, improving the performance of your application.</li><li><strong>Minification:</strong> Reduces the size of your JavaScript files by removing unnecessary characters and optimizing the code.</li><li><strong>Source Maps:</strong> Generates source maps for easier debugging.</li><li><strong>TypeScript Support:</strong> Fully supports TypeScript out of the box without additional configuration.</li></ul><h3>4. Compatibility with Other Tools</h3><p>tsup is designed to be compatible with other tools in the JavaScript ecosystem. Whether you’re using a framework like React, Vue, or Svelte, or you need to integrate with other build tools like Rollup or webpack, tsup can fit seamlessly into your workflow. This flexibility makes it an excellent choice for a wide range of projects.</p><h3>5. Modern JavaScript and TypeScript Support</h3><p>tsup stays up-to-date with the latest JavaScript and TypeScript features, ensuring that you can use the most recent language enhancements in your projects. This forward-thinking approach helps future-proof your codebase and takes advantage of modern syntax and features.</p><h3>Comparing tsup to Other Compilers</h3><h3>Let’s assume a simple project structure:</h3><pre>- /project<br>  - /src<br>    - index.ts<br>  - /dist<br>  - tsconfig.json<br>  - package.json</pre><h3>Tsup setup:</h3><p><strong>Installation:</strong></p><pre>npm install tsup --save-dev</pre><p><strong>Usage:</strong></p><p>Add the following script to package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsup src/index.ts --format cjs,esm --dts&quot;<br>}</pre><p><strong>Command:</strong></p><pre>npm run build</pre><p><strong>That’s it, simples as that.</strong></p><p><strong>You can even add more customization here as your heart (or the need) desires: </strong><strong>tsup.config.ts</strong></p><pre>import { defineConfig } from &#39;tsup&#39;;<br><br>export default defineConfig({<br>  entry: [&#39;src/index.ts&#39;],<br>  format: [&#39;cjs&#39;, &#39;esm&#39;],<br>  dts: true,<br>  splitting: true,<br>});</pre><h3>Babel setup</h3><p>Babel is a widely-used JavaScript compiler that allows developers to use the latest JavaScript features by transpiling code to older versions for compatibility. While Babel is highly configurable and supports a vast range of plugins, its configuration complexity can be overwhelming. Moreover, Babel is not designed as a bundler, so you often need to pair it with other tools like webpack for complete functionality.</p><p><strong>Installation:</strong></p><pre>npm install @babel/core @babel/cli @babel/preset-env @babel/preset-typescript --save-dev</pre><p><strong>Configuration (</strong><strong>.babelrc or </strong><strong>babel.config.json):</strong></p><pre>{<br>  &quot;presets&quot;: [<br>    &quot;@babel/preset-env&quot;,<br>    &quot;@babel/preset-typescript&quot;<br>  ]<br>}</pre><p><strong>Usage:</strong></p><p>Add the following script to package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;babel src --out-dir dist --extensions \\&quot;.ts\\&quot;&quot;<br>}</pre><p><strong>Command:</strong></p><pre>npm run build</pre><blockquote>In contrast, tsup offers a simpler, more integrated experience with fewer configuration headaches and faster build times, thanks to esbuild.</blockquote><h3>Webpack setup</h3><p>webpack is a powerful and highly configurable module bundler. It is extremely versatile and can handle complex build requirements. However, this power comes at the cost of complexity. Setting up webpack often requires a steep learning curve and a significant amount of configuration.</p><p><strong>Installation:</strong></p><pre>npm install webpack webpack-cli ts-loader typescript --save-dev</pre><p><strong>Configuration (</strong><strong>webpack.config.js):</strong></p><pre>const path = require(&#39;path&#39;);<br><br>module.exports = {<br>  entry: &#39;./src/index.ts&#39;,<br>  output: {<br>    filename: &#39;bundle.js&#39;,<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    libraryTarget: &#39;umd&#39;,<br>  },<br>  resolve: {<br>    extensions: [&#39;.ts&#39;, &#39;.js&#39;],<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\\.ts$/,<br>        use: &#39;ts-loader&#39;,<br>        exclude: /node_modules/,<br>      },<br>    ],<br>  },<br>  mode: &#39;production&#39;,<br>};</pre><p><strong>Usage:</strong></p><p>Add the following script to package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;webpack&quot;<br>}</pre><p><strong>Command:</strong></p><pre>npm run build</pre><blockquote>tsup provides a more straightforward alternative, delivering the essential features needed for most projects with minimal setup. While it may not offer the extensive configurability of webpack, it covers the majority of use cases with far less effort.</blockquote><h3>Tsc setup</h3><p>The TypeScript compiler (tsc) is the default tool for compiling TypeScript code. It’s reliable and integrates well with TypeScript projects. However, tsc is not designed to handle bundling or advanced build optimizations like tree shaking and code splitting.</p><p><strong>Installation:</strong></p><pre>npm install typescript --save-dev</pre><p><strong>Configuration (</strong><strong>tsconfig.json):</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;target&quot;: &quot;es6&quot;,<br>    &quot;sourceMap&quot;: true,<br>    &quot;declaration&quot;: true},<br>  &quot;include&quot;: [&quot;src/**/*&quot;]<br>}</pre><p><strong>Usage:</strong></p><p>Add the following script to package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsc&quot;<br>}</pre><p><strong>Command:</strong></p><pre>npm run build</pre><blockquote>tsup combines the strengths of tsc with the powerful bundling capabilities of esbuild, providing a more comprehensive solution for modern TypeScript projects.</blockquote><h3>Conclusion</h3><p>Tsup is a great tool for JavaScript and TypeScript development because it’s fast, simple, and has powerful features. Whether you’re working on a small project or a big application, tsup is a good alternative to more complex and slower tools like Babel and webpack. Using tsup can make your development process smoother, reduce build times, and make setup easier, so you can focus on writing great code.</p><p>You can choose any compiler you desires, but for me TSUP is the best option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcdcf29d9925" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>