<?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 Raygun on Medium]]></title>
        <description><![CDATA[Stories by Raygun on Medium]]></description>
        <link>https://medium.com/@raygunio?source=rss-3e912712f84d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k7IR357MsB9KLrRlpACqmA.jpeg</url>
            <title>Stories by Raygun on Medium</title>
            <link>https://medium.com/@raygunio?source=rss-3e912712f84d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:42:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raygunio/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[Top 10 .NET exceptions (part two)]]></title>
            <link>https://medium.com/@raygunio/top-10-net-exceptions-part-two-01e59600c3e1?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/01e59600c3e1</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[crash-reporting]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 20:49:47 GMT</pubDate>
            <atom:updated>2025-01-15T20:49:47.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 10 .NET exceptions (part two)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftiq9n-pLLrMbTDFvXKw7g.png" /></figure><p>In <a href="https://medium.com/@raygunio/top-10-net-exceptions-part-one-383ade0848b1">Part 1</a>, we walked through the top 5 most common .NET exceptions — breaking down what triggers them and how to fix them. Now, we’re rounding out the list with five more exceptions every .NET developer is bound to encounter at some point:</p><ol><li>EntityCommandExecutionException</li><li>OutOfMemoryException</li><li>KeyNotFoundException</li><li>StackOverflowException</li><li>InvalidOperationException</li></ol><p>These exceptions can stem from database issues, memory mismanagement, and logic errors that can bring your applications to a halt. In this article, we’ll break down each one, explain when and why they occur, and share practical strategies to fix them so you can keep your code running smoothly.</p><h3>6. EntityCommandExecutionException</h3><p>EntityCommandExecutionException occurs when an Entity Framework fails to execute a database command. This error often happens during operations like SaveChangesAsync when database constraints (e.g., foreign key violations, unique constraints) are violated, or database connectivity issues arise. Imagine a product catalog system performing updates to product records:</p><pre>public async Task UpdateProductAsync(ProductDto dto)<br>{<br>    var product = await _context.Products.FirstAsync(p =&gt; p.Id == dto.Id);<br>    product.Name = dto.Name;<br>    product.CategoryId = dto.CategoryId; // Risk of foreign key violation<br>    await _context.SaveChangesAsync(); // Throws EntityCommandExecutionException<br>}</pre><p>This code assumes all CategoryId values are valid. If a CategoryId doesn’t exist in the database, a DbUpdateException (caused by an EntityCommandExecutionException, which also wraps a database specific exception) is thrown. The lack of retry logic also makes it susceptible to transient issues like deadlocks.</p><h3>Fix</h3><p>Before saving changes, validate the input data and handle potential exceptions gracefully:</p><pre>public async Task UpdateProductAsync(ProductDto dto)<br>{<br>    var product = await _context.Products.FirstOrDefaultAsync(p =&gt; p.Id == dto.Id);<br>    if (product == null) return;<br>    <br>    vat category = await _context.Categories.FirstOrDefaultAsync(c =&gt; c.Id == dto.CategoryId);<br>    if (category == null)<br>    {<br>        _logger.LogWarning(&quot;Invalid category ID: {CategoryId}&quot;, dto.CategoryId);<br>        return;<br>    }<br>    <br>    product.Name = dto.Name;<br>    product.CategoryId = dto.CategoryId;<br>    try<br>    {<br>        await _context.SaveChangesAsync();<br>    }<br>    catch (DbUpdateException ex) when (ex.InnerException is SqlException sql &amp;&amp; sql.Number == 547)<br>    {<br>        _logger.LogError(&quot;Database constraint violation: {Message}&quot;, ex.Message);<br>        throw new BusinessException(&quot;Invalid data in db update&quot;);<br>    }<br>}</pre><h3>General tips for handling EntityCommandExecutionExceptions</h3><ul><li><strong>Validate inputs</strong>: Always check foreign key and unique constraints before calling SaveChangesAsync.</li><li><strong>Map errors to business logic</strong>: Use SqlException.Number to translate database errors into meaningful application exceptions.</li><li><strong>Implement retry logic</strong>: Use libraries like Polly to handle transient errors like deadlocks.</li><li><strong>Log errors</strong>: Record detailed error information, including SQL error codes and states, for easier debugging.</li></ul><h3>7. OutOfMemoryException</h3><p>OutOfMemoryException occurs when an application tries to allocate more memory than is available. This error typically happens when handling large datasets or files without efficient memory management. Here’s a financial application attempting to load a large CSV file into memory:</p><pre>public List&lt;Transaction&gt; LoadTransactions(string filePath)<br>{<br>    var lines = File.ReadAllLines(filePath); // Risk of memory exhaustion<br>    return lines.Select(ParseTransaction).ToList();<br>}</pre><p>This approach is acceptable for small files but fails for large ones. Loading the entire file into memory can lead to a spike in memory usage, eventually causing a crash.</p><h3>Fix</h3><p>Process large files line by line to minimize memory usage:</p><pre>public IEnumerable&lt;Transaction&gt; LoadTransactions(string filePath)<br>{<br>    using var reader = new StreamReader(filePath);<br>    while (!reader.EndOfStream)<br>    {<br>        var line = reader.ReadLine();<br>        if (line != null) yield return ParseTransaction(line);<br>    }<br>}</pre><h3>General tips for handling OutOfMemoryExceptions</h3><ul><li><strong>Use streams</strong>: Process files incrementally rather than loading them entirely into memory.</li><li><strong>Implement batch processing</strong>: Break large operations into smaller, manageable chunks.</li><li><strong>Monitor memory</strong>: Use tools like the .NET Performance Profiler to detect and fix memory bottlenecks.</li><li><strong>Dispose of resources</strong>: Implement ‘using’ statements or blocks to release memory when resources are no longer needed.</li></ul><h3>8. KeyNotFoundException</h3><p>A KeyNotFoundException is thrown when attempting to access a dictionary or JSON property with a key that does not exist. This often occurs when working with JSON data without validating the input. Here’s a JSON parser that assumes all fields are present in the input data:</p><pre>public User ParseUser(JsonElement userJson)<br>{<br>    return new User<br>    {<br>        Name = userJson.GetProperty(&quot;name&quot;).GetString(),<br>        Email = userJson.GetProperty(&quot;email&quot;).GetString(),<br>        Phone = userJson.GetProperty(&quot;phone&quot;).GetString() // Risk of exception<br>    };<br>}</pre><p>If the phone field is missing, this code will throw a KeyNotFoundException.</p><h3>Fix</h3><p>To prevent the exception, check for the existence of the field and provide fallback values:</p><pre>public User ParseUser(JsonElement userJson)<br>{<br>    return new User<br>    {<br>        Name = userJson.GetProperty(&quot;name&quot;).GetString(),<br>        Email = userJson.GetProperty(&quot;email&quot;).GetString(),<br>        Phone = userJson.TryGetProperty(&quot;phone&quot;, out var phone) ? phone.GetString() : &quot;N/A&quot;<br>    };<br>}</pre><h3>General tips for handling KeyNotFoundExceptions</h3><ul><li><strong>Validate inputs</strong>: Ensure the structure and completeness of the input data before accessing it.</li><li><strong>Deserialize the JSON directly</strong>: Use the .NET JSON library to deserialize objects into concrete types. This handles missing values automatically:</li></ul><pre>var user = JsonSerializer.Deserialize&lt;User&gt;(jsonString);</pre><ul><li><strong>Access properties safely</strong>: Use methods like TryGetValue/TryGetProperty or provide default values for missing fields to avoid exceptions.</li><li><strong>Log issues</strong>: Record details of malformed or incomplete data for easier debugging.</li></ul><h3>9. StackOverflowException</h3><p>StackOverflowException occurs when a program attempts to use more memory in the call stack than has been allocated to it. This is typically a result of a large number of method calls within a given call tree (through recursion or loops). Still, it can also be caused by declaring excessive local variables within stack frames. This severe exception terminates the process immediately and cannot be caught or handled. Consider a file system scanner that recursively traverses directories to build a tree structure:</p><pre>public class FileSystemScanner<br>{<br>    public DirectoryNode ScanDirectory(string path)<br>    {<br>        var node = new DirectoryNode(path);<br>        node.Children = Directory<br>            .GetDirectories(path)<br>            .Select(subDir =&gt; ScanDirectory(subDir)) // Recursive call<br>            .ToList();<br>        return node;<br>    }<br>}</pre><p>This code is vulnerable in several ways. Recursive calls will exhaust the stack if the directory tree is too deep, and symbolic links or junctions can create infinite loops. Even shallow recursion can consume excessive memory if large or many local variables exist in each stack frame.</p><h3>Fix</h3><p>Replace recursive calls with an iterative approach that manually manages the stack:</p><pre>public DirectoryNode ScanDirectoryIterative(string rootPath)<br>{<br>    var root = new DirectoryNode(rootPath);<br>    var stack = new Stack&lt;(DirectoryNode Node, string Path)&gt;();<br>    stack.Push((root, rootPath));<br>    var visitedPaths = new HashSet&lt;string&gt; { rootPath }; // Prevent cycles<br><br>    while (stack.Count &gt; 0)<br>        {<br>            var (current, path) = stack.Pop();<br>            foreach (var dir in Directory.GetDirectories(path))<br>            {<br>                if (!visitedPaths.Add(dir)) continue; // Skip already visited paths<br>                var child = new DirectoryNode(dir);<br>                current.Children.Add(child);<br>                stack.Push((child, dir));<br>            }<br>        }<br>        return root;<br>    }</pre><h3>General tips for handling StackOverflowExceptions</h3><ul><li><strong>Use iteration</strong>: For deep or complex structures, use iterative algorithms over recursion.</li><li><strong>Track visited nodes</strong>: Use a HashSet to handle cycles, such as those caused by symbolic links.</li><li><strong>Limit depth</strong>: Set a maximum depth for traversal to avoid hitting stack limits.</li><li><strong>Profile memory</strong>: Monitor stack usage and memory during development.</li></ul><h3>10. InvalidOperationException</h3><p>InvalidOperationException is thrown when an operation for the current state of an object is invalid. A typical scenario is using LINQ’s Single or SingleOrDefault on a sequence that doesn’t meet the uniqueness constraint — either because it has multiple matches or no matches at all. Here’s a permission management service that retrieves user access information. Users may have multiple permissions for a given system, and the database is ordered such that the highest permission for a user and system is first.</p><pre>public class PermissionService<br>{<br>    private readonly List&lt;UserAccess&gt; _userAccessList = new List&lt;UserAccess&gt;<br>    {<br>        new UserAccess { Email = &quot;sarah@company.com&quot;, System = &quot;CRM&quot;, Permission = &quot;Read&quot; },<br>        new UserAccess { Email = &quot;sarah@company.com&quot;, System = &quot;Billing&quot;, Permission = &quot;Write&quot; },<br>        new UserAccess { Email = &quot;sarah@company.com&quot;, System = &quot;Billing&quot;, Permission = &quot;Read&quot; },<br>        new UserAccess { Email = &quot;mike@company.com&quot;, System = &quot;CRM&quot;, Permission = &quot;Admin&quot; }<br>    };<br><br>    public string GetUserPermissionForSystem(string email, string system)<br>        {<br>            // Bug: Multiple entries for the same user and system<br>            var access = _userAccessList.SingleOrDefault(u =&gt; <br>                u.Email == email &amp;&amp; u.System == system);<br>            return access?.Permission ?? &quot;NoAccess&quot;;<br>        }<br>    }</pre><p>Because multiple entries exist for a user and system, SingleOrDefault will throw an InvalidOperationException. Uniqueness is not enforced in the database, so using Single or SingleOrDefault is incorrect.</p><h3>Fix</h3><p>Use FirstOrDefault as duplicates are acceptable. Since the database maintains an intentional order, FirstOrDeafult is preferable to Any.</p><pre>public string GetUserPermissionForSystem(string email, string system)<br>{<br>    return _userAccessList<br>        .Where(u =&gt; u.Email == email &amp;&amp; u.System == system)<br>        .FirstOrDefault()?.Permission ?? &quot;NoAccess&quot;;<br>}</pre><h3>General tips for handling InvalidOperationExceptions</h3><ol><li><strong>Choose the right LINQ method</strong>:</li></ol><ul><li>Single: Use when enforcing uniqueness is critical. This method will throw an exception in the case of a missing or duplicate value.</li><li>First: Use when you only need the first match. This method will throw an exception in the case of a missing value.</li><li>Any: Use to check for existence without fetching data.</li><li>SingleOrDefault: Use to enforce uniqueness while also providing a default in case of a missing value. This method will still throw an exception if it encounters duplicates.</li><li>FirstOrDefault: Find the first match and provide a default (null for objects) in case of a missing value.</li></ul><p><strong>2. Handle duplicates</strong>: Log and manage cases where queries find multiple matches.</p><p><strong>3. Ensure data integrity</strong>: Prevent duplicates (if uniqueness is a requirement) at the source by enforcing database constraints or performing validation.</p><h3>Wrap up</h3><p>With these 10 common .NET exceptions covered, you now have a solid foundation for handling some of the most frequent and frustrating issues in your .NET applications. From null references to stack overflows, better exception management leads to more reliable, maintainable, and performant code — and fewer late-night debugging sessions. Whether it’s catching database errors, managing memory, or avoiding invalid operations, these strategies will help you write cleaner code and ship confidently. Armed with this knowledge, you’re well-equipped to tackle even the trickiest bugs in your .NET projects.</p><p>Not a Raygun customer? <a href="https://app.raygun.com/signup">Try out the full Crash Reporting application free for 14 days!</a></p><p><em>Article originally published on the </em><a href="https://raygun.com/blog/dotnet-exceptions-part-2/"><em>Raygun Blog</em></a><em>, written by Rowan Tandy.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01e59600c3e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 .NET exceptions (part one)]]></title>
            <link>https://medium.com/@raygunio/top-10-net-exceptions-part-one-383ade0848b1?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/383ade0848b1</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[exceptions-handling]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 20:39:07 GMT</pubDate>
            <atom:updated>2025-01-15T20:44:23.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 10 .NET exceptions (part one)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PppR4TeHinRqtPIz_aGxzw.png" /></figure><p>Exception handling is essential to .NET development, but not all exceptions are equal. Some, like NullReferenceException, surprise developers with unclear stack traces and production crashes. Others, such as MySQLException or HttpRequestException, often point to issues like resource mismanagement or network failures.</p><p>At Raygun, we’ve worked with teams around the world to monitor and fix software issues, giving us deep insight into how exceptions occur and how to handle them effectively.</p><p>This article covers common exceptions in .NET, the scenarios that trigger them, and practical strategies to handle them. From managing null checks to fixing database connection issues and async cancellations, this guide will help you write safer, more reliable code.</p><h3>What’s in the article</h3><ol><li>NullReferenceException</li><li>MySqlException</li><li>HttpRequestException</li><li>TaskCanceledException</li><li>AggregateException</li></ol><h3>1. NullReferenceException</h3><p>The NullReferenceException is one of the most common and notorious exceptions in .NET development. It occurs when code attempts to access a member of an object (or an element of an array) that is null. This exception is particularly troublesome as it often surfaces in production environments, causing unexpected application failures. It is usually challenging to determine which object created the error from the stack trace alone.</p><p>Imagine you’re processing an order and need to send an email notification for high-value purchases. In this case, the system assumes every order has a valid customer and tries to access the customer’s email address — without any checks.</p><pre>public async Task ProcessOrderBad(Order order)<br>{<br>    if (order == null)<br>        throw new ArgumentNullException(nameof(order));<br><br>var customer = await customerService.GetCustomerAsync(order.CustomerId);<br>    if (order.Total &gt; 1000)<br>    {<br>        // Boom! NullReferenceException here if customer wasn&#39;t found<br>        await emailService.SendHighValueOrderAlert(customer.Email);<br>    }<br>    await ProcessOrderItems(order);<br>}</pre><p>The problem is that we’re not checking if the customer object is null before attempting to access its Email property. If customerService.GetCustomerAsync can’t find a customer for the given CustomerId, it might return null. Trying to access customer.Email in that scenario will throw a NullReferenceException.</p><h3>Fix</h3><p>Before accessing the Email property, ensure that the customer object is not null. This check prevents the NullReferenceException by handling the scenario where the customer might not be found.</p><pre>if (customer == null)<br>{<br>    throw new InvalidOperationException(&quot;Customer not found.&quot;);<br>}</pre><h3>General tips for handling NullReferenceExceptions</h3><ul><li><strong>Use the Null Object Pattern</strong>: Instead of null, return an empty object that defines default behavior.</li></ul><pre>public class NullCustomer : ICustomer <br>    { <br>        public string Email =&gt; string.Empty;<br>    }</pre><ul><li><strong>Take advantage of C# 8.0’s nullable reference types</strong>: Enable nullable reference types to let the compiler warn you about potential null references during development.</li></ul><pre>#nullable enable<br>    Customer? customer = await customerService.GetCustomerAsync(order.CustomerId);</pre><ul><li><strong>Use the null-coalescing operator (??)</strong>: Provide default values when a variable is null to ensure safe defaults.</li></ul><pre>string displayName = username ?? &quot;Guest&quot;;</pre><ul><li><strong>Use the null conditional operator (?.)</strong>: Safely access members only if the object is not null.</li></ul><pre>string? email = customer?.Email;</pre><ul><li><strong>Use a static code analyzer</strong>: Tools like SonarQube or ReSharper can identify potential null reference issues during development.</li><li><strong>Write unit tests</strong>: Specifically test null scenarios to ensure that your application handles them gracefully.</li></ul><h3>2. MySqlException</h3><p>A MySQLException is a common exception in .NET applications that use the MySQL. Data library to interact with MySQL databases. This exception can surface for various reasons, from syntax errors in SQL queries to issues with database connectivity. One frequent cause is exhausting the connection pool — this occurs when too many connections to the database are opened without being properly closed, leaving no available connections for new requests.</p><p>During a recent .NET migration, we encountered an issue where switching from using blocks to using statements for database connections led to MySqlExceptions. In web requests with long-running operations, connections were held for the entire duration of the request instead of being released immediately after the database operations were completed. Under high traffic, this exhausted the connection pool, causing exceptions across multiple systems.</p><pre>public async Task ProcessUpload(IFormFile file)<br>{<br>    // Using statement holds the connection for entire method scope<br>    using var dbConnection = new SqlConnection(_connectionString);<br>    await dbConnection.OpenAsync();<br>    <br>    await VerifyUserPermissions(dbConnection);<br>    <br>    // Connection still held during this long operation! <br>    await ProcessLargeFile(file);<br>    <br>    // Connection not released until method ends<br>}</pre><p>In the code above, the using statement scopes the dbConnection for the entire ProcessUpload method. This means the database connection remains open during the long-running ProcessLargeFile operation, preventing it from being returned to the connection pool promptly. Under high traffic, this can quickly exhaust the available connections, leading to MySqlExceptions.</p><h3>Fix</h3><p>Ensure database connections are opened, used, and closed as quickly as possible. By limiting the scope of the using statement to only the database operations, connections are released back to the pool immediately after they’re no longer needed.</p><pre>public async Task ProcessUpload(IFormFile file)<br>{<br>    // Using block releases connection after auth check<br>    using (var dbConnection = new SqlConnection(_connectionString))<br>    {<br>        await dbConnection.OpenAsync();<br>        await VerifyUserPermissions(dbConnection);<br>    }  // Connection released here!<br>    <br>    await ProcessLargeFile(file);<br>}</pre><h3>General tips for handling MySqlExceptions</h3><ul><li><strong>Implement retry mechanisms</strong>: Transient failures, such as temporary connection issues, can often be resolved by retrying the operation after a short delay.</li><li><strong>Use connection pooling</strong>: Use built-in connection pooling features (such as those in ADO.NET) to reuse SqlConnection instances with consistent connection strings. This practice avoids unnecessary opening of connections.</li><li><strong>Implement database timeouts</strong>: Set appropriate timeout values for your database operations to prevent long-running queries from holding connections indefinitely.</li><li><strong>Make queries faster</strong>: Aim for query execution times of less than 1 second by optimizing indexes, avoiding unnecessary data retrieval, and writing efficient SQL queries.</li></ul><h3>3. HttpRequestException</h3><p>An HttpRequestException pops up during HTTP requests when there are network issues, server errors, or timeouts. It’s a frequent occurrence in distributed systems and microservices that communicate over HTTP.</p><p>Many developers handle HTTP responses by checking status codes to determine success or failure states in their applications. A common pattern is to check for specific status codes like 200 for success or 404 for not found, and then handle the response content accordingly. This approach seems thorough at first glance.</p><pre>public async Task&lt;Customer&gt; GetCustomer(int id)<br>{<br>    var response = await _httpClient.GetAsync($&quot;/api/customers/{id}&quot;);<br>    <br>    if (response.StatusCode == HttpStatusCode.OK)<br>    {<br>        return await response.Content.ReadFromJsonAsync&lt;Customer&gt;();<br>    }<br>    else    <br>    {<br>        return null;<br>    }<br>}</pre><p>However, the above pattern overlooks a crucial aspect of HTTP communication — network-level failures. Even before your code gets a chance to examine the status code, the request could throw an HttpRequestException due to connection timeouts, DNS failures, SSL issues, or other infrastructure problems. Code that only handles status codes will break when these lower-level failures occur.</p><h3>Fix</h3><p>The solution is to implement proper exception handling around the HTTP request itself. By wrapping the request in a try-catch block that catches HttpRequestException, you can handle both status code responses and network-level failures. This creates a more resilient application that can gracefully handle application-level HTTP status codes and infrastructure and network issues that inevitably occur in distributed systems.</p><pre>public async Task&lt;Customer&gt; GetCustomer(int id)<br>{<br>    try <br>    {<br>        var response = await _httpClient.GetAsync($&quot;/api/customers/{id}&quot;);<br>        <br>        if (response.StatusCode == HttpStatusCode.OK)<br>        {<br>            return await response.Content.ReadFromJsonAsync&lt;Customer&gt;();<br>        }<br>        else if (response.StatusCode == HttpStatusCode.NotFound)<br>        {<br>            return null;<br>        }<br>        <br>        throw new ApplicationException($&quot;Unexpected status code: {response.StatusCode}&quot;);<br>    }<br>    catch (HttpRequestException ex)<br>    {<br>        // Handle network/infrastructure failures<br>        _logger.LogError(ex, &quot;Network error while fetching customer {CustomerId}&quot;, id);<br>        throw; // Or handle it according to your error strategy<br>    }<br>}</pre><h3>General tips for handling HttpRequestExceptions</h3><ul><li><strong>Add retry policies and set appropriate timeouts</strong>: Implement retry mechanisms for transient failures and configure timeouts to prevent hanging requests.</li><li><strong>Handle common status codes appropriately</strong>: Different HTTP status codes represent different issues. Handle them specifically to provide meaningful responses and actions.</li><li><strong>Use a crash reporting service</strong>: Integrating a <a href="https://raygun.com/platform/crash-reporting">crash reporting service</a> like Raygun helps capture and report errors experienced by clients, enabling developers to monitor and address issues proactively.</li><li><strong>Inspect HttpRequestException details</strong>: The HttpRequestException exposes diagnostic information through its StatusCode and InnerException properties. Common inner exceptions include SocketException (for network connectivity issues) and AuthenticationException (for SSL/TLS failures), helping you pinpoint the cause of the HttpRequestException.</li></ul><h3>4. TaskCanceledException</h3><p>A TaskCanceledException happens when an async operation gets canceled before it finishes. This can be triggered explicitly using a CancellationToken or implicitly, like when an HTTP request times out.</p><p>For example, think about a product search API. In this case, we’re trying to extend the timeout period for long-running searches, but there’s a fundamental misunderstanding of how HttpClient handles timeouts versus cancellation tokens.</p><p>In the problematic version, we create a CancellationTokenSource with a 180-second timeout, thinking this will override the default timeout:</p><pre>public async Task&lt;List&lt;Product&gt;&gt; SearchProductsBad(string query)<br>{<br>	// We want a longer timeout period<br>    CancellationTokenSource timeoutCts = new(TimeSpan.FromSeconds(180));<br><br>try <br>    {<br>        var response = await _httpClient.GetAsync($&quot;/api/products?q={query}&quot;, timeoutCts.Token);<br>        return await response.Content.ReadFromJsonAsync&lt;List&lt;Product&gt;&gt;();<br>    }<br>    catch (TaskCancelledException ex)<br>    {<br>        Console.WriteLine($&quot;Exception details: {ex.Message}&quot;);<br>        // Exception details: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.<br>    }<br>}</pre><p>The issue here is that creating a CancellationTokenSource with a 180-second timeout won’t override HttpClient’s built-in 100-second timeout. The HttpClient.Timeout property takes precedence, so the request will still timeout after 100 seconds, regardless of the CancellationToken’s timeout value.</p><h3>Fix</h3><p>We must properly extend the timeout period by directly modifying the HttpClient’s Timeout property. The request will now wait 180 seconds before timing out, rather than being constrained by the default 100-second timeout regardless of the CancellationToken settings.</p><pre>public async Task&lt;List&lt;Product&gt;&gt; SearchProducts(string query)<br>{<br>	_httpClient.Timeout = TimeSpan.FromSeconds(180);<br>    try <br>    {<br>        var response = await _httpClient.GetAsync($&quot;/api/products?q={query}&quot;);<br>        return await response.Content.ReadFromJsonAsync&lt;List&lt;Product&gt;&gt;();<br>    }<br>    catch (TaskCancelledException ex)<br>    {<br>        Console.WriteLine($&quot;Exception details: {ex.Message}&quot;);<br>        // Our exception handling can remain unchanged.<br>    }<br>}</pre><h3>General tips for handling TaskCancelledException</h3><ul><li><strong>Always pass a CancellationToken through the call chain</strong>: Ensure that every asynchronous method accepts and forwards a CancellationToken to allow callers to cancel operations as needed. For example, have a token that allows for user cancellation to avoid maintaining unnecessary query connections.</li></ul><pre>public async Task&lt;List&lt;Product&gt;&gt; SearchProducts(string query, CancellationToken userCt)<br>    {<br>        var response = await _httpClient.GetAsync($&quot;/api/products?q={query}&quot;, userCt);<br>    }</pre><ul><li><strong>Clean up resources when cancellation occurs</strong>: Ensure that all resources, such as database connections or file handles, are properly disposed of when an operation is canceled. For example, implement using blocks to dispose of resources automatically.</li></ul><pre>using (var resource = new Resource())<br>    {<br>        // do work<br>    } // Resource disposed here</pre><ul><li><strong>Set appropriate timeouts</strong>: Configure timeout durations that align with the expected duration of operations. This simplifies your code as manually requesting cancellation is not required.</li><li><strong>Implement cooperative cancellation for asynchronous programming</strong>: Ensure long running async methods periodically check the cancellation token.</li></ul><pre>public async Task DoWorkAsync(CancellationToken token)<br>    {<br>        for (int i = 0; i &lt; 100; i++)<br>        {<br>            if (token.IsCancellationRequested)<br>            {<br>                return<br>            }<br>        // Do work<br>        }<br>    }</pre><ul><li><strong>Use CancellationToken.None to explicitly disable cancellation</strong>: When implementing methods that accept cancellation tokens, use CancellationToken.None to explicitly indicate that cancellation is intentionally disabled rather than accidentally omitted.</li></ul><pre>await SearchProducts(query, CancellationToken.None);</pre><h3>5. AggregateException</h3><p>An AggregateException occurs when multiple errors occur during parallel or batch operations. It serves as a container for multiple exceptions that occur during parallel processing, task aggregation, or batch operations, allowing you to handle different types of failures collectively.</p><p>Consider a system processing multiple orders in parallel. Each order processing could fail for different reasons (timeout, not found, validation), and we need to handle these failures collectively while maintaining useful error information.</p><pre>Public void ProcessOrdersBad(List&lt;Order&gt; orders)<br>{<br>	try <br>	{<br>    		Task.WaitAll(orders.Select(order =&gt; ProcessOrder(order)).ToArray());<br>	}<br>	catch (AggregateException ae) <br>	{<br>		_logger.LogError(&quot;Exception processing orders&quot;);<br>	}		<br>}</pre><p>The code doesn’t handle the possibility of multiple failures occurring during parallel processing. When multiple tasks fail, the exceptions are bundled into an AggregateException, but the code doesn’t extract or handle these individual failures appropriately.</p><h3>Fix</h3><p>By flattening the exception, we can remove nested instances of the AggregateException making it easy to determine the root causes.</p><pre>public void ProcessOrders(List&lt;Order&gt; orders) <br>{ <br>    var tasks = orders.Select(order =&gt; ProcessOrder(order)); <br>    try <br>    { <br>        Task.WaitAll(tasks.ToArray()); <br>    } <br>        catch (AggregateException ae) <br>        { <br>            ae = ae.Flatten();<br>            var timeouts = ae.InnerExceptions.OfType&lt;TimeoutException&gt;().Count(); <br>            var notFounds = ae.InnerExceptions.OfType&lt;NotFoundException&gt;().Count(); <br>            var validations = ae.InnerExceptions.OfType&lt;ValidationException&gt;().Count(); <br>            // Log as appropriate<br>        } <br>    }</pre><h3>General tips for handling AggregateException</h3><ul><li><strong>Flatten the exception</strong>: Use ae.Flatten() to simplify nested AggregateException instances, making it easier to process all inner exceptions. This method removes any nested AggregateExceptions.</li></ul><pre>catch (AggregateException ae)<br>    {<br>        ae = ae.Flatten();<br>        // Process ae.InnerExceptions<br>    }</pre><ul><li><strong>Group and analyze inner exceptions by type</strong>: Categorize exceptions to provide better error reporting and take specific actions based on exception types.</li></ul><pre>var validationErrors = ae.InnerExceptions.OfType&lt;ValidationException&gt;();</pre><ul><li><strong>Use the TaskStatus Enum to identify failed tasks</strong>: The TaskStatus enum lets you determine which tasks have failed, enabling targeted error handling and recovery.</li></ul><pre>var failedTasks = tasks.Where(t =&gt; t.Status == TaskStatus.Faulted);</pre><h3>Wrap up</h3><p>By understanding these exceptions and how to manage them, you can prevent small oversights from turning into major failures. Better exception handling leads to more stable, maintainable applications — and happier managers. Check out <a href="https://raygun.com/blog/dotnet-exceptions-part-2/">part 2</a>, where we cover how to tackle EntityCommandExecution, OutOfMemory, KeyNotFound, StackOverflow, and InvalidOperation exceptions.</p><p><em>Article originally published on the </em><a href="https://raygun.com/blog/dotnet-exceptions-part-1/"><em>Raygun Blog</em></a><em>, written by Rowan Tandy.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383ade0848b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering AI systems with Model Context Protocol]]></title>
            <link>https://medium.com/@raygunio/engineering-ai-systems-with-model-context-protocol-ea1afafcc184?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1afafcc184</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 04:06:02 GMT</pubDate>
            <atom:updated>2025-01-08T04:07:25.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORcroMKsBvmmxzJtZX-9ew.png" /></figure><p>On November 26, 2024, Anthropic released the Model Context Protocol (MCP) — an open standard for data exchange between applications and data sources. MCP simplifies how Large Language Models (LLMs) interact with external tools and data, addressing the challenges developers face when integrating AI into their systems.</p><p>At Raygun, we’ve been exploring agentic workflows to improve productivity and saw real potential in MCP. This post will explain how MCP works, what we’ve implemented, and where we think the standard is headed.</p><h3>What’s in this article</h3><ul><li>The basics</li><li>What can MCP do?</li><li>Raygun MCP server</li><li>Building MCP servers</li><li>Current limitations</li><li>Looking forward</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ffast.wistia.net%2Fembed%2Fiframe%2Fkh8ussztle&amp;display_name=Wistia%2C+Inc.&amp;url=https%3A%2F%2Fraygun.wistia.com%2Fmedias%2Fkh8ussztle&amp;image=https%3A%2F%2Fembed-ssl.wistia.com%2Fdeliveries%2F9f3445271345fa90a1f0f854dfb43b2a2a599847.jpg%3Fimage_crop_resized%3D960x540&amp;type=text%2Fhtml&amp;schema=wistia" width="960" height="540" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74b49aa8a30c339cb0432176e6ff795/href">https://medium.com/media/d74b49aa8a30c339cb0432176e6ff795/href</a></iframe><h3>The basics</h3><p>MCP consists of two components: MCP hosts and MCP servers. A host, like Claude Desktop, acts as the AI interface. MCP servers connect the host to various data sources and tools. Servers advertise their capabilities — fetching files, querying a database, or making API requests — so a single host can access multiple servers simultaneously. Currently, MCP operates locally but still supports remote APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*4OdFy8rAn8uG65AXFjlamQ.png" /></figure><p>MCP introduces three key interfaces for data interaction: <strong>tools</strong>, <strong>prompts</strong>, and <strong>resources</strong>.</p><ul><li><strong>Tools</strong> are standardized actions declared on the server. They work like APIs, enabling tasks like searching the web, analyzing code, or processing data. Because tools follow a common standard, any MCP-compatible host can discover and use them.</li><li><strong>Prompts</strong> are reusable templates defined by servers that users can select to standardize everyday interactions. For example, a Git server might provide a ‘generate-commit-message’ prompt template that users can choose when they want to create standardized commit messages.</li><li><strong>Resources</strong> offer a consistent way to access read-only data, similar to file paths or database queries. For example, file:///logs/app.log or postgres://database/users.</li></ul><p>The initialization process is simple: an MCP host discovers the capabilities of connected servers and loads their tools, prompts, and resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*x52q_zGiubRNueyHLqJgLg.png" /></figure><p>In terms of security, MCP servers keep credentials and sensitive data isolated. Hosts don’t have direct access to these credentials, and all interactions require explicit user approval. This approach works well for MCP’s current local-first design, where servers are not publicly exposed.</p><h3>What can MCP do?</h3><p>MCP’s modular design allows hosts like Claude Desktop to act autonomously across multiple servers. There are many tasks that AI can accomplish now that hosts easily integrate with API endpoints and local data sources.</p><p>For example, Claude accessed and updated relevant project files while building <a href="https://github.com/MindscapeHQ/mcp-server-raygun">Raygun’s MCP server</a>. It recognized file dependencies, fetched the necessary context, and provided suggestions that sped up development.</p><p>The same applies to other servers. If your codebase is on GitHub, an MCP server can fetch specific files without requiring a complete clone of the repository. The <a href="https://github.com/modelcontextprotocol/servers/tree/main/src/github">Github MCP server</a> can also create branches and help with issue management.</p><p>Using an MCP server for tools like Puppeteer allows you to automate complex web interactions by allowing AI to interact with web pages. This <a href="https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer">Puppeteer MCP server</a> supports page navigation, screenshots, clicking, and hovering.</p><p>Using the <a href="https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps">Google Maps MCP server</a>, hosts like Claude Desktop can access location data and perform geocoding, place searches, route calculations, and travel times.</p><p>As more developers build MCP servers, the ecosystem grows. Each new server adds capabilities that any MCP-compatible host can use, making LLMs far more versatile.</p><h3>Raygun MCP server</h3><p>When MCP launched, we saw an opportunity to create an <a href="https://github.com/MindscapeHQ/mcp-server-raygun">MCP server</a> for the <a href="https://api.raygun.com/v3/swagger/index.html">Raygun API</a>. This server lets LLMs access error reports and performance data, making tasks like analysis and report generation easier. We’ve already seen internal improvements when using it to optimize Raygun’s web application. With this server, you can use LLMs like Claude to improve user experiences by finding slow pages and identifying fixes with AI.</p><h3>Building MCP servers</h3><p>Anthropic has made it easy to build MCP servers (we got ours running two days after release), supporting <a href="https://github.com/modelcontextprotocol/typescript-sdk">TypeScript</a> and <a href="https://github.com/modelcontextprotocol/python-sdk">Python</a> through their SDKs. Their <a href="https://modelcontextprotocol.io/llms-full.txt">full-text documentation</a> gives developers (or even AI tools) everything needed to create MCP servers and clients. One recommended way to <a href="https://modelcontextprotocol.io/tutorials/building-mcp-with-llms">get started</a> is to share the full-text documentation and SDK resources with an LLM, like Claude, to help set up a server it can later interact with.</p><p>When creating our own MCP server for Raygun, we found it helpful to plan out the categorization of data and functionality ahead of time. Deciding what to define as a tool, prompt, or resource made implementation much smoother. Once this structure is in place, programming becomes far more straightforward.</p><p>Anthropic also has many <a href="https://modelcontextprotocol.io/examples">examples of MCP servers</a> that developers can use as a jumping-off point. Another tool we found useful when creating the Raygun MCP server was the <a href="https://github.com/modelcontextprotocol/inspector">MCP Inspector</a>, which simplifies debugging by listing a server’s capabilities, running tools, and verifying responses.</p><h3>Current limitations</h3><p>Setting up MCP and adding servers to Claude Desktop requires technical knowledge, making MCP servers difficult for non-technical users to configure and operate. Even for technical users, GitHub is the only place to find or share new MCP servers, limiting discovery.<br>Additionally, MCP servers must run locally, restricting the scope of data they can access.</p><h3>Looking forward</h3><p>The Model Context Protocol is a good first step in standardizing how AI systems interact with tools and data sources. Reducing the complexity of integrations and enforcing a modular design makes it easier to build AI workflows. Anthropic is actively developing remote MCP hosts, so the local restriction will not be an issue for long.</p><p>At Raygun, we’re excited to continue working with MCP and contributing to its growth. With features like remote server support in active development by Anthropic, MCP could become the standard for integrating AI into applications.</p><p>For now, it’s a big step toward making AI tools more robust and adaptable.</p><p>Not a Raygun customer? <a href="https://app.raygun.com/signup">Try out the full Crash Reporting application free for 14 days!</a></p><p><em>Originally published on the </em><a href="https://raygun.com/blog/announcing-mcp/"><em>Raygun Blog</em></a>, written by Reilly Oldham</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1afafcc184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking OpenAI models for automated error resolution]]></title>
            <link>https://medium.com/@raygunio/benchmarking-openai-models-for-automated-error-resolution-74145dc4f492?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/74145dc4f492</guid>
            <category><![CDATA[error-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 02:35:20 GMT</pubDate>
            <atom:updated>2024-08-08T02:35:20.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbX282hf01EtPtYOF9PBWQ.png" /></figure><p>Large Language Models (LLMs) are increasingly shaping the future of software development, offering new possibilities in code generation, debugging, and error resolution. Recent advancements in these AI-driven tools have prompted a closer examination of their practical applications and potential impact on developer workflows.</p><p>This article explores the effectiveness of LLMs in software development, with a particular focus on <a href="https://raygun.com/ai-error-resolution">error resolution</a>. Drawing from industry-wide observations and insights gained through <a href="https://raygun.com/blog/gpt4omini-raygun-ai-error-resolution/">my work with AI Error Resolution</a> at Raygun, I’ll analyze LLMs’ current capabilities and their implications for the future of development practices. The discussion will weigh both the promising advancements and the challenges that arise as these technologies integrate into our daily work.</p><h3>OpenAI models for software development</h3><p>OpenAI has successfully released newer, faster, and allegedly smarter models. While benchmark sites confirm these results, we see more and more anecdotal data claiming that <a href="https://community.openai.com/t/declining-quality-of-openai-models-over-time-a-concerning-trend/847753">these models feel dumber</a>. Most existing benchmarks focus purely on the logical reasoning side of these models, such as completing SAT questions, rather than focusing on qualitative responses, especially in the software engineering domain. My goal here is to quantitatively and qualitatively evaluate these models using <a href="https://raygun.com/ai-error-resolution">error resolution</a> as a benchmark, given its common use in developers’ workflows.</p><p>Our comprehensive evaluation will cover several models, including GPT-3.5 Turbo, GPT-4, GPT-4 Turbo, GPT-4o, and GPT-4o mini. We’ll use real-life stack traces and associated information sent to Raygun to assess how these models handle error resolution. Factors such as response speed, quality of answers, and developer preferences will be thoroughly examined. This analysis will lead to suggestions for extracting the best responses from these models, such as the impact of providing more context, like source maps and source code, on their effectiveness.</p><h3>Experimental methodology</h3><p>As mentioned, we will evaluate the following models: GPT-3.5 Turbo, GPT-4, GPT-4 Turbo, GPT-4o, and GPT-4o Mini. The specific variants used are the default models provided by the OpenAI API as of July 30, 2024.</p><p>For our evaluation, we selected seven real-world errors from various programming languages, including Python, TypeScript, and .NET, each combined with different frameworks. We selected these by sampling existing errors within our Raygun accounts and personal projects for a representative sample. Errors that were transient or did not point to a direct cause were not selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*3rFtFDabXXg2qF8yOUvb8g.png" /></figure><p>We then used a templated system prompt from <a href="https://raygun.com/ai-error-resolution">Raygun’s AI Error Resolution</a>, which incorporated information from the crash reports sent to Raygun. We tested this directly across all the models through OpenAI’s API. This process generated 35 LLM error-response pairs. These pairs were then randomly assigned to engineers at Raygun, who rated them on a scale of 1 to 5 based on accuracy, clarity, and usefulness. We had a sample of 11 engineers, including Software and Data Engineers, with mixed levels of experience, from engineers with a couple of years of experience to a couple of decades of experience.</p><p>In addition to the preference ratings, we will also conduct an analytical analysis of the models’ performance. This analysis will focus on two key aspects, <strong>response time and response length</strong>, which we will then use to derive multiple measures of these models’ effectiveness.</p><h3>Developer preferences — qualitative results</h3><h4>General observations</h4><p>We produced the graph below based on the engineers’ ratings. From this, there are a few distinct results that both support and contradict the anecdotal evidence. While this analysis focuses on error resolution, comparing these findings with other motivational factors discussed in the introduction is essential. For instance, the model’s effectiveness in error resolution might differ from their performance in tasks like code generation or debugging, which could influence overall perceptions. This broader perspective helps us understand the varying impacts of large language models on different aspects of a developer’s workflow.</p><h4>Unexpected findings</h4><p>We assumed GPT-4 would be the best model, but our software engineers rated it the worst. We can provide possible justifications for this result using the feedback from our software engineers and some of the analytic data, which we will show in the next section. These hypotheses resulted from my discussions with another engineer who closely followed this study. The later models of GPT-4 Turbo and onwards include code snippets when suggesting changes and engineers have reported that this gives them a better understanding of the solutions. GPT-4 did not generate snippets and has longer solutions than GPT-3.5 Turbo, indicating that engineers dislike longer responses that do not contain supplementary resources.</p><h4>Error patterns</h4><p>We also observed that the JSON validation error consistently received very low rankings across all model variants because the stack trace alone doesn’t provide a good solution for this error; this leads us to prompt engineering and what information is helpful when asking an LLM for help.</p><h4>Contextual Influences</h4><p><strong>For .NET errors</strong></p><p>.NET errors comprised all of these test cases except for the division by zero error and the invalid stop ID, as described in an earlier table. The result is that only the context the LLMs and engineers were made aware of was the stack trace, tags, breadcrumbs, and custom data. We see a higher reported score on these errors, likely because the engineers here at Raygun primarily work with .NET. However, in the cases where we tested different languages, we still observed good results.</p><p><strong>Other languages</strong></p><p>Based on the engineers’ comments, the reason for this is that in both the Python and TypeScript cases, the stack trace came with the surrounding code context. The surrounding code context was provided as part of the stack trace in Python, and in the TypeScript error, this was from the source maps with source code included. With this additional information, the LLMs could generate code snippets that directly addressed the errors, which also helped with the ratings of the later series of GPT-4 variants.</p><h4>Performance insights</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IH9_yrxyuRhqjuEGr_LtzQ.png" /></figure><p><strong>Decline in performance after GPT-4 Turbo</strong></p><p>Looking at the scores of GPT-4 Turbo and onwards, we see a drop in ratings, especially once we reach GPT-4o, though these results are still better than GPT-4, and most are better than GPT-3.5 Turbo. If we remove the JSON serialization error as an outlier, we can still observe a decline in performance after GPT-4 Turbo. This result clearly shows that the performance of the GPT-4 series peaked with GPT-4 Turbo and declined afterward.</p><p><strong>The importance of context for non-descriptive stack traces</strong></p><p>This poor performance from the JSON serialization error is likely due to the need for supporting information on the underlying issue. Just looking at the stack trace makes it challenging to pinpoint the error, as there were multiple points of failure. Again, this plays into the topic of including more context, such as source code and variable values, to hint at where the issue could be. An enhancement here could be a RAG lookup implementation on the source code, so it is possible to associate the stack trace with the corresponding code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qi1anBq6ccl84SW_2ovP_Q.png" /></figure><p><strong>Impact of response length on performance</strong></p><p>One theory for this worsening performance in the later models is the increase in response length. These models may fare better in heavier logic-based questions, but these longer responses are undesirable in everyday conversation. I have encountered this when asking questions about Python libraries, where I would like a direct answer. Each time, it would repeat a whole introduction section on setting up the library and useless information regarding my question.</p><p>If this is the case, we would like to see some corrections to this when newer models come out, such as GPT-5 and other competitors, but for now, the wordiness of these models is here to stay.</p><h3>Analytical analysis — quantitative results</h3><h4>Response time and content generation</h4><p>While qualitative evaluation of LLM responses is essential, response time/generation speed and the amount of content generated also significantly impact these tools’ usefulness. Below is a graph showing the average response time to create a chat completion for the error-response pair.</p><p>Interestingly, <strong>GPT-4 Turbo is the slowest model regarding average response time</strong> to generate a chat completion. This is a surprising result, as general understanding suggests that GPT-4 Turbo should be faster than GPT-4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uSQBQDTDGTXSEQlpMc9D3g.png" /></figure><h4>Token generation and model performance</h4><p>The next graph explains this surprising result by measuring the average number of tokens generated by each model. This shows that GPT-4 Turbo generates significantly more tokens on average than GPT-4. Interestingly, the previous graph shows GPT-4o generates the most tokens but is still considerably faster than GPT-4 Turbo.</p><p>We also see that this trend of more tokens does not continue with OpenAI’s latest model, GPT-4o mini. The average number of tokens decreases compared to GPT-4 Turbo but remains well above GPT-4. The model generating the least number of tokens is GPT-3.5 Turbo, which aligns with the qualitative analysis results, where engineers preferred shorter responses as opposed to lengthier responses with no supplemental explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*y9WNGyBDMZc2LWMPsjNjuQ.png" /></figure><h4>Per-token response time</h4><p>After examining the response time and average token count by model, we can determine each model’s speed with respect to response time and token generation.</p><p>Below is a graph showing the per-token response time by model. Here, we see that GPT-4 is faster than GPT-4 Turbo, but this is due to an outlier in the data. Given its tendency to generate longer outputs, its overall response time is still longer than GPT-4. This may mean that GPT-4 Turbo is a less desirable model when it generates too much content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OEbb6WdY4vNdSLu3-eMZ5g.png" /><figcaption>Note: GPT-3.5, GPT 4, and GPT-4o models use different tokenizers</figcaption></figure><h4>Comparison of GPT-4o and GPT-4o mini</h4><p>Interestingly, the data shows that GPT-4o and GPT-4o mini have similar response speeds, contrasting with other sources’ findings. This discrepancy suggests that a larger sample size may be needed to reveal a more pronounced difference in their performance. Another explanation is that given that we are measuring the tokens per second by the total response time, we are slightly skewing the values to be lower due to Time To First Token (TTFT) and other network-related bottlenecks.</p><h4>Scaling patterns</h4><p>Plotting the response time versus token count, grouped by model, reveals distinct patterns in these models’ scaling. For GPT-3.5, GPT-4o, and GPT-4o Mini, the scaling is mostly linear, with an increase in token count leading to a corresponding increase in response time.</p><p>However, this pattern does not hold for the larger and older models of the GPT-4 series, where these two variables have no consistent relationship. This inconsistency could be due to a smaller sample size or fewer resources dedicated to these requests, resulting in varying response times. The latter explanation is more likely given the linear relationship observed in the other models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8XZkd1xbpaB_AAw0V4uIwg.png" /></figure><h4>GPT-4 context limitations</h4><p>One final piece of analysis emerged from generating these error-response pairs. While the GPT-4 model is competent, its context length is significantly limited for tasks requiring long inputs, such as stack traces. Due to this, one error-response pair could not be generated because the combined input and output would exceed the model’s 8192-token context window.</p><h4>Joint analysis</h4><p>After assessing the qualitative data, it is evident that GPT-4 Turbo is the best model for this task. However, comparing this to the quantitative data introduces response time and cost considerations. The new GPT-4o models are substantially faster and considerably cheaper than all other models, presenting a tradeoff. GPT-4 Turbo is the preferred choice if slightly better performance is required. However, if cost and speed are priorities, GPT-4o and GPT-4o mini are better alternatives.</p><h4>Conclusion</h4><p>In conclusion, our study provides mixed evidence regarding the performance of later models. While some newer models, like GPT-4 Turbo and GPT-4o, showed improvements due to their ability to include concise code snippets, others, like GPT-4, fell short due to verbose and less practical responses.</p><p><strong>Key takeaways:</strong></p><ol><li><strong>Code snippets matter</strong>: Models that provide code snippets and explanations are more effective and preferred by developers.</li><li><strong>Context is critical</strong>: Adding surrounding code or source maps significantly enhances the quality of responses.</li><li><strong>Balance response length</strong>: Shorter, more concise responses are generally more helpful than longer, verbose ones.</li><li><strong>Regular evaluation</strong>: Continuously assess model performance to ensure you use the most effective tool for your needs.</li><li><strong>Mind context limits</strong>: Be aware of the context length limitations and plan accordingly.</li></ol><p>By focusing on these factors, developers can better leverage LLMs for error resolution, ultimately enhancing their productivity and the accuracy of their solutions.</p><p>Future experiments that would complement this study could include a deeper analysis of code generation, as mentioned in the introduction. One possible experiment could involve taking the suggestions from the error resolution and providing additional context to the LLMs. Ideally, if this study were to be redone, it would be beneficial to include a wider variety of errors, including more challenging ones, and gather ratings from a more diverse set of engineers.</p><p><em>There’s never been a more exciting time to get started with Raygun! </em><a href="https://app.raygun.com/signup"><em>Try out Crash Reporting, including AI Error Resolution, free for 14 days.</em></a></p><p>Post written by Reilly Oldham. Originally published on the <a href="https://raygun.com/blog/benchmarking-openai-models-for-automated-error-resolution/">Raygun Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74145dc4f492" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI realism (part one) | Raygun Blog]]></title>
            <link>https://medium.com/@raygunio/ai-realism-part-one-raygun-blog-b00f0157d1d4?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b00f0157d1d4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 20:14:01 GMT</pubDate>
            <atom:updated>2024-04-10T23:58:44.263Z</atom:updated>
            <content:encoded><![CDATA[<p>By JD Trask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhVn-Fsn2wl08mfPPa8B_A.png" /></figure><p><em>Emotions are running high about AI technologies. In this 2-parter, I do my best to make a rational case on the reality of AI, and how we can respond to it. This is part one; find </em><a href="https://raygun.com/blog/ai-realism-part-2/"><em>part two here</em></a><em>.</em></p><p>We seem to be struggling to have pragmatic discussions about advancements in Artificial Intelligence. It’s hard to hear calmer voices over the detractors and breathless enthusiasts. Today, I want to make a reasoned, evidence-based case for the potential of this technology, glance at present and future applications, and offer some practical examples for implementing <a href="https://raygun.com/ai-principles">AI within an organization</a>.</p><p>Now, let me preface by saying that these tools are far from perfect. There are <a href="https://raygun.com/ai-principles">valid concerns</a> about the hallucinations, the confidently inaccurate answers, the ethics, and the shortcomings. Some are <a href="https://doctorow.medium.com/the-ai-hype-bubble-is-the-new-crypto-hype-bubble-74e53028631e">drawing analogies to crypto</a>, predicting an explosion of scams and frauds, and claiming that there’s no real substance there.</p><p>While cynicism about crypto has proven fairly valid, this moment seems less like cryptocurrency’s self-promoting hype machine and more of a paradigm change like the internet. After all, don’t forget how the internet started out. Sluggish dial-up speeds and disastrous usability, often waiting hours just to watch one janky download. It was painful, but we did it anyway, because everybody could see the outlines of what made this amazing. And that’s exactly, in my opinion, where we are with AI right now. We have a lot to work out still, but we can all see the promise.</p><p>This is a very different world from the one we lived in at the <a href="https://en.wikipedia.org/wiki/History_of_the_World_Wide_Web">birth of the internet</a>, or even the crypto gold rush of 2017. What’s different? Well, we stopped the global economy to respond to a pandemic. We’re now dealing with <a href="https://www.worldbank.org/en/publication/wdr2022/brief/chapter-1-introduction-the-economic-impacts-of-the-covid-19-crisis">the fallout of that</a>. Investors have largely pulled back in the market; valuations have been adjusted. People who raised capital now face much more significant challenges in getting a follow-on round. The pain of higher interest rates is flowing through to even the smallest essentials with inflation. Globally, there’s renewed emphasis on productivity and doing more with less to pay off our accumulated debt.</p><p>Then, just as everything looks quite dire, we’ve introduced a revolutionary technology that can expand the productivity of the human race massively.</p><p>Now, that may sound too good to be true. Let me explain why this could be such a radical solution.</p><p>Early in his career, Jeff Bezos worked for a hedge fund. He was doing fine, but obviously had bigger ambitions. One day, he <a href="https://finance.yahoo.com/news/jeff-bezos-believed-amazon-only-154224448.html">read that the internet was growing at 2300%</a> per year. He knew immediately that there were huge opportunities in an environment with that kind of growth rate. He quit the hedge fund. That was 1994.</p><p>The following year, Bill Gates pivoted Microsoft dramatically towards the internet. Mature readers may recall how Microsoft in the nineties was about as terrifying a juggernaut as today’s Google, Amazon, and Facebook combined. They basically controlled everything that happened on any given computer. And yet, Gates looked at the rise of the World Wide Web and decided they needed to change direction. He sent out the <a href="https://lettersofnote.com/2011/07/22/the-internet-tidal-wave/">“Internet Tidal Wave” memo</a>, calling it “the most important single development to come along.”</p><p>Bezos and Gates are in their current positions because they caught on early enough to take advantage of the ascension of the online world.</p><p>The internet took until roughly 1997–98 to <a href="https://www.nytimes.com/1999/11/12/business/internet-users-now-exceed-100-million.html">hit a hundred million global users</a>.</p><p>I believe that AI will dwarf the impact of the internet. In the case of ChatGPT, we went from <a href="https://www.theverge.com/2023/11/6/23948386/chatgpt-active-user-count-openai-developer-conference#:~:text=ChatGPT%20was%20widely%20seen%20as,2004%2C%20Twitter%20took%20over%20five">zero to a hundred million users</a> in under three months, not years. Everything is speeding up, and we need to be catching this early and seizing our moment to pivot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*UxN45CK0EcWtTnWC.jpg" /></figure><p><em>Image source @EconomyApp</em></p><p>Looking at tools like <a href="https://copilot.microsoft.com/">CoPilot</a>, it’s already clear how we’ll be able to get more information more quickly, generate analysis, spot trends, and combine datasets. We can cut hours of busy work and focus on the higher-value things that humans remain uniquely good at.</p><p>Another simple example is <a href="https://learn.microsoft.com/en-us/microsoftteams/meeting-transcription-captions">Microsoft Teams’ automatic transcription</a>. Previously, a team member took notes during meetings, then edited and filed them. The results were slightly different depending on who took the notes and what they perceived as being the important parts of the discussion. Now, the team can stay present in the meeting, we remove the risk of misinterpretation, and so on. These things boost our ability to get work done right now.</p><p>These are helpful, but not revolutionary. In 1997 terms, I remember that it was a big deal when Microsoft Word shipped with the ability to insert a hyperlink in a document. In hindsight, the <a href="https://en.wikipedia.org/wiki/History_of_Microsoft_Word">developments in the mid-to-late nineties</a> weren’t all that groundbreaking. It wasn’t until after the .com bubble that tech got seriously competitive and built some of the massive advancements that we use today.</p><p>It’s still early days. We’ll see a lot of stuff being shipped, and most of it won’t last. Part of the problem right now is there’s kind of a fog of war. There are so many options to keep track of and they’re changing so fast, and it’s impossible to know what’s just hype.</p><p>A lot of people think of AI as simply ChatGPT, and that’s their entire concept of this. ChatGPT is a large language model. You ask questions, or prompt the model, and it gives you an answer. Skeptics point out that this is just a “fancy auto-complete”. It’s not really thinking, it’s not really synthesizing anything. And that’s mostly true. However, that’s also a fairly naive, non-technical evaluation. The reality is that the large language model is a breakthrough based on transformer technology, but that’s just one piece of these systems.</p><p>Objectively, we all have something that’s similar to an LLM inside our own brain. What we don’t have though, in AI, is consciousness, which is what decides what to prompt. The human brain has all of these other subsystems that we can’t replicate (yet), but the LLM is a pretty powerful piece of the puzzle.</p><p>However, there are frameworks out there like <a href="https://www.langchain.com/">LangChain</a>, that sit above an LLM and perform higher-level orchestration. Let’s say we want to build a virtual sales development rep. We’d tell it to come up with criteria, build a list of prospects, contact them all at a particular time, wait a certain amount of time to follow up, etc. You could ask the LLM, what are the steps for a successful SDR campaign? Then, you can have a series of agents that sit above that, so that effectively each answer becomes the input for the next step in the chain. At that point, we’re getting much more than a plain-text set of instructions. We can orchestrate a series of autonomous actions. LangChain can connect things into a smarter, more sophisticated system, making it much more approachable for “normal” people to build their own websites, scripts, and tools.</p><p>This is where you could give the system rules and understanding. You hear people say, look, these tools can’t do reasoning. Fair enough. There are, however, algorithms that use a chain of reasoning, that can interpret that if x and y are true, that implies this. And that’s where a lot of work is going. It doesn’t mean the computer is thinking, but it’s a hell of a lot more than auto-complete.</p><p>The tech around this right now is still unvarnished, but it’s being worked on even as I type this. Like the internet itself, it’s fiddly and difficult to work with, but there is gold in these hills for the people who figure it out.</p><h3>So, what should I be doing right now?</h3><p>While these are still the first few snowballs of a much bigger avalanche, there’s exciting stuff to act on and try out right now, out-of-the-box. Here’s what I recommend in the here and now.</p><p><strong>Expert review:</strong> We sometimes do custom terms with larger enterprise customers, and that usually means we need to review some of the wording in those contracts. Now, I can read a legal document and have a pretty good understanding, but there are usually things I’m not sure about. One came through recently, and our lawyers quoted $4,000 to review two clauses. So I just put those clauses into ChatGPT, and asked for the risks and ramifications. There’s $4,000 I didn’t have to spend. To be clear, this is at your own risk; obviously legal documents are sensitive and sometimes you just need the peace of mind. But start considering what expertise you can automate and then fact-check.</p><p><strong>Improve communications:</strong> One of the most attainable uses of AI is to review communications. People will upload a drafted email, social media post, a product description, and ask what could be improved, can you reduce the word count by 50%, and so on. We’re also using image generation within the design team, experimenting to get it to adhere to our brand guidelines.</p><p>The cost of content creation, especially generic content, has plummeted. Some people have seen an arbitrage opportunity that will only exist for the next 12 months, and just generate masses of low quality content to capture some value. That’s not sustainable, but what is sustainable is integrating generative tools into your existing tasks, guided by creative professionals.</p><p><strong>Form habits early:</strong> The easiest steps are obvious ones. Get a ChatGPT account (I’ve set the OpenAI chat webpage to be an “app” on my taskbar, so that it’s visible and accessible). Use their latest model — it’s the best there is (right now). Don’t wait for it to be perfect or mandatory. Start trying things, changing your habits, and shifting your muscle memory.</p><p>Previously, to solve a problem, I’d determine what I wanted to achieve, and then plan out the execution in steps, Googling any I was unsure of. It takes time and discomfort to bypass that habit and go straight to asking for the final output. It’s a big shift, because it’s not how anything has worked previously. A fundamental adjustment to how we all think and behave.</p><h3>How can we maintain security?</h3><p>As I say, things are moving fast right now, and velocity and safety are often at odds. Many organizations have opted out of using these models at all to protect sensitive information.</p><p>You’re probably familiar with Europe’s <a href="https://raygun.com/gdpr">GDPR requirements</a>, which grant the right to be forgotten; to request everything an entity knows about me and require them to remove it. Right now, you can’t remove data from a large language model. OpenAI spent millions training that model, and removing data would mean starting again.</p><p>So how can you use these tools securely? If you’re highly safety-conscious, you can self-host a model. However, you need some grunty hardware to run it. From the outset, we resolved firmly at Raygun that none of our customer data would go to OpenAI. One of the outcomes of our AI-week is we’re building a fairly powerful server to self-host some models with our internal data. Worst-case scenario, we can just delete the model. There are a lot of these open-source models; they’re all different. It’s harder than just calling OpenAI, but you also get to learn about how to train them and how they actually work.</p><h4>Stay curious</h4><p>No one’s an expert right now. AI is recursive, and it’s changing every day. It is helping accelerate its own development. People say it can’t think, and they’re right. However, we’ve built this massive database of everything that it can infer. So it can help us identify things that maybe aren’t as obvious to a human, that can be connected together to achieve an outcome.</p><p>It starts with writing an email faster, but this quickly gets us thinking bigger. How can we actually, dramatically improve the effectiveness of our workplaces? Honestly, this is destined to impact the way we work regardless. Everybody is going to face a challenge here over the next few years. And the more they understand, the better prepared they can be for that. We should all keep pushing to educate ourselves and each other, encourage, and experiment. More on that, and more on Raygun’s AI-driven projects, in Part 2.</p><p><em>Originally published at </em><a href="https://raygun.com/blog/ai-realism-part-1/"><em>https://raygun.com</em></a><em> on March 19, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b00f0157d1d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practices for writing clean, maintainable JavaScript]]></title>
            <link>https://medium.com/@raygunio/best-practices-for-writing-clean-maintainable-javascript-cca3d4174f5a?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca3d4174f5a</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 20:53:40 GMT</pubDate>
            <atom:updated>2024-02-29T20:53:40.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*db9x1aQ2aPw8_pLgPpJJSw.jpeg" /></figure><p><strong>By Anna Monus</strong></p><p>The world’s biggest language comes with a huge collection of conventions and guidelines from the community’s collective wisdom. Following JavaScript best practices can help achieve faster page loads and better performance, improve code readability, and make maintenance and debugging easier. Carefully crafted code can also prevent errors and security issues, especially if it’s complemented with real-time diagnostic tools such as <a href="https://raygun.com/languages/javascript">JavaScript error monitoring</a>.</p><p>In this article, we’ll look into a selection of JavaScript best practices that you can use in front-end development.</p><h3>Quicklinks</h3><ul><li><a href="https://raygun.com/blog/javascript-best-practices/#stylingandnaming">JavaScript styling and naming best practices</a></li><li><a href="https://raygun.com/blog/javascript-best-practices/#coding">JavaScript coding practices</a></li><li><a href="https://raygun.com/blog/javascript-best-practices/#classes">JavaScript classes best practices</a></li><li><a href="https://raygun.com/blog/javascript-best-practices/#nextsteps">Next steps</a></li></ul><h3>JavaScript styling and naming best practices</h3><h3>1. Choose a JavaScript coding style guide and stick to it</h3><p>Even though you can set up your own coding guidelines that fit with your goals, you don’t necessarily have to. There are multiple ready-to-use JavaScript coding style guides that are well tested and widely used across the industry. Some examples include the community-based <a href="https://github.com/rwaldron/idiomatic.js">Idiomatic JavaScript</a>, the <a href="https://google.github.io/styleguide/jsguide.html">Google JavaScript Style Guide</a>, and <a href="https://github.com/airbnb/javascript">AirBnB’s JavaScript Style Guide</a>.</p><p>Using a coding style guide is especially important in teamwork, where multiple developers are working on the same project. As Idiomatic JavaScript puts it, “all code in any code base should look like a single person typed it, no matter how many people contributed.” Whether you create your own style guide or use a third-party one, consistent code will be easier to read, write, debug, and maintain.</p><h3>2. Give descriptive names to variables and functions</h3><p>Make the names of your variables, functions, and other code structures easy to understand for anyone who works with your code. Don’t use names that are either too short or too long, and take care that they succinctly describe their own purpose.</p><p>Some good examples are (from the DOM API):</p><ul><li>Properties (variables): firstChild, isConnected, nextSibling</li><li>Methods (functions): getResponseHeader(), addEventListener()</li><li>Objects: XMLHttpRequest, NodeList</li><li>Interfaces: HTMLCollection, EventTarget</li></ul><p>Also keep in mind that JavaScript is a case-sensitive language. As <a href="https://wiki.c2.com/?CamelCase">camel case capitalization</a> is the most common naming system in JavaScript programming, you should use lower camelcase for variables and functions and upper camelcase for classes and interfaces for better code readability.</p><h3>3. Use shorthands, but be careful with them</h3><p>JavaScript includes many shorthands that allow you to write code faster and make your scripts load faster.</p><p>There are older shorthands that have been part of the JavaScript syntax for ages, such as the if true shorthand:</p><pre>/* Longhand )*/<br>if (value = true) { … }<br><br>/* Shorthand */<br>if (value) { … }</pre><p>And of course, there are newer ones, too, such as arrow functions introduced in ECMAScript 6:</p><pre>// Longhand<br>let add = function(a, b) {<br>	return a + b;<br>}<br><br>// Shorthand<br>let add = (a,b) =&gt; a + b;</pre><p>Sometimes, however, shorthands might return surprising results. So, always be sure of what you’re doing, check the documentation, find relevant JavaScript code examples, and test the outcome.</p><h3>4. Comment your code, but keep it short</h3><p>Commenting is a hot topic in programming. Some say it’s not necessary at all, but code without any comments gets hard to read after a while — especially when working on team or legacy projects. On the other hand, overly long and verbose comments are unnecessary because they’ll take extra time to read through and understand.</p><p>As a rule of thumb, comment your code, especially functions, classes, objects, and interfaces, but only include key information. To keep your comments concise and easy to read, use tags such as @constructor, @param, @version, @return, and others.</p><p>Here’s an example of a short but descriptive comment from <a href="https://jsdoc.app/about-getting-started.html#adding-documentation-comments-to-your-code">JSDoc’s guidelines</a>:</p><pre>/**<br>* Represents a book.<br>* @constructor<br>* @param {string} title - The title of the book.<br>* @param {string} author - The author of the book.<br>*/<br>function Book(title, author) { … }</pre><p>If you comment your JavaScript code properly, you can also use a tool such as JSDoc to automatically generate documentation for your project.</p><h3>JavaScript coding practices</h3><h3>5. Avoid using JavaScript to add styling</h3><p>Taking separation of concerns (SoC) seriously is one of the most important JavaScript coding practices. Technically, JavaScript allows you to directly change the CSS code using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style">style</a> property. However, to make debugging easier and improve code maintainability, it’s best to avoid it.</p><p>As an alternative, you can add and remove classes using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/classList">ClassList</a> API as follows (then add the style rules with CSS):</p><pre>// selects the first p tag on the page<br>let p = document.querySelector(&quot;p&quot;);<br><br>// dynamically adds classes<br>p.classList.add(&quot;class-1&quot;, &quot;class-2&quot;);<br>// dynamically removes classes<br>p.classList.remove(&quot;class-3&quot;, &quot;class-4&quot;);<br>// based on the presence of the class, it&#39;s either added or removed<br>p.classList.toggle(&quot;class-5&quot;);</pre><h3>6. Declare local variables with let and const</h3><p>As global variables are available to all the scripts running on your page, they can easily be overridden by other variables using the same name. There are various ways to reduce the number of global variables, but ECMAScript 6 has introduced two new JavaScript statements you can use to declare variables in the local scope: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a>.</p><p>Both let and const create block-scoped local variables, but let can be re-declared (in a different scope) while const can’t. As opposed to var, neither let nor const becomes a property of the window object, so they can’t be accessed, and therefore overridden, by other scripts — even when they are declared globally (in the highest scope).</p><p>You can define let with or without a value (however, it can only be read and written after full initialization), but you can’t declare const without a value:</p><pre>let localVar;<br>let localVarText = &quot;text string&quot;;<br><br>const LOCAL_CONST = 999;</pre><h3>7. Use for...of instead of for loops</h3><p>Loops can get costly performance-wise because you repeat the same operation over and over again. However, if you optimize them, you can make them run faster.</p><p>There are many JavaScript best practices to write more performant loops, such as avoiding nesting, keeping DOM manipulation outside of loops, and declaring a separate variable for the length of the loop (e.g. let cityCount = cities.length).</p><p>Using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> statement instead of for is such a JavaScript coding practice, too. This syntax has been introduced by ECMAScript 6, and it includes a built-in iterator so that you don’t have to define the i variable and the length value:</p><pre>// with for loop<br>let cities = [&quot;New York&quot;, &quot;Paris&quot;, &quot;Beijing&quot;, &quot;Sao Paulo&quot;, &quot;Auckland&quot;];<br>let cityCount = cities.length;<br><br>for(let i = 0; i &lt; cityCount; i++) {<br> console.log( cities[i] );<br>}<br>// with for...of loop<br>let cities = [&quot;New York&quot;, &quot;Paris&quot;, &quot;Beijing&quot;, &quot;Sao Paulo&quot;, &quot;Auckland&quot;];<br>for(city of cities) {<br> console.log(city);<br>}</pre><p>You can use the for...of loop to iterate over any iterable object, such as arrays, strings, nodelists, maps, and more.</p><h3>8. Create helper functions for common tasks</h3><p>The topic of modularization comes up frequently in discussions of JavaScript best practices. Modularization means the splitting of larger files into smaller parts — a.k.a. reusable modules. ECMAScript modules and module bundlers such as Webpack help with setting up such architecture, but creating modular and reusable functions is just as important.</p><p>As the <a href="https://raygun.com/blog/solid-design-principles/">first SOLID design principle</a> (single responsibility principle) states, every function, interface, class, and other code structure should perform only one task. Creating helper functions for common tasks is one way to follow this principle. Helper functions should be context-independent so that they can be called from any module.</p><p>To see some JavaScript functionality examples, check out <a href="https://github.com/cferdinandi/vanilla-js-toolkit">The Vanilla JS Toolkit</a> that includes smart helper functions such as animate(), getParents(), pick(), shuffle(), and others. For example, here’s the pick() function — as you can see, it performs one single action:</p><pre>function pick (obj, props) {<br><br>// Create new object<br> var picked = {};<br> // Loop through props and push to new object<br> for (let prop of props) {<br>  picked[prop] = obj[prop];<br> }<br> // Return new object<br> return picked;<br>}</pre><h3>JavaScript classes best practices</h3><h3>9. Avoid creating irrelevant classes</h3><p>Using classes is another hot topic in JavaScript programming. Even though JavaScript has a prototypical inheritance model, ECMAScript 6 has introduced the class syntax to improve code readability. It’s frequently referred to as “syntactic sugar” as it doesn’t add any new functionality, and, as <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance#ecmascript_2015_classes">stated by the MDN Docs</a>, classes are “being converted into Prototypal Inheritance models” under the hood.</p><p>So whether you use classes or not mainly depends on your preferences and project requirements — but if you do decide to use the class syntax, there are, of course, some JavaScript best practices to follow.</p><p>First and foremost, you need to avoid creating irrelevant classes to build a well-structured application. Classes can be irrelevant for a couple of reasons, including:</p><ul><li>Catch-all classes that do more than one thing (or everything)</li><li>Classes that only have data (properties) but no actions (methods) — try to move the data into another class</li><li>Classes that only include behavior (methods) but no data (properties) — in this case, it’s better to create a function</li></ul><p>Overall, classes should respect the single responsibility principle (similar to functions) and include both data and behavior, for example:</p><pre>class Product {<br>	constructor(name, price) {<br>		this.name = name;<br>		this.price = price;<br>	}<br>	displayInfo() {<br>		console.log(&#39;Hi, you can see a &#39; + this.name + &#39; that costs $&#39; + this.price);<br>	}<br>}</pre><h3>10. Pay attention to (the lack of) hoisting when using classes</h3><p>In JavaScript, classes are a special type of function, but they don’t always behave like ordinary functions, which can lead to some confusion.</p><p>For instance, unlike functions, classes are not hoisted. Hoisting means that the JavaScript interpreter moves function declarations to the top of their scope so that they can be called before being declared. When working with classes, you can’t take advantage of this feature, however.</p><p>You always need to declare a class before you call it, otherwise you’ll get an uncaught reference error. Following the previous example with the Product class:</p><pre>// uncaught reference error<br>const hat = new Product(&quot;red hat&quot;, 1000);<br>hat.displayInfo();<br>class Product { … }<br><br>// good order - the class is declared first<br>class Product { … }<br>const hat = new Product(&quot;red hat&quot;, 1000);<br>hat.displayInfo();</pre><h3>Next steps</h3><p>The JavaScript coding practices discussed above can help you write cleaner and better-structured code that’s easier to maintain and debug. However, creating development code is just the first step of the software life cycle.</p><p>Even if you’re diligently following these JavaScript best practices, errors can (and will) still occur when your end-users interact with your application. To ensure your users experience your code as intended, you need to detect and address errors in production. With <a href="https://raygun.com/for/javascript-error-monitoring">JavaScript error tracking</a>, you can take care of errors on the production side, monitoring your application in real-time, catching errors as they happen, and taking immediate action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cca3d4174f5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring software quality with integration testing]]></title>
            <link>https://medium.com/@raygunio/ensuring-software-quality-with-integration-testing-8417bbde21e5?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8417bbde21e5</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 02:39:45 GMT</pubDate>
            <atom:updated>2024-02-29T02:39:45.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpy_l0tq8Zsu_J3D0-gFCw.jpeg" /></figure><p><strong>By Deacon McIntyre</strong></p><p>Before <a href="https://raygun.com/blog/public-api-launch/">the Raygun API limited release last year</a>, we’d been consistently receiving requests for a public API for a long time, to provide a way for our customers to access their Raygun data programmatically. We’re now proud to say we’re providing a public API with <a href="https://raygun.com/documentation/product-guides/raygun-api/#endpoints">a range of endpoints</a>, but it took us a lot of planning and development to get here!</p><p>In this post, I’d like to take you back to the beginning of development on our big API project. Specifically, I want to walk through the pivotal decisions we made around testing when we started development on the project, and how (and why) these have paid off.</p><h3>A question of testing</h3><p>We had planned the project, laid the groundwork, and were starting to get into development. Early on, we had to ask ourselves: how do we ensure that our various software components work seamlessly together to deliver the desired functionality? And how could we create an environment where we could quickly and confidently introduce new changes? We already had some unit tests, but it seemed like they might not be enough to satisfy our software quality goals. This led us to consider integration tests.</p><p>Before I get into the details, let’s clarify the distinction between integration tests and unit tests.</p><h3>Unit tests vs integration tests</h3><p><a href="https://raygun.com/blog/javascript-unit-testing-frameworks/">Unit testing</a> focuses on verifying that individual units or components of software are working as expected. A “unit” is typically the smallest part of any software that can be tested, such as a method or a function. By testing each little piece on its own, we can be more confident that the software works well overall. These tests are isolated, meaning external dependencies (like databases or external services) are generally mocked or stubbed out.</p><p>For example, we might have an IUserService class which normally makes an API or database request to fetch information about a user. We don’t want our unit tests to rely on a real API or database for a number of reasons (speed, isolation, consistency, control over test scenarios, etc), so we can do something like this:</p><pre>public void GetUserName_ReturnsCorrectName()<br>{<br>    // Arrange<br>    var mockUserService = new Mock&lt;IUserService&gt;();<br>    var testUserId = 1;<br>    var testUserName = &quot;Alice&quot;;<br><br>    // Setup the mock to return a fake user for a specific ID<br>    mockUserService.Setup(s =&gt; s.GetUserById(testUserId))<br>      .Returns(new User { Id = testUserId, Name = testUserName });<br>    var userProcessor = new UserProcessor(mockUserService.Object);<br>    // Act<br>    var userName = userProcessor.GetUserName(testUserId);<br>    // Assert<br>    Assert.Equal(testUserName, userName);<br>    // Verify that GetUserById was called with the correct ID<br>    mockUserService.Verify(s =&gt; s.GetUserById(testUserId), Times.Once());<br>}</pre><p><a href="https://en.wikipedia.org/wiki/Integration_testing">Integration testing</a>, on the other hand, is about ensuring that the units or components of software work well when integrated together. It aims to expose the problems that might occur when different units interact with each other. Integration tests often deal with real instances of external dependencies rather than their mocked or stubbed versions–this helps to make the tests realistic, to better catch issues that could happen in production. To illustrate this more clearly, we’ll look at an example of integration testing shortly!</p><h3>Are integration tests worth the cost?</h3><p>It’s <a href="https://www.testquality.com/blog/tpost/limrj90n51-failing-at-integration-testing-common-mi">well known that integration tests</a> are usually not trivial to set up, with a number of potential costs creating a barrier to entry. When deciding whether it was worth it for us to implement integration tests alongside our existing unit tests, we had to consider the following:</p><ul><li>Integration tests often require configuring testing infrastructure alongside your tests (e.g., on a build server), which can take time and lead to brittle tests if the infrastructure ever has issues. This can also make it difficult to run the integration tests in a local development environment.</li><li>Integration tests usually require more effort to write vs. a unit test, because of the need to ensure each test scenario is set up properly. Compounding this across hundreds of tests can really add up on development time.</li><li>Integration tests almost always take longer to execute than unit tests, leading to long CI/CD cycles, wasting developers’ time.</li></ul><p>In the end we decided that in our case, the benefits outweighed the costs. We knew that for an API, testing the HTTP and database edges of the application was critical, and unit tests would not be enough to provide confidence in that regard. We also had the advantage of a relatively simple interface–testing did not need to simulate user interactions on a GUI, we could simply send HTTP requests to trigger our tests. And by automating the tests, we would save significant time by reducing the need for manual testing, and adding a “safety net” for any issues we might not find during manual testing. Over the long run, that time saved should more than make up for the time spent implementing the tests.</p><p>We also had a secret weapon that eliminated many of the costs, reducing both the infrastructure setup overhead and the test execution time! With this powerful asset, the decision to implement integration tests became obvious.</p><p>What might it be? Let me introduce you to…</p><h3>The WebApplicationFactory</h3><p>The WebApplicationFactory is a class provided by .NET’s Microsoft.AspNetCore.Mvc.Testing package, described in <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1">their documentation</a> as a “Factory for bootstrapping an application in memory for functional end to end tests.” While the description mentions end-to-end tests, the value of running an application in-memory applies to integration tests as well.</p><p>As I indicated above, the benefits of this in-memory execution are twofold:</p><ul><li>We can lower the infrastructure overhead and speed up the tests by replacing external services with in-memory equivalents.</li><li>As you’ll see below, we do this for all external services except for the database because we believed it was important to test using a real database.</li><li>We can reduce the test duration further by relying on the WebApplicationFactory to simulate network requests in-memory, making them both faster and more reliable.</li></ul><h3>Show me some examples!</h3><p>Ok, here’s a simplified overview of how we did it, starting with our custom “WebApplicationFactory” class:</p><pre>public class CustomWebApplicationFactory&lt;TProgram&gt; : WebApplicationFactory&lt;TProgram&gt; where TProgram : class<br>{<br>    private const string TestingDatabaseConnectionString = &quot;testing database connection string&quot;; protected override void ConfigureWebHost(IWebHostBuilder builder)<br>    {<br>        builder.ConfigureTestServices(services =&gt;<br>        {<br>            services.AddAuthentication(&quot;test&quot;)<br>                    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthenticationHandler&gt;(&quot;test&quot;, _ =&gt; { });<br>            services.Replace(ServiceDescriptor.Singleton&lt;DbContext&gt;(_ =&gt; new DbContext<br>            {<br>                ConnectionString = TestingDatabaseConnectionString,<br>                // other config settings<br>            }));<br>            services.Replace(ServiceDescriptor.Singleton&lt;IDistributedCache, MemoryDistributedCache&gt;());<br>            services.AddInMemoryRateLimiting();<br>            services.Replace(ServiceDescriptor.Singleton&lt;IPublisher, FakePublisher&gt;()<br>        });<br>        builder.UseEnvironment(&quot;Development&quot;);<br>    }<br>}</pre><p>As you can see, it’s not very complicated. The ConfigureWebHost method is where we set up all the things that we want the integration tests to do differently to a production run of the application.</p><p>First, we configure a test authentication-handler that allows us to control the authentication status in the tests. Most of the time, we use it to return an authenticated user, but it can also return an unauthenticated user in order to test the behavior of unauthenticated requests. Our authentication system has its own tests so replacing it with a test handler here streamlines these tests significantly.</p><p>Then we replace the code that interfaces with our database (called “DbContext” here) with code that is identical except for the database connection string. This allows our tests to interact with a database in the same way they would in production, without modifying any of our production data. Further down, we’ve employed in-memory substitutes or “fakes”, but we believed it paramount for our integration tests to interact with an actual database. This was our primary external dependency, echoing the real-world scenario our API operates under. It ensured our tests validated interactions with the database correctly, mimicking the actual production environment.</p><p>To ensure our tests run quickly and to avoid the need to set up any external dependencies other than the test database, we opted to utilize in-memory versions of certain services. For those that didn’t offer such options, we built fakes. You can see these configured at the end of the ConfigureWebHost method. The FakePublisher simply stashes messages in an internal dictionary instead of publishing to an external queue. This makes it easier to verify whether or not messages have been published in our tests - we can simply inspect the FakePublisher’s dictionary.</p><h3>Usage</h3><p>Our integration-test classes all make use of a base class that sets up an HttpClient using the CustomWebApplicationFactory. This is a real HttpClient, not a mock, and we use it just like we might use one to make requests in a real application. That’s important because the value of the integration tests lies in them being as close as possible to production. The more the tests deviate from the real-world scenario, the less likely they are to be able to catch a potential real-world issue!</p><p>Inside the WebApplicationFactory, the HttpClient is configured to use a <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.testhost.testserver">TestServer</a> to execute the requests in-memory. So while it is a real HttpClient, it doesn’t have the overhead of performing actual network requests, resulting in the best of both worlds for integration testing.</p><pre>protected CustomWebApplicationFactory&lt;Program&gt; Factory;<br>protected HttpClient Client;<br>protected DbContext DbContext; <br><br>[OneTimeSetUp]<br>public void OneTimeSetUp()<br>{<br>    Factory = new CustomWebApplicationFactory&lt;Program&gt;();<br>}<br>[SetUp]<br>public void SetUpBase()<br>{<br>    Client = Factory.CreateClient();<br>    var dbContextFactory = Factory.Services.GetRequiredService&lt;IDbContextFactory&gt;();<br>    DbContext = dbContextFactoryFactory.CreateDbContext();<br>}</pre><p>hese methods initialize the fields that we’ll need for all of our tests: the HttpClient to make requests, the DbContext to update or read the database, and the Factory to retrieve any services we might need to inspect during the tests.</p><p>An integration test that makes use of all of these fields might look something like this:</p><pre>[Test]<br>public async Task ResolveErrorGroup_ErrorGroupIsActive_PublishesEvent()<br>{<br>    SetUpErrorGroup(DbContext);<br><br>await Client.PostAsync($&quot;applications/{1}/error-groups/{2}/resolve&quot;, null);<br>    var publisher = (Factory.Services.GetRequiredService&lt;IPublisher&gt;() as FakePublisher)!;<br>    var messages = publisher.PublishedMessages;<br>    Assert.That(messages[typeof(ResolvedMessage)], Has.Count.EqualTo(1));<br>}</pre><p>In this test:</p><ul><li>For clarity in the example I’ve condensed it into a “SetUpErrorGroup” method, but the first step is to configure the database to the state we need it for the test, using the DbContext from the base class.</li><li>Then we make a request using the Client that was created in the SetUpBase method earlier. This is where the in-memory request goes to our API, which is also running in-memory!</li><li>Lastly, we use the Factory to get our fake publisher and assert that the message was published as expected. In other tests we might save the response from the request and assert based on that instead.</li></ul><h3>Lessons Learned</h3><p>Now that it’s been a few months since development started, we’re able to look back and identify a few points that made the integration tests really shine for us:</p><ol><li>We ran all of our tests (both unit and integration) on every build of our CI server, and they can be run in under 2 minutes on a development machine. This means that the tests are constantly being run, consistently reinforcing our confidence as the code evolves. This helped us release new features more quickly, as we could be sure that new features were not causing any regressions.</li><li>For some unit tests, we found that once all the external services were mocked, the remainder of the code had very little logic to actually unit test. This highlighted the importance of the integration tests; since much of the API’s functionality hinges on interactions with external services, we found that testing against actual databases and HTTP clients rather than relying on mocks was essential.</li><li>While the integration tests have been useful for testing external services, one benefit that I didn’t anticipate was that the integration tests have also been great for testing complex behaviors <em>within</em> the application. For example, middleware operations or message/handler systems that are loosely coupled from the rest of the application might be difficult to unit test when isolated. However, because we’re simulating an actual request, the test will traverse through every layer within the application just as it would in a live environment.</li></ol><h3>Summing up</h3><p>In this post, we’ve covered some background on the development of Raygun’s public API, along with our decisions around testing and the differences between unit and integration tests. I’ve also let you in on the powerful secret weapon that is the WebApplicationFactory, which you’ll hopefully make good use of!</p><p>One of the most important factors in our success with this approach was that we didn’t treat integration tests as an afterthought. We started early and included tests with every feature we added, so we’ve accumulated a good number of them now. Having a large test suite has been really important to build confidence, because if developers feel the tests can’t reliably detect issues introduced by their changes, the tests lose their value.</p><p>I hope this account of our integration testing lessons has been insightful. You can follow along with the <a href="https://api.raygun.io/v3/swagger/index.html?__hstc=159254181.d0b565021ed1e7212ddb2981d2803d8e.1706582272922.1709171086933.1709173808737.45&amp;__hssc=159254181.2.1709173808737&amp;__hsfp=3101213850">progress of the Raygun API here!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8417bbde21e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Toolbox 2024 Part 3: Bundlers and test frameworks]]></title>
            <link>https://medium.com/@raygunio/js-toolbox-2024-part-3-bundlers-and-test-frameworks-c60f55f26920?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c60f55f26920</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 22:33:09 GMT</pubDate>
            <atom:updated>2024-02-13T22:33:09.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXn6cOGvSbJuQlN9X9stSQ.jpeg" /></figure><p><em>JavaScript is bigger than ever, and the ecosystem is nothing short of overwhelming. In this JS toolbox 2024 series, we’ve selected and analyzed the most noteworthy JS tools, so that you don’t have to.</em></p><p><strong>By Ollie Bannister</strong></p><p>In <a href="https://raygun.com/blog/js-toolbox-part-1/">part 1 of this series</a>, we explored the foundations of any JavaScript project: Runtime environments and package management. In <a href="https://raygun.com/blog/js-toolbox-part-2">part 2, we focused on JavaScript frameworks and static site generators</a>. Now, in part 3, we turn our attention to the tools that refine and optimize the development process: Bundlers and test frameworks.</p><h4>In this post:</h4><p><strong>Bundlers</strong></p><ul><li>Webpack</li><li>EsBuild</li><li>Vite</li><li>Parcel 2</li></ul><p><strong>Test frameworks</strong></p><ul><li>MochaJS</li><li>Jest</li><li>Jasmine</li><li>Puppeteer</li><li>Selenium</li><li>Playwright</li></ul><p><strong>What to choose?</strong></p><h3>Bundlers</h3><p>In modern web development, bundlers play a pivotal role in getting your project production-ready. They are essential tools for combining multiple files and assets into streamlined, optimized bundles, effectively managing complex dependencies, and enhancing application performance.</p><p>This section delves into the world of bundlers, focusing on popular tools such as <a href="https://github.com/Webpack/Webpack">webpack</a>, <a href="https://github.com/evanw/esbuild">esbuild</a>, <a href="https://github.com/vitejs/vite">vite</a>, and <a href="https://github.com/parcel-bundler/parcel">parcel 2</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xfdtJpfwH8CQ8s3p.png" /></figure><p><a href="https://star-history.com/#Webpack/Webpack&amp;evanw/esbuild&amp;vitejs/vite&amp;parcel-bundler/parcel&amp;Date"><em>An overview</em></a><em> of bundler popularity trends.</em></p><p>In 2023, Webpack has maintained its position as the most popular project bundler, but Vite is rapidly gaining ground and could soon challenge for the top spot. Meanwhile, Parcel and esbuild have also experienced steady growth, making the project bundler category even more competitive.</p><h3>Webpack</h3><p><a href="https://github.com/Webpack/Webpack">Webpack</a> is a powerful and widely-used module bundler for JavaScript applications. It’s known for its flexibility and extensive plugin system, making it a popular tool in complex web development projects.</p><p>It also benefits from being a long-standing player in the JavaScript ecosystem. Over the years, Webpack has adapted to the evolving demands of web development, establishing itself as a reliable and robust tool.</p><h4>Advantages</h4><ul><li><strong>Extensive customization</strong>: Webpack offers a highly configurable environment, allowing developers to tailor the bundling process to their specific needs through a vast array of plugins and loaders.</li><li><strong>Strong community and ecosystem</strong>: With a large community backing it, Webpack benefits from a rich ecosystem of plugins, extensive documentation, and community support.</li><li><strong>Optimized bundle handling</strong>: It excels in handling various assets and dependencies, offering features like code splitting and lazy loading to optimize application performance.</li></ul><h4>Disadvantages</h4><ul><li><strong>Steep learning curve</strong>: The complexity and vastness of Webpack’s configuration options can be overwhelming for beginners or simpler projects.</li><li><strong>Configuration overhead</strong>: Setting up and maintaining a Webpack configuration can become cumbersome, especially in larger projects with more specific requirements.</li></ul><h3>EsBuild</h3><p><a href="https://github.com/evanw/esbuild">EsBuild</a> is a relatively new, blazing-fast JavaScript bundler and minifier. It stands out for its high performance, significantly speeding up the build process in development pipelines.</p><h4>Advantages</h4><ul><li><strong>Exceptional speed</strong>: EsBuild is known for its incredibly fast build times, often orders of magnitude quicker than traditional bundlers, which greatly enhances developer productivity.</li><li><strong>Simplicity and ease of use</strong>: With a straightforward setup and minimal configuration, EsBuild is accessible and easy to integrate into development workflows.</li><li><strong>Efficient bundling and minification</strong>: It efficiently handles the tasks of bundling and minification, reducing the size of output files and improving application load times.</li></ul><h4>Disadvantages</h4><ul><li><strong>Limited plugin ecosystem</strong>: Being newer in the market, EsBuild has a smaller range of plugins and integrations compared to more established bundlers like Webpack.</li><li><strong>Less feature-rich</strong>: While its simplicity is a strength, EsBuild may lack some of the advanced features and customizability found in other, more mature bundling tools.</li></ul><h3>Vite</h3><p><a href="https://github.com/vitejs/vite">Vite</a> is a modern front-end build tool that significantly improves the development experience with its fast cold server start and hot module replacement. It leverages native ES modules and is optimized for speed and efficiency.</p><h4>Advantages</h4><ul><li><strong>Rapid development cycle</strong>: Vite offers a fast server start and quick updates with its hot module replacement, streamlining the development process.</li><li><strong>Optimized for modern browsers</strong>: Utilizing native ES modules, Vite is designed for modern browsers, reducing the need for extensive transpiling and bundling.</li><li><strong>Ease of use</strong>: With sensible defaults and minimal configuration, Vite simplifies setup and usage, making it accessible for new developers and efficient for experienced ones.</li></ul><h4>Disadvantages</h4><ul><li><strong>Dependency on modern browser features</strong>: Vite’s reliance on native ES modules means it may not be the best fit for projects needing to support older browsers.</li><li><strong>Growing ecosystem</strong>: While rapidly evolving, Vite’s ecosystem and range of plugins are still in the growth phase and may not yet match the breadth of more established tools like Webpack.</li></ul><h3>Parcel 2</h3><p><a href="https://github.com/parcel-bundler/parcel">Parcel 2</a> emphasizes a zero-configuration approach to bundling web applications. It’s a powerful tool that offers a hassle-free developer experience, focusing on simplicity and speed.</p><h3>Advantages</h3><ul><li><strong>Zero configuration required</strong>: Parcel 2 stands out for its no-config setup, allowing developers to get started quickly without the need for intricate configuration.</li><li><strong>Fast build times</strong>: It offers rapid build and rebuild times, enhancing productivity and streamlining the development process.</li><li><strong>Out-of-the-box features</strong>: Parcel 2 comes with many built-in features like code splitting, module replacement, and support for various languages and file types.</li></ul><h3>Disadvantages</h3><ul><li><strong>Less granular control</strong>: The zero-configuration approach, while convenient, can limit developers who need more control over the bundling process.</li><li><strong>Smaller community</strong>: Compared to tools like Webpack, Parcel 2 has a smaller community, which might mean fewer resources and plugins available to developers.</li></ul><h3>Test frameworks</h3><p>Test frameworks are crucial for ensuring the quality and reliability of JavaScript applications, particularly through comprehensive code coverage. These frameworks provide the structured environment needed for writing, executing, and managing tests, playing a pivotal role in validating code functionality and detecting bugs. As JavaScript is adopted in both front-end and back-end project stacks, the robustness of testing frameworks becomes more important, helping developers maintain high standards of code integrity and application performance.</p><p>This section will introduce you to a variety of JavaScript test frameworks, each with unique attributes tailored to different testing requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-zuRwGSAx7I5G4Xu.png" /></figure><p><a href="https://star-history.com/#mochajs/mocha&amp;jasmine/jasmine&amp;jestjs/jest&amp;puppeteer/puppeteer&amp;SeleniumHQ/selenium&amp;microsoft/playwright&amp;Date"><em>An overview</em></a><em> of Framework popularity trends.</em></p><p>Over the past year, the JavaScript testing framework landscape has remained relatively solid. No major disruptor technologies have proven to challenge <a href="https://github.com/puppeteer/puppeteer">Puppeteer</a> for the top spot, although the rapid growth of <a href="https://github.com/microsoft/playwright">Playwright</a> gives us something to keep our eyes on through 2024.</p><p>These technologies aren’t directly comparable however due to the varying niches that they fill. In this section, I will cover each technology to give you the context to help you make the right decision when choosing the testing framework for your project.</p><h3>MochaJS</h3><p><a href="https://github.com/mochajs/mocha">MochaJS</a> is a feature-rich JavaScript test framework running on Node.js, making it a popular choice for both backend and frontend testing. It’s known for its flexibility and straightforward syntax, allowing for asynchronous testing and the use of any assertion library.</p><p><strong>Example test case syntax:</strong></p><pre>describe(&#39;Array&#39;, function() {<br>  describe(&#39;#indexOf()&#39;, function() {<br>    it(&#39;should return -1 when the value is not present&#39;, function() {<br>      assert.equal([1, 2, 3].indexOf(4), -1);<br>    });<br>  });<br>});</pre><h4>Advantages</h4><ul><li><strong>Flexibility and compatibility</strong>: MochaJS is highly flexible, allowing developers to choose their preferred assertion libraries, mock/spy libraries, and more.</li><li><strong>Rich feature set</strong>: It offers a wide range of features like asynchronous testing, test coverage reports, and hooks for setting up conditions before running tests.</li><li><strong>Good documentation and community support</strong>: MochaJS has comprehensive documentation and strong community support, making it easier for new users to get started and find solutions to common problems.</li></ul><h4>Disadvantages</h4><ul><li><strong>Global variables</strong>: Mocha exposes global variables, which can be an issue for developers preferring a more modular approach.</li><li><strong>Slower than some rivals</strong>: While Mocha is versatile, it can be slow compared to some newer testing frameworks, particularly in large test suites.</li></ul><h3>Jest</h3><p><a href="https://github.com/jestjs/jest">Jest</a>, created and maintained by Facebook, is a JavaScript testing framework with a focus on simplicity. It is often recognized for its zero-configuration setup and seamless integration, especially with React applications, making it a favored choice for developers in both small-scale projects and large enterprise applications.</p><p><strong>Example test case syntax:</strong></p><pre>test(&#39;adds 1 + 2 to equal 3&#39;, () =&gt; {<br>  expect(1 + 2).toBe(3);<br>});</pre><h4>Advantages</h4><ul><li><strong>Zero-configuration</strong>: Jest is designed for out-of-the-box usability with minimal setup, offering a smooth testing experience right from the start.</li><li><strong>Built-in mocking and assertions</strong>: It comes with powerful mocking capabilities and a rich set of assertion APIs, eliminating the need for additional libraries.</li><li><strong>Snapshot testing and coverage</strong>: Jest provides snapshot testing, which is great for catching unexpected changes, and built-in coverage reports to keep track of your test suite’s effectiveness.</li></ul><h4>Disadvantages</h4><ul><li><strong>Performance in large projects</strong>: While generally fast, Jest can exhibit slower test execution times in very large projects or complex test suites.</li><li><strong>Configuration complexity in advanced scenarios</strong>: Despite its zero-config appeal, advanced use cases might require navigating through more complex configurations and setups.</li></ul><h3>Jasmine</h3><p><a href="https://github.com/jasmine/jasmine">Jasmine</a> is a behavior-driven development framework for testing JavaScript code. It’s known for its clean, straightforward syntax and does not rely on any other JavaScript frameworks or a Document Object Model (DOM). Jasmine is often praised for its simplicity and ease of use in both frontend and backend testing environments.</p><p><strong>Example test case syntax:</strong></p><pre>describe(&quot;A suite&quot;, function() {<br>  it(&quot;contains spec with an expectation&quot;, function() {<br>    expect(true).toBe(true);<br>  });<br>});</pre><h4>Advantages</h4><ul><li><strong>Clean, readable syntax</strong>: Jasmine’s syntax is designed to be easy to read and write, making it accessible for developers of all skill levels.</li><li><strong>Independent of other technologies</strong>: It doesn’t depend on any external software or browser DOM, making it suitable for testing any JavaScript application.</li><li><strong>Out-of-the-box functionality</strong>: Jasmine comes with everything you need for testing your JavaScript code, including test doubles and asynchronous testing support.</li></ul><h4>Disadvantages</h4><ul><li><strong>Limited mocking capabilities</strong>: Jasmine’s mocking capabilities, while present, are not as extensive or straightforward as some other testing frameworks.</li><li><strong>Slower performance with large test suites</strong>: In scenarios involving large test suites, Jasmine can sometimes be slower compared to other modern testing frameworks.</li></ul><h3>Puppeteer</h3><p><a href="https://github.com/puppeteer/puppeteer">Puppeteer</a> is a Node library that provides a high-level API to control headless Chrome or Chromium. It’s primarily used for browser automation, making it a powerful tool for end-to-end testing of web applications, taking screenshots, and generating pre-rendered content from web pages.</p><p><strong>Example test case syntax:</strong></p><pre>const puppeteer = require(&#39;puppeteer&#39;);<br><br>(async () =&gt; {<br>  const browser = await puppeteer.launch();<br>  const page = await browser.newPage();<br>  await page.goto(&#39;https://example.com&#39;);<br>  // other actions...<br>  await browser.close();<br>})();</pre><h4>Advantages</h4><ul><li><strong>Browser Automation</strong>: Puppeteer excels in automating and testing browser environments, offering precise control over Chrome or Chromium.</li><li><strong>Rich Feature Set for Testing</strong>: It supports a wide array of testing needs, from capturing screenshots and generating PDFs to testing modern web applications.</li><li><strong>High-Level API</strong>: Puppeteer’s API abstracts away complexities, making it relatively easy to write scripts for browser-based testing.</li></ul><h4>Disadvantages</h4><ul><li><strong>Limited browser support</strong>: Puppeteer primarily works with Chrome and Chromium, which might not be suitable for cross-browser testing needs.</li><li><strong>Higher resource usage</strong>: Being a full browser automation tool, it can be more resource-intensive compared to some lightweight testing frameworks, potentially leading to slower performance in resource-constrained environments.</li></ul><h3>Selenium</h3><p><a href="https://github.com/SeleniumHQ/selenium">Selenium</a> is an extensively used open-source automation framework for web applications. It allows for cross-browser testing by automating browser actions, making it a staple tool for end-to-end testing in diverse web development environments.</p><p><strong>Example test case syntax:</strong></p><pre>WebDriver driver = new ChromeDriver();<br>driver.get(&quot;http://www.example.com&quot;);<br>WebElement element = driver.findElement(By.name(&quot;q&quot;));<br>element.sendKeys(&quot;Hello Selenium WebDriver!&quot;);<br>element.submit();</pre><h4>Advantages</h4><ul><li><strong>Cross-browser compatibility</strong>: Selenium supports testing across a wide range of browsers, including Chrome, Firefox, Safari, and Internet Explorer, making it ideal for cross-browser testing.</li><li><strong>Support for multiple programming languages</strong>: It offers the flexibility to write tests in several programming languages, such as Java, Python, C#, and JavaScript.</li><li><strong>Strong community and ecosystem</strong>: Being one of the oldest and most established testing frameworks, Selenium has a large community, extensive resources, and integration support.</li></ul><h4>Disadvantages</h4><ul><li><strong>Complex setup and learning curve</strong>: Setting up Selenium can be complex, and it requires a fair amount of learning, particularly for those new to testing automation.</li><li><strong>Performance issues</strong>: Selenium tests can sometimes be slower compared to some modern testing frameworks, especially when running complex test suites or tests across multiple browsers.</li></ul><h4>Playwright</h4><p><a href="https://github.com/microsoft/playwright">Playwright</a> is a relatively new but powerful node library for browser automation. Developed by Microsoft, it enables cross-browser web automation that is ever-reliable for end-to-end testing. Playwright is compatible with all modern web browsers, including Chrome, Firefox, and Safari, and offers capabilities for both headless and non-headless browser testing.</p><p><strong>Example test case syntax:</strong></p><pre>const { chromium } = require(&#39;playwright&#39;);<br><br>(async () =&gt; {<br>  const browser = await chromium.launch();<br>  const page = await browser.newPage();<br>  await page.goto(&#39;https://example.com&#39;);<br>  // other actions...<br>  await browser.close();<br>})();</pre><h4>Advantages</h4><ul><li><strong>Cross-browser support</strong>: Playwright supports automated testing across multiple browsers and platforms, enhancing its utility in diverse development scenarios.</li><li><strong>Modern and robust API</strong>: It offers a modern, feature-rich API that allows for advanced browser automation, including support for single-page applications.</li><li><strong>Fast and reliable</strong>: Playwright tests are generally faster and more reliable than those performed with older tools, offering improved stability and performance.</li></ul><h4>Disadvantages</h4><ul><li><strong>Relatively new in the market</strong>: As a newer tool, Playwright is still building its community and ecosystem, which can currently lack the extensiveness of more established frameworks.</li><li><strong>Learning curve</strong>: While its API is user-friendly, there is still a learning curve, especially for developers new to browser automation and end-to-end testing.</li></ul><h3>What to choose?</h3><p>Choosing the right tools for your JavaScript project, is a crucial decision that can significantly impact your development workflow and the quality of your final product. Each tool comes with its own set of strengths and drawbacks.</p><p>For bundlers, the decision might hinge on factors like ease of configuration, build speed, and ecosystem support. In test frameworks, the decision could depend on the nature of your testing needs, ranging from unit and integration testing to end-to-end browser automation.</p><p>Your choice should align with the specific needs of your project, the skill set of your team, and the nature of your development environment. It’s about finding the right tool that not only addresses your current requirements but also adapts to the evolving demands of your project. A comprehensive understanding of each tool’s capabilities and limitations is key to making an informed decision that enhances both your development process and the overall quality of your JavaScript applications. Remember, the right set of tools can empower your development team, streamline your processes, and lead to the creation of a robust, efficient, and maintainable codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c60f55f26920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Toolbox 2024 Part 2: Frameworks and static site generators]]></title>
            <link>https://medium.com/@raygunio/js-toolbox-2024-part-2-frameworks-and-static-site-generators-4c3e95f5f98b?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3e95f5f98b</guid>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[static-site-generator]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 21:53:13 GMT</pubDate>
            <atom:updated>2024-02-13T21:53:13.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8OU4yFcP73977XW6QYKqA.jpeg" /></figure><p><em>In 2024, JavaScript is bigger than ever. The ecosystem is just as huge, and almost impossible to keep track of, so I’ve had a go at picking out 2024’s most essential JS tools for you.</em></p><p><strong>By Ollie Bannister</strong></p><p>In part 1 of this series, we <a href="https://raygun.com/blog/js-toolbox-part-1/">reviewed runtimes and package managers,</a> the foundational building blocks of your software project. So in part 2, we’re analyzing the tools which form the walls and roof that give your software project its structure: frameworks and static site generators.</p><p>For this installment of JS Toolbox 2024, we explore various frameworks &amp; generators available in the JavaScript &amp; TypeScript ecosystem, analyzing their strengths, weaknesses, and ideal use cases.</p><p><em>You can also check out </em><a href="https://raygun.com/blog/js-toolbox-part-1/"><em>Part 3, covering bundlers and test frameworks, here</em></a><em>.</em></p><h4>In this post:</h4><p><strong>Frameworks</strong></p><ul><li>React</li><li>Vue</li><li>Angular</li><li>Svelte</li></ul><p><strong>Static Site/Server side Generators</strong></p><ul><li>Astro</li><li>Nuxt</li><li>Hugo</li><li>Gatsby</li><li>Jekyll</li></ul><p><strong>What to choose?</strong></p><h3>Frameworks</h3><p><a href="https://raygun.com/blog/popular-javascript-frameworks/">JavaScript frameworks</a> are an essential part of modern web development, providing tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so understanding the current state of frameworks is crucial for projects old and new.</p><p>In this section, we look at some of the most prominent JavaScript frameworks that shaped web development in 2023 and speculate on what 2024 will have in store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n5A2bcj26zrrzCLf.png" /></figure><p><a href="https://star-history.com/#facebook/react&amp;vuejs/vue&amp;angular/angular&amp;sveltejs/svelte&amp;Date"><em>An overview</em></a><em> of framework popularity trends.</em></p><p>In 2023, <a href="https://github.com/facebook/react">React</a> and <a href="https://github.com/vuejs/vue">Vue.js</a> have continued to lead the pack. We’ve seen some consistent growth from both <a href="https://github.com/angular/angular">Angular</a> and <a href="https://github.com/sveltejs/svelte">Svelte</a>; however, given Svelte’s trajectory I can see the gap closing on its competitors in 2024. Let’s get into what’s good and not-so-good about these leading frameworks.</p><h3>React</h3><p>Developed by Facebook, <a href="https://github.com/facebook/react">React</a> rapidly gained popularity as a framework for developing dynamic user interfaces for high-traffic web pages. Known for its efficiency, React utilizes a virtual DOM, which simplifies integration with various applications. This approach enables fast and smooth user experience, making it a favored choice for modern web development.</p><p>React components are typically written using JSX, which allows you to write HTML-like syntax in your JavaScript.</p><pre>import React from &#39;react&#39;;<br><br>function Greeting({ name }) {<br>  return &lt;h1&gt;Hello, {name}!&lt;/h1&gt;;<br>}<br><br>export default Greeting;</pre><h4>Advantages</h4><ul><li><strong>Component-based architecture</strong>: React’s design is centered around reusable components, allowing developers to build encapsulated components that manage their own state. This architecture makes it easier to manage and maintain large applications, as well as to reuse code, leading to more <a href="https://raygun.com/blog/javascript-best-practices/">efficient development processes</a>.</li><li>(<a href="https://raygun.com/blog/react-debugging-guide/">Related: Get a complete guide to React debugging here</a>)</li><li><strong>Virtual DOM for enhanced performance</strong>: React employs a virtual DOM (Document Object Model) that optimizes rendering and improves application performance. This means React can update changes in an application’s UI quickly and efficiently, leading to a smoother and more responsive user experience, especially for complex applications with dynamic content.</li><li><strong>Strong community and ecosystem</strong>: React has a large and active community, backed by Facebook’s support. This vast ecosystem provides a wealth of resources, including libraries, tools, and third-party extensions. The strong community support also ensures regular updates, a wealth of learning resources, and a wide range of solutions for various development challenges.</li></ul><h4>Disadvantages</h4><ul><li><strong>Steep learning curve for beginners</strong>: Despite its popularity, React can be challenging for beginners to grasp. Its component-based architecture, JSX syntax, and overall ecosystem can be overwhelming initially. Newcomers to React often need time to become comfortable with concepts like <a href="https://react.dev/learn/managing-state">state management</a>, lifecycle methods, and the <a href="https://www.w3schools.com/react/react_props.asp">use of props</a>.</li><li><strong>Rapid pace of development</strong>: The fast evolution of React and its ecosystem can be a double-edged sword. While regular updates introduce new features and improvements, they also mean developers need to continuously adapt and learn. This rapid change can lead to challenges in keeping projects up-to-date and may require frequent refactoring or rewriting of existing code to align with the latest best practices.</li></ul><h3>Vue</h3><p><a href="https://github.com/vuejs/vue">Vue.js</a>, often simply referred to as Vue, has established itself as a highly adaptable and progressive JavaScript framework, primarily used for building user interfaces and <a href="https://raygun.com/blog/spa-performance/">single-page applications</a>. Its gentle learning curve and incrementally adoptable architecture have made it a popular choice among developers, particularly for its ease of integration into existing projects.</p><p>Vue components are often structured with a template, script, and style section. This example uses the Vue 3 Composition API:</p><pre>&lt;template&gt;<br>  &lt;h1&gt;Hello, {{ name }}!&lt;/h1&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { ref } from &#39;vue&#39;;<br><br>export default {<br>  setup() {<br>    const name = ref(&#39;Vue User&#39;);<br>    return { name };<br>  }<br>};<br>&lt;/script&gt;<br><br>&lt;style&gt;<br>h1 {<br>  color: blue;<br>}<br>&lt;/style&gt;</pre><h4>Advantages</h4><ul><li><strong>Intuitive and easy to learn</strong>: Vue’s straightforward and <a href="https://vuejs.org/guide/introduction.html">clear documentation</a> makes it accessible, especially for those new to JavaScript frameworks. Its template syntax and use of plain JavaScript make it easier to get started and become productive quickly.</li><li><strong>Reactive and composable</strong>: Vue’s core feature is its reactivity system, which ensures efficient updates and rendering. The framework’s focus on component composition allows for building complex interfaces while keeping the codebase organized and maintainable.</li><li><strong>Versatile ecosystem</strong>: Vue offers a rich ecosystem with solutions like <a href="https://vuex.vuejs.org/">Vuex</a> for state management and Vue Router for routing, providing developers with a comprehensive toolkit for modern web development. The framework is also compatible with a variety of other libraries and tools, making it versatile for different project needs.</li></ul><h4>Disadvantages</h4><ul><li><strong>Less market share and community size</strong>: Compared to giants like React, Vue has a smaller community and market share. While growing, this can sometimes mean fewer resources, third-party libraries, and extensions than more widely adopted frameworks.</li><li><strong>Risk of over-flexibility</strong>: Vue’s flexibility, while a strength, can also be a drawback. The freedom in structuring applications can lead to inconsistencies in large projects or among different developers, potentially affecting maintainability and scalability.</li></ul><h3>Angular</h3><p><a href="https://github.com/angular/angular">Angular</a>, maintained by Google, is a robust and feature-rich framework designed for building scalable and sophisticated single-page applications. It’s widely recognized for its ability to create efficient, large-scale enterprise-grade web applications, offering a comprehensive solution with a powerful suite of tools.</p><p>Angular components combine a TypeScript class with an HTML template, typically decorated with metadata.</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-greeting&#39;,<br>  template: `&lt;h1&gt;Hello, {{ name }}!&lt;/h1&gt;`,<br>  styleUrls: [&#39;./greeting.component.css&#39;]<br>})<br><br>export class GreetingComponent {<br>  name = &#39;Angular User&#39;;<br>}</pre><h4>Advantages</h4><ul><li><strong>Full-fledged framework</strong>: Angular is a complete framework that includes everything needed for front-end development, from a powerful templating engine to integrated state management, making it a one-stop solution for complex applications.</li><li><strong>Advanced dependency injection</strong>: <a href="https://blog.angular-university.io/angular-dependency-injection/">Angular’s advanced dependency injection</a> system is a key feature that facilitates greater efficiency in building and managing applications. It simplifies the process of supplying components with the data and services they need, leading to more modular, flexible, and easily testable code.</li><li><strong>Consistent code structure</strong>: Angular enforces a consistent code structure and best practices through its opinionated nature. This uniformity is advantageous for team collaboration and when scaling up the application.</li></ul><h4>Disadvantages</h4><ul><li><strong>Steep learning curve</strong>: Angular’s extensive set of features and functionalities, while powerful, often presents a challenging learning curve, particularly for beginners or those accustomed to more straightforward frameworks.</li><li><strong>Performance overhead</strong>: While powerful, Angular’s complexity can lead to performance overhead in smaller projects. The framework is better suited for larger applications where the full feature set can be effectively utilized.</li></ul><h3>Svelte</h3><p><a href="https://github.com/sveltejs/svelte">Svelte</a> is an innovative component-based framework that shifts much of the work to compile time, offering a unique approach to building interactive web interfaces. Unlike traditional frameworks that apply updates to the DOM in response to state changes, Svelte compiles applications to highly efficient vanilla JavaScript at build time, resulting in faster and more responsive applications.</p><p>Svelte components are written with HTML, JavaScript, and CSS in a single file, with reactive state updates.</p><pre>&lt;script&gt;<br>  let name = &#39;Svelte User&#39;;<br>&lt;/script&gt;<br><br>&lt;h1&gt;Hello, {name}!&lt;/h1&gt;<br><br>&lt;style&gt;<br>  h1 {<br>    color: green;<br>  }<br>&lt;/style&gt;</pre><h4>Advantages</h4><ul><li><strong>Compile-time innovation</strong>: Svelte’s unique compile-time approach leads to less boilerplate code and higher performance, as it generates optimized JavaScript code that directly updates the DOM.</li><li><strong>Ease of learning and use</strong>: With a syntax closer to vanilla JavaScript and HTML, Svelte is straightforward to learn, particularly for those with basic JavaScript knowledge. This simplicity also makes it easier to start building applications quickly.</li><li><strong>Minimal runtime overhead</strong>: Svelte applications do not carry the weight of a framework’s runtime, resulting in smaller bundle sizes and faster load times, which is particularly advantageous for performance-sensitive applications.</li></ul><h4>Disadvantages</h4><ul><li><strong>Smaller community and ecosystem</strong>: Svelte’s community, while active and growing, is smaller than those of more established frameworks like React or Angular. This can mean fewer resources, libraries, and community support compared to its larger counterparts.</li><li><strong>Less mainstream adoption</strong>: Being relatively new and different, Svelte has not seen as widespread adoption in the industry as some other frameworks. This might pose challenges in finding experienced developers or integrating with certain existing technologies and tools.</li></ul><h3>Static site/Server-side generators</h3><p><a href="https://en.wikipedia.org/wiki/Static_site_generator">Static site generators</a> have become a cornerstone of modern web development, offering a streamlined approach to building fast and secure websites. These tools pre-render pages at build time, creating static HTML files which results in blazing-fast load times and improved performance. With the growing need for speed, <a href="https://raygun.com/blog/js-security-vulnerabilities-best-practices/">security</a>, and scalability in web development, static site generators are increasingly becoming a popular choice for both developers and businesses.</p><p>In this section, we explore some of the leading static site generators that defined the 2023 web development landscape, and the ones we should keep on the radar for 2024.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SpBtAwTEQSGeYJnF.png" /></figure><p><a href="https://star-history.com/#withastro/astro&amp;nuxt/nuxt&amp;gohugoio/hugo&amp;gatsbyjs/gatsby&amp;Jekyll/Jekyll&amp;Date"><em>An overview</em></a><em> of Framework popularity trends.</em></p><p>It’s been an exciting year in the static site/server-side generation landscape, most notably for <a href="https://github.com/withastro/astro">Astro</a>, a relatively new contender that is taking the sector by storm. <a href="https://github.com/gohugoio/hugo">Hugo</a> has maintained its lead, sitting over 15k stars ahead of <a href="https://github.com/gatsbyjs/gatsby">Gatsby</a>. <a href="https://github.com/nuxt/nuxt">Nuxt’s</a> steady growth has enabled it to win popularity over <a href="https://github.com/Jekyll/Jekyll">Jekyll</a>.</p><p>The popularity of these static site generators in 2023 sets the stage for further growth and innovation in 2024, as developers continue to prioritize speed, security, and scalability in web development on the server.</p><h3>Astro</h3><p><a href="https://github.com/withastro/astro">Astro</a> is a modern static site generator that allows developers to build fast, content-focused websites using a component-based architecture. It stands out for its ability to deliver lightning-fast performance by only sending essential JavaScript, leveraging partial hydration.</p><h4>Advantages</h4><ul><li><strong>Optimized performance</strong>: Astro optimizes loading performance by serving mostly static HTML and hydrating components with JavaScript only as needed, making sites faster and more efficient.</li><li><strong>Flexible component architecture</strong>: It supports various frontend frameworks within the same project, allowing developers to use the best tool for each specific component.</li><li><strong>Enhanced developer experience</strong>: Astro offers a streamlined developer experience with intuitive syntax, fast build times, and a focus on delivering high-quality content.</li></ul><h4>Disadvantages</h4><ul><li><strong>Relatively new in the market</strong>: Being a newer entrant in the static site generator ecosystem, Astro might not have as extensive a community or as many resources as more established tools.</li><li><strong>Limited plugins and integrations</strong>: As it is still growing, Astro’s ecosystem of plugins and integrations may be less developed compared to other static site generators, potentially limiting its out-of-the-box capabilities.</li></ul><h3>Nuxt</h3><p><a href="https://github.com/nuxt/nuxt">Nuxt.js</a> is a powerful Vue.js framework that simplifies the development of universal or single-page Vue apps. Known for its versatility, Nuxt provides a streamlined development experience with its convention-over-configuration approach, offering a robust platform for both static site generation and server-side rendering.</p><h4>Advantages</h4><ul><li><strong>Automatic code splitting</strong>: Nuxt.js automatically splits code into manageable bundles, improving load times and performance, especially for complex applications with many components.</li><li><strong>Easy to use with Vue.js</strong>: Leveraging Vue.js, Nuxt offers an enjoyable development experience with a familiar, component-based architecture and an intuitive setup, ideal for both newcomers and experienced Vue developers.</li><li><strong>Server-side rendering and static site generation</strong>: Nuxt’s flexibility allows developers to choose between generating a static site or using server-side rendering, making it adaptable to various project requirements.</li></ul><h4>Disadvantages</h4><ul><li><strong>Learning curve for non-Vue developers</strong>: While Nuxt simplifies Vue.js development, those unfamiliar with Vue might face a learning curve in understanding its ecosystem and architecture.</li><li><strong>Overhead for simple projects</strong>: For smaller, less complex projects, the extensive features and structure of Nuxt.js could introduce unnecessary overhead, making simpler static site generators a more efficient choice.</li></ul><h3>Hugo</h3><p><a href="https://github.com/gohugoio/hugo">Hugo</a> is a fast and flexible static site generator, <a href="https://css-tricks.com/comparing-static-site-generator-build-times/">renowned for its incredible speed</a> in building static websites and blogs. It stands out for its efficiency and ease of use, making it a popular choice for developers looking to quickly deploy high-performance sites.</p><h4>Advantages</h4><ul><li><strong>Exceptional build speed</strong>: Hugo’s most notable feature is its blazing-fast build time, efficiently handling even large sites with thousands of pages.</li><li><strong>Ease of use and setup</strong>: Hugo is simple to set up and operate, with a straightforward structure that’s easy to understand, making it accessible for both beginners and experienced developers.</li><li><strong>Robust content management</strong>: It offers robust content organization, with a strong emphasis on content management that allows for a high degree of customization and flexibility in content presentation.</li></ul><h4>Disadvantages</h4><ul><li><strong>Limited plugin ecosystem</strong>: Compared to other static site generators, Hugo has a more limited range of plugins and themes, which might restrict some customization options.</li><li><strong>Steep learning curve for advanced usage</strong>: While basic usage of Hugo is straightforward, leveraging its more advanced features requires a steeper learning curve, particularly for those not familiar with GoLang, the language in which Hugo is written.</li></ul><h3>Gatsby</h3><p><a href="https://github.com/gatsbyjs/gatsby">Gatsby</a> is a modern static site generator based on React, known for creating fast and optimized web applications. It integrates seamlessly with various data sources, making it a popular choice for building complex, data-driven sites with rich interactive features.</p><h4>Advantages</h4><ul><li><strong>Performance optimization</strong>: Gatsby automatically optimizes site performance, implementing best practices like code splitting and lazy loading images, leading to fast-loading, efficient websites.</li><li><strong>Rich data integration</strong>: Thanks to its powerful data layer, Gatsby can pull data from multiple sources (CMSs, APIs, databases, etc.), allowing for flexible and dynamic site generation.</li><li><strong>Robust plugin ecosystem</strong>: Gatsby boasts a large collection of plugins, enabling developers to easily add functionality and integrate with various tools and services.</li></ul><h4>Disadvantages</h4><ul><li><strong>Complexity for beginners</strong>: Due to its reliance on React and <a href="https://graphql.org/">GraphQL</a>, Gatsby can be complex for beginners or for those unfamiliar with these technologies.</li><li><strong>Build times</strong>: For very large sites, Gatsby’s build times can be longer than some other static site generators, which might impact development and deployment efficiency.</li></ul><h3>Jekyll</h3><p><a href="https://github.com/Jekyll/Jekyll">Jekyll</a> is one of the earliest and most established static site generators, widely used for creating simple, blog-aware websites. Built in Ruby, it integrates seamlessly with GitHub Pages, making it a preferred choice for personal, project, or documentation sites.</p><h4>Advantages</h4><ul><li><strong>Simple and easy to use</strong>: Jekyll’s straightforward setup and minimalistic approach make it ideal for beginners or for projects that require simple static sites without the need for complex features.</li><li><strong>Strong integration with GitHub Pages</strong>: Jekyll offers seamless integration with <a href="https://pages.github.com/">GitHub Pages</a>, providing an easy pathway to deploy and host websites directly from GitHub repositories.</li><li><strong>Rich theme ecosystem</strong>: It has a robust ecosystem of themes, allowing for quick and easy customization of websites without extensive development.</li></ul><h4>Disadvantages</h4><ul><li><strong>Limited to simple use cases</strong>: Jekyll is less suited for complex applications as it lacks the advanced features and flexibility offered by newer static site generators.</li><li><strong>Ruby dependency</strong>: The need to have Ruby installed can be a barrier for those not familiar with the Ruby environment, potentially limiting its accessibility to a wider audience.</li></ul><h3>What to choose?</h3><p>Each tool, with its unique features and drawbacks, caters to different requirements and preferences. Understanding these is crucial in making an informed decision that aligns with the specific needs and goals of your project.</p><p>Whether it’s the blazing-fast builds of Hugo, the robust data integration of Gatsby, the simplicity of Jekyll, the React-based architecture of Gatsby, or the sheer efficiency of Astro and Nuxt, each offers distinct advantages that are pivotal for certain types of projects. However, it’s equally important to weigh these against their potential drawbacks, whether it’s complexity, build times, ecosystem limitations, or specific technology dependencies.</p><p>In the end, the choice depends on a balance of factors: the complexity of your project, the scalability you need, your team’s familiarity with the underlying technologies, and the specific features you require. By carefully assessing each tool’s capabilities and how they match your project’s requirements, you can choose a tool that not only meets your current needs but also supports the future growth and evolution of your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c3e95f5f98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS Toolbox 2024 Part 1: Runtime environments & package management]]></title>
            <link>https://medium.com/@raygunio/js-toolbox-2024-part-1-runtime-environments-package-management-7c4d74a63e4c?source=rss-3e912712f84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c4d74a63e4c</guid>
            <category><![CDATA[runtime]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[package-management]]></category>
            <dc:creator><![CDATA[Raygun]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 21:39:54 GMT</pubDate>
            <atom:updated>2024-02-13T21:41:48.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtiyrjdQND3npEGFUqNo6g.jpeg" /></figure><p><em>JavaScript is bigger than ever, and the ecosystem is nothing short of overwhelming. In this JS toolbox 2024 series, we’ve selected and analyzed the most noteworthy JS tools, so that you don’t have to.</em></p><p><strong>By Ollie Bannister</strong></p><p>Just as any durable structure needs a solid foundation, <a href="https://raygun.com/blog/javascript-best-practices/">successful JavaScript projects</a> rely heavily on starting with the right tools.</p><p>This post, the first in our JS Toolbox 2024 series, explores the core pillars of the JavaScript &amp; TypeScript ecosystem: Runtime environments, package management, and development servers.</p><p><em>See </em><a href="https://raygun.com/blog/js-toolbox-part-2"><em>part two, covering frameworks and static site generators, here</em></a><em>.</em></p><p><strong>In this post:</strong></p><ol><li><strong>Runtime environments</strong></li></ol><ul><li>Node.js</li><li>Deno</li><li>Bun</li></ul><p><strong>2. Comparing JS runtimes</strong></p><ul><li>Installation</li><li>Performance, stability, and security</li><li>Community</li></ul><p><strong>3. Package managers</strong></p><ul><li>NPM</li><li>Yarn</li><li>pnpM</li><li>Bun</li></ul><p><strong>What to choose</strong></p><h3>Runtime environments</h3><p>In JavaScript development, runtimes are the engines that drive advanced, server-centric projects beyond the limitations of a user’s browser. This independence is pivotal in modern web development, allowing for more sophisticated and versatile applications. The JavaScript runtime market is more dynamic than ever, with several contenders competing for the top spot. <a href="https://nodejs.org/en/">Node.js</a>, the long-established leader in this space, now faces formidable competition from <a href="https://deno.com/">Deno</a> and <a href="https://bun.sh/">Bun</a>.</p><p>Deno is the brainchild of Ryan Dahl, the original creator of Node.js. It represents a significant step forward in runtime technology, emphasizing security through fine-grained access controls and modern capabilities like native TypeScript support.</p><p>Bun has burst onto the scene, releasing version 1.0 in September 2023. Bun sets itself apart with exceptional speed, challenging the performance standards established by its predecessors. Bun’s rapid execution capabilities, enabled by <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation">just-in-time (JIT) execution</a>, make it a powerful alternative in the runtime environment space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7vDmccGdlcWgqdQx.png" /></figure><p><a href="https://star-history.com/#nodejs/node&amp;denoland/deno&amp;oven-sh/bun&amp;Date"><em>An overview</em></a><em> of framework popularity trends.</em></p><p>The popularity of Node.js has continued to grow over 2023, and I anticipate this will continue into 2024. There has been a slight downtrend in growth trajectory, which I’d guess is due to the other tooling growing in market share.</p><p>Deno has seen substantial growth over 2023. If the current trend continues I anticipate Deno to overtake Node.js in popularity in 2024, though it’s worth mentioning that star-based popularity doesn’t reflect usage in the field. Without a doubt, Node.js will retain its position as the lead environment for production systems throughout 2024.</p><p>Bun has seen the largest growth in this category over the past year. I anticipate that Bun will find a steady foothold and continue its ascent, following the <a href="https://bun.sh/blog/bun-v1.0">release of version 1.0</a>. It’s early days for this new player, but comparing early stage growth to others in the category, it’s shaping up to be a high performer.</p><h3>Node.js</h3><p><a href="https://nodejs.org/en/">Node.js</a>, acclaimed as the<a href="https://survey.stackoverflow.co/2023/#section-most-popular-technologies-web-frameworks-and-technologies"> leading web technology</a> by StackOverflow developers, has been a significant player in the web development world since its inception in 2009. It revolutionized web development by enabling JavaScript for server-side scripting, thus allowing for the creation of complex, backend-driven applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5MANIzqC1nhjnFXI.jpg" /></figure><h4>Advantages</h4><ul><li><strong>Asynchronous and event-driven</strong>: Node.js operates on an asynchronous, event-driven architecture, making it efficient for scalable network applications. This model allows Node.js to handle multiple operations concurrently without blocking the main thread.</li><li><strong>Rich ecosystem</strong>: With a diverse and extensive range of<a href="https://github.com/topics/nodejs"> tools, resources, and libraries</a> available, Node.js offers developers an incredibly rich ecosystem, supporting a wide array of development needs.</li><li><strong>Optimized for performance</strong>: Node.js is known for its low-latency handling of HTTP requests, which is optimal for web frameworks. It efficiently utilizes system resources, allowing for load balancing and the use of multiple cores through child processes and its cluster module.</li></ul><h4>Disadvantages</h4><ul><li><strong>Learning curve for asynchronous programming</strong>: The non-blocking, asynchronous nature of Node.js can be challenging for developers accustomed to linear programming paradigms, leading to a steep learning curve.</li><li><strong>Callback hell</strong>: While manageable, Node.js can lead to complex nested callbacks — often referred to as “callback hell” — which can make code difficult to read and maintain. However, this can be mitigated with modern features like async/await.</li></ul><h3>Deno</h3><p><a href="https://deno.com/">Deno</a> represents a step forward in JavaScript and TypeScript runtimes, leveraging<a href="https://v8.dev/"> Google’s V8 engine</a> and built in Rust for enhanced security and performance. Conceived by Ryan Dahl, the original creator of Node.js, Deno is positioned as a more secure and modern alternative, addressing some of the core issues found in Node.js, particularly around security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bna-oEawc70BD1Ex.png" /></figure><h4>Advantages</h4><ul><li><strong>Enhanced security</strong>: Deno’s secure-by-default approach requires explicit permissions for file, network, and environment access, reducing the risks associated with an all-access runtime.</li><li><strong>Native TypeScript support</strong>: It offers first-class support for TypeScript and TSX, allowing developers to use TypeScript out of the box without additional transpiling steps.</li><li><strong>Single executable compilation</strong>: Deno can compile entire applications into a single, self-contained executable, simplifying deployment and distribution processes.</li></ul><h4>Disadvantages</h4><ul><li><strong>Young ecosystem</strong>: Being relatively new compared to Node.js, Deno’s ecosystem is still growing, which may temporarily limit the availability of third-party modules and tools.</li><li><strong>Adoption barrier</strong>: For teams and projects deeply integrated with Node.js, transitioning to Deno can represent a significant change, posing challenges in terms of adoption and migration.</li></ul><h3>Bun</h3><p><a href="https://bun.sh/">Bun</a> emerges as a promising new contender in the JavaScript runtime space, positioning itself as a faster and more efficient alternative to Node.js. Developed using<a href="https://ziglang.org/"> Zig</a> and powered by<a href="https://developer.apple.com/documentation/javascriptcore"> JavaScriptCore</a>, Bun is designed to deliver significantly quicker startup times and lower memory usage, making it an attractive option for modern web development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*3JG4xDFbt8XQLdR8.png" /></figure><p>Currently, Bun provides a <em>limited, experimental</em> native build for Windows with full support for Linux and macOS. Hopefully, over 2024 we see full support for Windows released.</p><h4>Advantages</h4><ul><li><strong>High performance</strong>: Bun’s main draw is its performance, offering faster execution and lower resource usage compared to traditional runtimes, making it particularly suitable for high-efficiency requirements.</li><li><strong>Integrated development tools</strong>: It comes with an integrated suite of tools, including a test runner, script runner, and a Node.js-compatible package manager, all optimized for speed and compatibility with Node.js projects.</li><li><strong>Evolving ecosystem</strong>: Bun is continuously evolving, with a focus on enhancing Node.js compatibility and broadening its integration with various frameworks, signaling its potential as a versatile and adaptable solution for diverse development needs.</li></ul><h4>Disadvantages</h4><ul><li><strong>Relative newness in the market</strong>: As a newer player, Bun’s ecosystem is not as mature as Node.js, which might pose limitations in terms of available libraries and community support.</li><li><strong>Compatibility challenges</strong>: While efforts are being made to improve compatibility with Node.js, there may still be challenges and growing pains in integrating Bun into existing Node.js-based projects or workflows.</li></ul><h3>Comparing JavaScript runtimes</h3><h4>Installation</h4><p>Each JavaScript runtime has its unique installation process. Here’s a brief overview of how to install Node.js, Deno, and Bun:</p><p><strong>Node.js</strong></p><ol><li><strong>Download</strong>: Visit the<a href="https://nodejs.org/en/"> Node.js website</a> and download the installer suitable for your operating system.</li><li><strong>Run installer</strong>: Execute the downloaded file and follow the installation prompts. This process will install both Node.js and npm.</li><li><strong>Verify installation</strong>: Open a terminal or command prompt and type node -v and npm -v to check the installed versions of Node.js and npm, respectively.</li></ol><p>Managing different versions of Node.js has historically been a challenge for developers. To address this issue, tools like<a href="https://github.com/nvm-sh/nvm"> NVM (Node Version Manager)</a> and<a href="https://github.com/coreybutler/nvm-windows"> NVM Windows</a> have been developed, greatly simplifying the process of installing and switching between various Node.js versions.</p><p><strong>Deno</strong></p><ol><li><strong>Shell Command</strong>: You can install Deno using a simple shell command.</li></ol><ul><li>Windows: irm https://deno.land/install.ps1 | iex</li><li>Linux/macOS: curl -fsSL https://deno.land/x/install/install.sh | sh `</li></ul><ol><li><strong>Alternative methods</strong>: Other methods like downloading a binary from the <a href="https://github.com/denoland/deno/releases">Deno releases page</a> are also available.</li><li><strong>Verify installation</strong>: To ensure Deno is installed correctly, type <strong>deno --version</strong> in your terminal.</li></ol><p><strong>Bun</strong></p><ol><li><strong>Shell Command</strong>: Similar to Deno, Bun can be installed using a shell command. For instance, on macOS, Linux, and WSL use the command curl https://bun.sh/install | bash.</li><li><strong>Alternative methods</strong>: For detailed instructions or alternative methods, check the <a href="https://bun.sh/">Bun installation guide</a>.</li><li><strong>Verify installation</strong>: After installation, run bun --version in your terminal to verify that Bun is correctly installed.</li></ol><h4>Performance, stability and security</h4><p>In evaluating JavaScript runtimes, performance, stability, and <a href="https://raygun.com/blog/js-security-vulnerabilities-best-practices/">security</a> are the key factors to consider. Mayank Choubey’s benchmark studies provide insightful comparisons among Node.js, Deno, and Bun:</p><ul><li><a href="https://medium.com/deno-the-complete-reference/node-js-vs-deno-vs-bun-express-hello-world-server-benchmarking-7bf44c197d2b">Node.js vs Deno vs Bun: Express hello world server benchmarking</a></li><li><a href="https://medium.com/deno-the-complete-reference/node-js-vs-deno-vs-bun-native-http-hello-world-server-benchmarking-f48edd514513">Node.js vs Deno vs Bun: Native HTTP hello world server benchmarking</a></li></ul><p>I’d recommend giving the post a read if you’re interested in the specifics. Otherwise, I’ll do my best to summarize the results below.</p><p><strong>Node.js</strong></p><ul><li>Historically, Node.js has been known for its efficient handling of asynchronous operations and has set a standard in server-side JavaScript performance.</li><li>In the benchmark, Node.js displayed solid performance, reflective of its maturity and optimization over the years. However, it didn’t lead the pack in terms of raw speed.</li><li>As Node.js has been around for a long time and has proven its reliability, it takes out the category of <strong>stability</strong>.</li></ul><p><strong>Deno</strong></p><ul><li>Deno, being a relatively newer runtime, has shown promising improvements in performance, particularly in the context of security and TypeScript support.</li><li>The benchmark results for Deno were competitive, showcasing its capability to handle server requests efficiently, though it still trails slightly behind in raw processing speed compared to Bun.</li><li>Given its emphasis on security features like explicit permissions for file, network, and environment access, Deno excels in the category of <strong>security</strong>.</li></ul><p><strong>Bun</strong></p><ul><li>Bun made a significant impression with its performance in this benchmark. It leverages Zig and JavaScriptCore, which contributes to its faster startup times and lower memory usage.</li><li>In the “Hello World” server test, Bun outperformed both Node.js and Deno in terms of request handling speed, showcasing its potential as a high-performance JavaScript runtime.</li><li>With its significant speed improvements, Bun leads in the category of <strong>performance</strong>.</li></ul><p>These results suggest that while Node.js remains a reliable and robust choice for many applications, Deno and Bun are catching up, offering competitive and sometimes superior performance metrics.</p><p>Bun, in particular, demonstrates remarkable speed, which could be a game-changer for performance-critical applications. However, it’s important to consider other factors such as stability, community support, and feature completeness when choosing a runtime for your project.</p><h3>Community</h3><p>The community surrounding a JavaScript runtime is vital for its growth and evolution. It shapes development, provides support, and drives innovation. Let’s briefly examine the community dynamics for Node.js, Deno, and Bun:</p><p><strong>Node.js</strong>: Node.js has one of the largest, most diverse communities in software development, enriched by a wide array of libraries, tools, and resources. Its community actively contributes to its core and modules, bolstered by global events and forums for learning and networking.</p><p><strong>Deno</strong>: Deno’s community is rapidly growing, drawing developers with its modern and security-centric features. It’s characterized by active involvement in the runtime’s development and a strong online presence, particularly on platforms like <a href="https://github.com/denoland/deno">GitHub</a> and Discord.</p><p><strong>Bun</strong>: Although newer, Bun’s community is dynamic and quickly expanding. Early adopters are actively engaged in its development and performance enhancement, with lively discussions and feedback exchanges on online platforms.</p><p>Each of these communities, from Node.js’s well-established network to the emerging groups around Deno and Bun, plays a crucial role in the adoption and development of these runtimes. For developers, understanding the nuances of these communities can be key to leveraging the full potential of a chosen runtime.</p><h3>Package managers</h3><p>If you’ve ever worked on the front end of a modern web application or if you’re a full-stack node engineer, you’ve likely used a package manager at some point. The package manager is responsible for managing the dependencies of your project, such as libraries, frameworks, and utilities.</p><p><a href="https://www.npmjs.com/">NPM</a> is the default package manager that comes pre-installed with Node.js. Yarn and PNPM compete to take NPM’s spot as the package management tool of choice for developers working in the JavaScript ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h83UYdGNa3vmcDFc.png" /></figure><p><a href="https://star-history.com/#npm/npm&amp;yarnpkg/yarn&amp;pnpm/pnpm&amp;oven-sh/bun&amp;Date"><em>An overview</em></a><em> of Framework popularity trends.</em></p><h4>NPM</h4><p><a href="https://www.npmjs.com/">Node Package Manager</a> or NPM for short, is the default and most dominant package manager for JavaScript projects. It comes pre-installed with Node.js, providing developers with immediate access to the npm registry, allowing them to install, share, and manage package dependencies right from the start of their project.</p><p>It was created in 2009 by Isaac Schlueter as a way to share and reuse code for Node.js projects. Since then, it has grown to become a huge repository of packages that can be used for both front-end and back-end development.</p><p>NPM consists of two main components:</p><ol><li><strong>NPM CLI (Command Line Interface)</strong>: This tool is used by developers to install, update, and manage packages (libraries or modules) in their JavaScript projects. It interacts with npm’s online repository, allowing developers to add external packages to their projects easily.</li><li><strong>NPM registry</strong>: An extensive online database of public and private JavaScript packages, the npm Registry is where developers can publish their packages, making them accessible to the wider JavaScript community. It’s known for its vast collection of libraries, frameworks, and tools, contributing to the versatility and functionality of JavaScript projects.</li></ol><p>This star graph doesn’t capture much in terms of the overall popularity of NPM CLI given that this tool comes pre-installed with Node.js. Knowing this, it’s worth also reviewing the <a href="https://npmtrends.com/npm-vs-pnpm-vs-yarn">overall download count of these packages</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VAT7xiPo6LqKJWU9.png" /></figure><p><em>NPM currently has 56,205,118,637 weekly downloads.</em></p><p>Woah, 56.2B! It’s safe to say NPM isn’t going anywhere. From the graphs we can see the steady incline in the overall popularity of this tool through 2023. I predict this growth will continue through 2024.</p><h3>Yarn</h3><p><a href="https://yarnpkg.com/">Yarn</a> is a well-established open-source package manager created in 2016 by Facebook, Google, Exponent, and Tilde. It was designed to address some of the issues and limitations of NPM, such as speed, correctness, security, and developer experience.</p><p>To improve these areas, Yarn incorporates a range of innovative features. These include workspaces for managing multiple packages within a single repository, offline caching for faster installs, parallel installations for improved speed, a hardened mode for enhanced security, and interactive commands for a more intuitive user interface. These features collectively contribute to Yarn’s robustness and efficiency.</p><p>It features a command-line interface that closely resembles NPM’s, but with several enhancements and differences. It utilizes the same package.json file as NPM for defining project dependencies. Additionally, Yarn introduces the yarn.lock file, which precisely locks down the versions of dependencies, ensuring consistent installs across environments. Like NPM, Yarn also creates a node_modules folder where it installs and organizes the packages for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lFtYzNTLel4F7AJ2.png" /></figure><p><em>Yarn currently has 4,396,069 weekly downloads.</em></p><p>Given that Yarn and pnpM require manual installs this does mean the download counts are un-comparable with NPM but it still gives us a glance at the overall trends.</p><p>In 2023, Yarn appears to have lost some of it’s growth trajectory but still remains the most popular alternative to NPM for package management.</p><h3>pnpM</h3><p><a href="https://github.com/pnpm/pnpm">Performant NPM or pnpM</a> for short, is another alternative package manager for JavaScript that was created in 2016 by Zoltan Kochan. It was designed to be faster, lighter, and more secure than both NPM and Yarn.</p><p>It excels in saving disk space and speeding up the installation process. Unlike npm, where each project stores separate copies of dependencies, pnpm stores them in a content-addressable store. This approach means if multiple projects use the same dependency, they share a single stored copy, significantly reducing disk usage. When updating dependencies, pnpm only adds changed files instead of duplicating the entire package.</p><p>The installation process in pnpm is streamlined into three stages: resolving dependencies, calculating the directory structure, and linking dependencies, making it faster than traditional methods. pnpm also creates a unique node_modules directory using symlinks for direct dependencies only, avoiding unnecessary access to indirect dependencies. This approach ensures a cleaner dependency structure, while still offering a traditional flat structure option through its <strong>node-linker</strong> setting for those who prefer it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PdNnJxYzrtITmw0D.png" /></figure><p><em>pnpM currently has 8,016,757 weekly downloads.</em></p><p>pnpM’s popularity surged in 2023, and I foresee this upward trend extending into 2024, as an increasing number of developers recognize its resource efficiency and streamlined project setup.</p><h3>Bun</h3><p>As Bun comes with an npm-compatible package manager, I felt it was worth mentioning here.</p><p>I’ve <a href="https://raygun.com/blog/js-toolbox-part-1/#bun">covered Bun in the Runtime Environments section above</a>.</p><h3>What to choose?</h3><p>Choosing the right tool for your project in 2024 depends on a variety of factors including your project’s specific requirements, your team’s familiarity with the technology, and the particular strengths of each tool. In the dynamic world of JavaScript development, having a clear understanding of these factors is crucial for making an informed decision.</p><p>For those prioritizing stability and a proven track record, Node.js remains a top recommendation. It’s well-established, supported by a vast ecosystem, and continues to be a reliable choice for a wide range of applications. Node.js’s maturity makes it a safe bet, especially for projects where long-term viability and extensive community support are essential.</p><p>On the other hand, if you’re inclined towards experimenting with the latest advancements in the field and are operating in a Linux-based environment, Bun presents an exciting opportunity. It stands out for its impressive performance and is ideal for those looking to leverage the bleeding edge of JavaScript runtime technology. Bun’s rapid execution capabilities make it a compelling option for performance-driven projects.</p><p>When it comes to package management, pnpm is an excellent choice. Its efficient handling of dependencies and disk space makes it ideal for developers managing multiple projects or large dependencies. With its growing popularity and focus on performance, pnpM is well-suited for modern JavaScript development.</p><p>JavaScript tools in 2024 offer a massive range catered to different needs and preferences. Whether you opt for the stability of Node.js, the cutting-edge performance of Bun, or the efficient dependency management of pnpM, each tool brings unique strengths to the table. Carefully consider your project’s requirements and team’s expertise to make the best choice for your development journey in 2024.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c4d74a63e4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>