ProgrammingPro #66: Calculate Directory Sizes with Go, PHP 8.4's New Features, and Swift 6's Embedded Swift
Bite-sized actionable content, practical tutorials, and resources for programmers.
Welcome to this week’s edition of ProgrammingPro!
In today’s Expert Insight, we bring you an excerpt from the recently published book,
System Programming Essentials with Go, which details how to calculate directory sizes using Go.
News Highlights: PHP 8.4 to introduce HTML 5 DOM parsing and new array functions in November; Swift 6 launches Embedded Swift for low-level programming; and Spring ecosystem releases milestone updates for Spring Boot, Framework, and Security.
My top 5 picks from today’s learning resources:
Use Guardrails To Prevent Hallucinations in Generative AI Applications🛡️
Learn JavaScript Reactivity - How to Build Signals from Scratch⚛️
Scaling Challenges - Productivity, Cost Efficiency, and Microservice Management📈
Netflix Saves Time and Money with Server-Driven Notifications💬
But there’s more, so dive right in.
Stay Awesome!
Divya Anne Selvaraj
Editor-in-Chief
PS: This week is your last chance to participate in this month’s survey! Do take the oppotunity to give us your feedback on ProgrammingPro, request specific learning resources, and get your one Packt Credit for the month.
🗞️News and Analysis🔎
Lessons learned from CrowdStrike outages on releasing software updates: Experts suggest monitoring updates by region, enabling quick rollbacks, and other strategies. Read to learn about best practices in software update deployment.
PHP 8.4 is coming in November with HTML 5 extension, new array functions, and more: This version introduces HTML 5 DOM parsing and better handling of large XML documents. Read to learn about all key improvements.
Swift 6 Introduces Embedded Swift for Low-level Programming: This compilation mode enables low-level programming without runtime distribution. Read to learn how it allows for programming embedded systems with Swift.
Spring Ecosystem Delivers Numerous Milestone Releases: These releases include updates for Spring Boot, Spring Framework, Spring Security, and others. Read to understand the specific improvements and new capabilities introduced.
React community splitting into full-stack and client-only camps, suggests survey: According to the State of React survey, only some developers are adopting advanced features. Read to gain insights into current trends within the community.
Executives have more confidence in software supply chain security than their developers: 92% of executives trust their malware detection, but only 70% of developers agree. Read to understand the need for improved communication.
How to maintain code for a century - Just add Rust: This article focuses on the reinvention of GNU coreutils in Rust. Read to learn why open-source software will endure while proprietary software may disappear if its company does.
🎓Tutorials and Learning Resources💡
Python
🎓Tutorial | Use Guardrails To Prevent Hallucinations in Generative AI Applications: Discusses the implementation of “Contextual Grounding Checks" to prevent hallucinations. Read to learn how to enhance the reliability of gen AI apps.
Beyond Hypermodern - Python is easy now: Introduces Rye, a new tool for Python project management that integrates best practices from other languages like Go and Rust. Read to learn how to set up a Python project with Rye.
C# and .NET
Scan HTML even faster with SIMD instructions (C++ and C#): Discusses the implementation of SIMD instructions in major web engines like WebKit/Safari and Chromium/Chrome. Read to learn how SIMD instructions optimize HTML parsing.
🎓Tutorial | How to use a Blazor QuickGrid with GraphQL: Provides a guide to displaying data in a Blazor application, using the StarTrek GraphQL API. Read to learn how to optimize performance and manage large datasets dynamically.
🎓Tutorial | Add AI to Your .NET Apps Easily with Prompty: Introduces Prompty, a Visual Studio Code extension that facilitates the integration of LLMs like GPT-4o into .NET applications. Read to learn how to use the Prompty extension.
C and C++
🎓Tutorial | Modern C++ Design Patterns: Offers structured solutions to common software design problems across three categories: Creational, Structural, and Behavioral. Read to learn how to apply various C++ design patterns.
🎓Tutorial | Calling Go Functions from C++: Explores the process of compiling a Go file into a c-archive using Go's build tools and then linking this archive with C++ code. Read to learn how to bridge two powerful programming languages.
🎓Tutorial | Tail recursion for macros in C: Discusses the potential and challenges of introducing tail recursion for macros in C, particularly with the adoption of the __VA_OPT__. Read to learn about the new syntactic possibilities.
Java
🎓Tutorial | Deciding and iterating with Java statements: Explores control structures in Java programming. Read to learn how to effectively manage program flow and employ conditional and looping constructs.
❓Quiz | How well do you know miscellaneous Java language semantics?: Includes 25 questions to test your Java knowledge. The current average score stands at 11. Think you can beat it?
🎓Tutorial | Implementing the Strategy Design pattern in Spring Boot: Discusses implementing the Strategy Design Pattern in Spring Boot to manage file parsing. Read to learn how to use the pattern to manage various file types.
JavaScript and TypeScript
📖Open Access Book | Exploring JavaScript (ES2024 Edition) by Dr. Axel Rauschmayer: a comprehensive guide for newcomers to JavaScript, emphasizing modern features and test-driven exercises. Read to gain practical skills.
🎓Tutorial | Learn JavaScript Reactivity - How to Build Signals from Scratch: Explains the concept of reactivity in JavaScript and how to implement signals to manage state changes. Read to learn how to build something similar to SolidJS.
🎓Tutorial | The Best Way to Create Singleton Design Pattern in JavaScript and TypeScript: Details the pattern’s benefits for resource management, global state control, simplified code structure, and thread safety. Read to learn how to implement it.
Go
Go 1.23 - Interactive release notes: Key updates include seamless range iterations using for-range loops and a new iter package defining iterator types like Seq and Seq2. Read to learn how to utilize the new iterator features.
Web UI Testing With Go: Details the author's transition from using JavaScript-based UI browser testing tools like Playwright for their startup to employing Go. Read to learn how the shift offered a streamlined, efficient testing strategy.
Rust
Investing in Rust: Details a study showing significant bug reduction in memory-safe implementations versus traditional unsafe languages like C/C++. Read to understand how adopting Rust can significantly enhance code safety and more.
🎓Tutorial | Named Arguments In Rust, If You Want Them: Discusses how to implement named arguments in Rust using a builder pattern and macros to simplify object creation. Read to learn about the benefits and drawbacks of using macros.
Swift
🎓Tutorial | Async await in Swift - The Full Toolkit: Serves as an extensive guide to Swift Concurrency, exploring various components such as async/await. Read to gain a comprehensive understanding of Swift's concurrency tools.
A Conversation With Swift 6 About Data Race Safety: Engages in a fictional dialogue to explore the migration process to Swift 6's stricter concurrency and data race safety features. Read to learn how to migrate code safely and efficiently.
PHP
🎓Tutorial | A guide to Laravel's model events: Introduces a powerful feature that automatically triggers logic associated with specific actions on Eloquent models. Read to learn efficient ways to handle automatic data-related tasks.
SQL
💼Case Study | Why Pinterest adopted a Distributed SQL database that ended up replacing HBase: Details migration from HBase to TiDB, driven by the need for a more capable and scalable storage solution. Read to learn about the benefits.
Ruby
What's Coming in Ruby on Rails 7.2 - Database Features in Active Record: The new version also introduces enhanced support for composite primary keys (CPKs). Read to learn about all the new features.
🌟Best Practices and Advice🚀
Software testing’s chaotic conundrum - Navigating the Three-Body Problem of speed, quality, and cost: Underscores the trade-offs and potential consequences of prioritizing one over the others, and proposes effective management strategies.
💼Case Study | Scaling Challenges - Productivity, Cost Efficiency, and Microservice Management: Delves into Trainline's strategic and technical responses to scaling challenges focusing on productivity, cost efficiency, and microservice management.
💼Case Study | Netflix Saves Time and Money with Server-Driven Notifications: Delves into how this system enhances cross-platform consistency and testability while saving on development time and platform-specific app updates.
💼Case Study | Navigating Software Architecture at Scale - Insights from Decathlon’s Architecture Process: Discusses the integration of methodologies like architecture committees, the C4 model, and System Thinking.
Take the Survey, Get a Packt Credit!
🧠 Expert Insight 📚
Here’s an excerpt from “Chapter 4: File and Directory Operations” in the book, System Programming Essentials with Go by Alex Rios, published in June 2024.
Calculating directory size
One of the most common things to be done is to check the size of directories. How can we do it using all our knowledge in Go? We first need to create a function to calculate the size of a directory:
func calculateDirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(filePath string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if !fileInfo.IsDir() {
size += fileInfo.Size()
}
return nil
})
if err != nil {
return 0, err
}
return size, nil
}
This function calculates the total size of all files within a given directory, including its subdirectories. Let’s understand how this function works:
func calculateDirSize(path string) (int64, error): This function takes a single argument path, which is the path to the directory for which you want to calculate the size. It returns two values: an int64 value representing the size in bytes and an error value indicating whether any errors occurred during the calculation.
It uses the filepath.Walk function to traverse the directory tree starting from the specified path. For each file or directory encountered during the walk, the provided callback function is called.
if !fileInfo.IsDir() { size += fileInfo.Size() }: This checks whether the current item is not a directory (i.e., it’s a file). If it’s a file, it adds the size of the file (fileInfo.Size()) to the size variable. This is how it accumulates the total size of all files.
After the filepath.Walk function completes its traversal, it checks if there was any error during the walk (if err != nil { return 0, err }) and returns the accumulated size if there were no errors.
The calculateDirSize could act as an invaluable part of a more general application where it is employed to compute the sizes of various directories listed within the directories slice. In the process, these sizes are converted into different units such as bytes, kilobytes, megabytes, or gigabytes, offering a more human-readable representation. The results are then presented to the user through an output stream.
Here’s a snapshot of how this function is applied within the larger context of the application:
m := map[string]int64{}
for _, directory := range directories {
dirSize, err := calculateDirSize(directory)
if err != nil {
fmt.Fprintf(cfg.ErrStream, "Error calculating size of %s: %v\n", directory, err)
continue
}
// Convert to MB
m[directory] = dirSize
}
for dir, size := range m {
var unit string
switch {
case size < 1024:
unit = "B"
case size < 1024*1024:
size /= 1024
unit = "KB"
case size < 1024*1024*1024:
size /= 1024 * 1024
unit = "MB"
default:
size /= 1024 * 1024 * 1024
unit = "GB"
}
fmt.Fprintf(outputWriter, "%s - %d%s\n", dir, size, unit)
}
The preceding code calculates the sizes of directories listed in the directories slice, converts those sizes to different units (bytes, kilobytes, megabytes, or gigabytes), and then prints the results.
System Programming Essentials with Go was published in June 2024. Packt library subscribers can continue reading the entire book for free or you can buy the book here!
🛠️ Useful Tools ⚒️
DevPod: an open-source tool that facilitates the creation and management of isolated, reproducible development environments in containers, which can be deployed on any infrastructure without server-side setup.
Briefer Notebooks: a hybrid of Notion and Jupyter with features for scheduling, dashboards, and SQL-to-dataframe conversions, designed to enhance sharing, reduce clutter, and streamline operations.
cnc: an open-source framework that simplifies application deployment across different environments using Infrastructure as Code principles and Terraform, streamlining the build, provision, and deployment stages.
That’s all for today.
We have an entire range of newsletters with focused content for tech pros. Subscribe to the ones you find the most useful here. Complete ProgrammingPro archives can be found here. Complete PythonPro archives are here.
If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want to advertise with us.
If you have any comments or feedback, take the survey, or leave a comment below.