Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

ProgrammingPro

34 Articles
Divya Anne Selvaraj
19 Sep 2024
Save for later

ProgrammingPro #74: Swift 6 Concurrency, C++ Memory Safety, Python Concurrency Best Practices, and Rust for Linux

Divya Anne Selvaraj
19 Sep 2024
Bite-sized actionable content, practical tutorials, and resources for programmers#74Join Roman Lavrik from Deloitte at Snyk hosted DevSecCon 2024Snyk is thrilled to announce DevSecCon 2024, Developing AI Trust Oct 8-9, a FREE virtual summit designed for DevOps, developer and security pros of all levels. Join Roman Lavrik from Deloitte, among many others, and learn some presciptive DevSecOps methods for AI-powered development.Save your spotHi ,Welcome to this week’s edition of ProgrammingPro!In today’sExpert Insight, we bring you an excerpt from the recently published book, Generative AI-Powered Assistant for Developers, which demonstrates how Amazon Q Developer assists in generating C++ code (The book also covers Python, Java, SQL, and more) for complex tasks like developing an operating system kernel.News Highlights: Swift 6 adds strict concurrency checking, C++ interoperability, and Embedded Swift; 60% of open source maintainers are unpaid, says 2024 report; C++ Alliance proposes a Safe Standard Library for memory safety; and RustConf reaffirms Rust's role in the Linux kernel.My top 5 picks from today’s learning resources:Why Learn Python Concurrency⚙️An Overview of C++26: Concurrency🔄Let’s build and optimize a Rust extension for Python🦀Leveraging eBPF for Improved Infrastructure Observability📊Llama 3 in Action - Deployment Strategies and Advanced Functionality for Real-World Applications🦙But there’s more, so dive right in.Stay Awesome!Divya Anne SelvarajEditor-in-ChiefPS: Thismonth’ssurvey is still live. Do take the opportunity to tell us what you think of ProgrammingPro, request learning resources, and earn your one Packt Credit for this month.Use AI to 10X your productivity & efficiency at workStill struggling to achieve work-life balance and manage your time efficiently?Join this 3 hour Intensive Workshop on AI & ChatGPT tools (usually $399) but FREE for the first 100 people.Save your free spot here (seats are filling fast!) ⏰Sign Up|Advertise🗞️News and Analysis🔎Swift 6 now available with strict concurrency checking: The version expands platform support, adds C++ interoperability, offers Embedded Swift, and improves build performance on Windows.Java 23 is now available: The version introduces preview features such as primitive types in patterns, flexible constructor bodies, and module import declarations. Library updates include structured concurrency and more.The state of open source maintainers: The 2024 State of Open Maintainer report has revealed that 60% of open source maintainers are unpaid despite their critical role in software security and paid maintainers face stress.Can Java rival Python in AI development?: Experts argue that Java's performance, enterprise adoption, and evolving syntax position it for growth in AI.C++ Alliance takes aim at C++ memory safety: The Safe C++ Extensions proposal introduces a Safe Standard Library with memory-safe implementations and features to prevent common memory-related errors.ASP.NET Core 9 RC 1 - Keep-Alive Timeouts for Websockets, Improved SignalR Tracing, and MoreLike: Other updates include Linux support for HTTPS certificates and type overriding for InputNumber components.RustConf speakers affirm Rust for Linux project despite challenges of unstable Rust, maintainer resignation: The Rust for Linux project, aims to make Rust a second programming language for the Linux kernel.🎓Tutorials and Learning Resources💡PythonWhy Learn Python Concurrency:Explains how concurrent, parallel, and asynchronous execution allow programs to fully utilize modern hardware, improve performance, and scale more effectively.For more Python resources, go to PythonProRecent Python Books from PacktBuy 5 eBooks for 30% + 20% off!Discount automatically calculated when you add items to cartGet the eBook for$31.99$21.99 Get the Print Book for$39.99$29.98Get the eBook for$43.99$29.99 Get the Print Book for$54.99$40.99Get the eBook for$31.99$18.99 Get the Print Book for$39.99 $25.99Print book discounts end on the 22nd of September 2024.C# and .NET🎓Tutorial | Using the Pinecone vector database in .NET: Explains how to build retrieval-augmented generation (RAG) AI applications.You have 10 seconds to nixify your .Net project: Guides you through building, packaging, and containerizing .NET applications using Nix and provides a detailed example.🎓Tutorial | Logistic Regression with Batch SGD Training and Weight Decay Using C#: Teaches you to use logistic regression for binary classification tasks and interpret the significance of model weights and bias.C and C++An Overview of C++26: Concurrency: Focuses on the new std::execution framework for managing asynchronous execution with schedulers, senders, and receivers.Going Super Sonic with Asio: Covers core usage, thread management, concurrency, IO optimization, and advanced strategies like custom allocators, disabling Nagle's algorithm, and efficient buffering.🎓Tutorial | LS implementation: Explains the implementation of the ls command in Unix-like operating systems, detailing how to replicate its various functionalities in C, such as listing all files (including hidden ones), and more.Java🎓Tutorial | Exception handling in Java - The basics: Covers how to throw, try, catch, and clean up exceptions and introduces concepts such as checked and unchecked exceptions, error handling, and the use of finally blocks.Embracing Reactive Applications on JVM - A Deep Dive Into Modern I/O Models and Vert.x: Discusses the evolution of I/O models and how reactive architectures, particularly Vert.x, can be leveraged for modern software development.The Arrival of Java 23: Announces the release of Java 23, detailing its new features, performance improvements, and contributions from the Java community while highlighting its significance for modern development.JavaScript and TypeScriptCompile and run C in JavaScript: Introduces Bun's new feature in version 1.1.28, enabling developers to compile and run C code directly from JavaScript for efficient use of native libraries without relying on N-API or WebAssembly.🎓Tutorial | How To Detect Proxies: Outlines how to detect and block proxy-based signups in web applications by examining IP spoofing techniques, using the X-Forwarded-For header, WebRTC, and third-party APIs like IPQuery.The Strange Behavior of the void Type in TypeScript: Explores the peculiar behavior of the void type in TypeScript, explaining its primary use for function return types, its restrictions on variable assignments, and more.GoHow Go Tests "go test": Explains how the Go team tests the go test command, outlining the evolution of testing methodologies for command-line tools, from shell scripts to Go-based testing frameworks.Notes on running Go in the browser with WebAssembly: Covers topics such as calling Go functions from JavaScript, manipulating the DOM with Go, and using TinyGo for smaller binaries.RustUnderstanding Memory Ordering in Rust: Explores the concept of memory ordering in Rust in multi-threaded programs to ensure data consistency when compiler and processor optimizations could disrupt execution order.🎓Tutorial | Let’s build and optimize a Rust extension for Python: Covers creating a Rust extension using PyO3 and Maturin, and optimizing it through various techniques like link-time optimization, and faster random number generation.SwiftSwift Build Times and Module Verification: Discusses optimizing Swift build times for the app Secrets 4 by refactoring its codebase into 36 smaller modules for better compiler performance and clearer access control.🎓Tutorial | Using Traits to annotate and customize test behavior: explains how to use traits in Swift Testing to annotate, customize, and control test behavior, including conditional enabling/disabling, bug tracking, and time limits.PHP🎓Why I Avoid Using empty() in PHP? A Closer Look: Highlights how the function's broad handling of values like 0, "0", and false can lead to unexpected behavior in production code, and advocates for strict comparisons (===).SQL🎓Tutorial | SQL from a Programming Language Perspective — Part I: Explains SQL's core operations—filtering, projecting, grouping, sorting, and merging tables—and how queries are built, focusing on SQL’s syntax evolution.Ruby🎓Tutorial | Ruby 3.0 - Optimizing Applications with GC.compact: Discusses the GC.compact method, which reduces memory fragmentation in long-running applications by compacting the heap.Kotlin🎓Advanced Kotlin Flow Cheat sheet (for Android Engineer):Covers key concepts such as cold vs. hot streams, channels, flow operators (merge, combine, zip), and buffer handling, with practical examples for optimizing flow.🌟Best Practices and Advice🚀Leveraging eBPF for Improved Infrastructure Observability: Discusses how Netflix uses eBPF to enhance infrastructure observability by monitoring system performance and detecting "noisy neighbors."Llama 3 in Action - Deployment Strategies and Advanced Functionality for Real-World Applications: Provides insights into deploying Llama 3, optimizing performance on platforms like AWS, and fine-tuning models for specific cases.Safeloop Architecture: Introduces a coding style focused on reducing cognitive load and improving predictability between design-time and runtime behavior by using explicit, predictable code patterns.A Comprehensive Introduction to Git & GitHub — Part 1/4 - Core git features: Covers essential concepts like Git architecture (working directory, staging area, repository), installation, configuring user identity, and more.🧠Expert Insight📚Here’s an excerpt from “Chapter 5: Boost Coding Efficiency for C and C++ with Auto-Code Generation” in the book, Generative AI-Powered Assistant for Developers by Behram Irani and Rahul Sonawane, published in August 2024.End-to-end C++ language use case developmentNow let’s move to the sample use case to show the power of Amazon Q Developer’s ability to recommend code. To illustrate, I am going to use the VS Code script editor window with singleandmulti-line prompts.Let’s say that we want to write a C++ program to develop a new operating system kernel, which can control system resources and has the ability to handle complex memory management tasks. The kernel must interact with hardware, manage processes, and ensure stability across differenthardware architectures.Let’s use the multi-line prompt technique to achieve the precedinguse case.Prompt:/* Write an end to end executable C++ scriptto develop a new operating system kernel, that can control over system resources and ability to handle complex memory management tasks. The kernel must interact with hardware, manage processes, and ensure stability across different hardware architectures.*/Figure 5.11 – Writing a C++ program with Amazon Q DeveloperThe preceding screenshot shows partial code suggested by Amazon Q Developer. You can observe that end-to-end code demonstrates several fundamental and advanced concepts in C++ programming, including OOP, classes, vectors, functions, error handling,and more.Now let’s use an interactive inline prompt with the chain-of-thought technique to enhance the code. As you can see, theloadProcess()function does not have exception handling, so let’s instruct it to add an exception handle for the null process with the single-lineprompt technique:Prompt :/* add exception handling for loadProcess */Figure 5.12 – Prompt – C++ program sample snapshotAs shown in the screenshot, based on our prompt, Amazon Q Developer added anullptrcondition to check the process load exception. If it encounters a null pointer, then the code gracefully exits with aError: process isnullmessage.Generative AI-Powered Assistant for Developerswas published in August 2024. Packt library subscribers can continue reading the entire book for free or you can buy the bookhere!Get the eBook for $31.99$21.99🛠️Useful Tools⚒️GraalVM: a high-performance JDK that compiles Java applications into native executables for instant startup and efficient performance.void: an open-source Cursor alternative, forked from vscode, allowing users to build, contribute, and develop independently with support via Discord and email.Neosync: an open-source tool for anonymizing PII, generating synthetic data, and syncing environments to improve testing, debugging, and compliance.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 usefulhere.If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want toadvertise with us.*{box-sizing:border-box}body{margin:0;padding:0}a[x-apple-data-detectors]{color:inherit!important;text-decoration:inherit!important}#MessageViewBody a{color:inherit;text-decoration:none}p{line-height:inherit}.desktop_hide,.desktop_hide table{mso-hide:all;display:none;max-height:0;overflow:hidden}.image_block img+div{display:none}sub,sup{line-height:0;font-size:75%}#converted-body .list_block ol,#converted-body .list_block ul,.body [class~=x_list_block] ol,.body [class~=x_list_block] ul,u+.body .list_block ol,u+.body .list_block ul{padding-left:20px} @media (max-width: 100%;display:block}.mobile_hide{min-height:0;max-height:0;max-width: 100%;overflow:hidden;font-size:0}.desktop_hide,.desktop_hide table{display:table!important;max-height:none!important}}
Read more
  • 0
  • 0
  • 1098

Divya Anne Selvaraj
12 Sep 2024
Save for later

ProgrammingPro #73: Java Microservices, C Falls in Tiobe Index, Rust Firmware Deployment, and Protocol Buffer Design

Divya Anne Selvaraj
12 Sep 2024
Bite-sized actionable content, practical tutorials, and resources for programmers#73:Java Microservices, C Falls in Tiobe Index, Rust Firmware Deployment, and Protocol Buffer DesignHi ,Welcome to this week’s edition of ProgrammingPro!In today’sExpert Insight, we bring you an excerpt from the recently published book, Java Concurrency and Parallelism, which demonstrates building a data processing pipeline using a microservices architecture with Java.News Highlights: C language falls to its lowest position in the Tiobe index; TypeScript 5.6 adds new compiler options and diagnostics; Vapor 5 leverages Swift 6 concurrency; and Rust 1.81 stabilizes the Error trait.My top 5 picks from today’s learning resources:Python QuickStart for People Learning AI🤖Modernize your UWP app with preview UWP support for .NET 9 and Native AOT🚀Deploying Rust in Existing Firmware Codebases🦀Protocol Buffer Design - Principles and Practices for Collaborative Development🤝Mastering Impact Analysis and Optimizing Change Release Processes🛠️But there’s more, so dive right in.Stay Awesome!Divya Anne SelvarajEditor-in-ChiefPS: Thismonth’ssurvey is still live. Do take the opportunity to tell us what you think of ProgrammingPro, request learning resources, and earn your one Packt Credit for this month.Sign Up|Advertise🗞️News and Analysis🔎C language slumps in Tiobe popularity index:C has dropped to fourth place, its lowest position since the index began. Read to learn about the reasons for C's reduced popularity compared to alternatives like C++ and Rust..NET 9 Release Candidate 1 is now available!: Key updates include enhanced WebSocket APIs, new compression options (ZLib and Brotli), advanced SignalR tracing, and improvements to .NET MAUI.Vapor 5 Materializes the Future of Server-Side Development in Swift: The release will leverage Swift 6's structured concurrency, introduce modern packages, and rewrite WebSocket and MultipartKit APIs for better async.Rust 1.81 stabilizes Error trait:The update allows its use in #![no_std] libraries, and introduces improved sort algorithms for better performance.TypeScript 5.6 now generally available:The update includes features such as disallowing nullish and truthy checks on non-variable syntax, new compiler options, and improved diagnostics.JFrog helps developers improve DevSecOps with new solutions and integrations: JFrog announced new solutions and integrations with GitHub and NVIDIA at its swampUp conference, enhancing security capabilities.Express.js 5.0 released after long delay, though not yet default as project appeals for contributors: New features include improved path route matching, better error handling for rejected promises, and the return of the app.router.🎓Tutorials and Learning Resources💡Sponsored Mini Course on AI worth $399 for free: 200+ hours of research on AI-led career growth strategies & hacks packed in 3 hours. Register Now.PythonPython QuickStart for People Learning AI:Covers Python fundamentals, including data types, loops, and functions, and provides a concrete AI project example using the OpenAI API for summarizing research papers.For more Python resources, go to PythonProC# and .NET🎓Tutorial | Modernize your UWP app with preview UWP support for .NET 9 and Native AOT: Explains how to upgrade UWP apps incrementally to .NET 9, adopt Native AOT, and discusses tools for future migration to WinUI 3.WebAssembly and Containers: Orchestrating Distributed Architectures with .NET AspireLike: Explains how .NET Aspire simplifies orchestration using C#, enabling developers to manage components using the Dashboard.🎓Tutorial | C# Testing set up: Provides a step-by-step guide on setting up testing in C# using xUnit, with a focus on creating a basic test structure for a C# class.C and C++What’s new in C++26 (part 1):Focuses on specifying reasons for deleted functions, unnamed placeholder variables, structured binding declarations in conditions, and user-generated static_assert messages.🎓Tutorial | Giving C++ std::regex a C makeover: Discusses how to wrap C++'s std::regex into a C interface, providing a way to use C++ regular expressions in C projects without dealing with C++ directly.🎥💼Case Study | Zero-Cost Abstractions in C++ - High Performance Message Dispatch - Luke Valenty - C++Now 2024: Provides a detailed breakdown of how Intel optimizes message handling and uses C++ techniques to manage power in embedded systems.Java🎓Tutorial | Packages and static imports in Java:Explains how Java developers can use packages and static imports to organize top-level types, prevent naming conflicts, and simplify access to static members.🎓Tutorial | Using oneAPI Construction Kit and TornadoVM to accelerate Java Programs on x86, ARM and RISC-V CPUs: Covers setup, performance comparisons, and configurations for OCK as an OpenCL and SPIR-V driver.🎓Tutorial | Writing a Linux scheduler in Java with eBPF (15): Explains how to implement two Linux schedulers using eBPF in Java: a FIFO scheduler and a weighted scheduler.Recent Java Resources from PacktDiscover strategies and best practices to develop high performance Java applicationsGet the eBook for $33.99$22.99Proven recipes for building modern and robust Java web applications with Spring BootGet the eBook for $31.99$21.99Master Continuous Integration with Jenkins: Automate, Test, and Deploy Like a ProGet the 3 hour course for $49.99JavaScript and TypeScriptUnderstanding Concurrency, Parallelism and JS: Explores the differences between concurrency and parallelism, explains how JavaScript achieves concurrency through Node.js’s single-threaded event-driven model, and more.Javascript/Python Array Quick Reference: Offers side-by-side comparisons of syntax for tasks like accessing, iterating, mapping, adding/removing elements, filtering, and sorting.What Good Looks Like - A Real-World Typescript Refactor: Demonstrates a real-world TypeScript refactor of an entity-manager library, focusing on improving efficiency and reducing complexity.Go🎓Tutorial | An HTTP Server in Go From scratch: Walks through key steps, including binding to a port, responding with status codes, extracting URL paths, handling request headers, and implementing concurrent connections.Using Go instead of bash for scripts: Explains how to automate programming tasks and simplify development by replacing Bash scripts with a more efficient, cross-platform Go program.RustDeploying Rust in Existing Firmware Codebases: Discusses how to incrementally deploy Rust into existing firmware codebases, focusing on enhancing memory safety, especially for critical components.Porting C to Rust for a Fast and Safe AV1 Media Decoder: Takes you through the challenges and methods of preserving C API compatibility, managing threading models, and achieving memory safety while maintaining performance.SwiftSwift Type placeholder - What is it and when to use it: Discusses Swift's type placeholders, introduced in Swift 5.6, allowing the compiler to infer complex types using underscores (_) in place of specific types.Swift Testing - Validate your code using expressive APIs: Discusses Apple's new Swift Testing framework, which includes the @Test macro for defining tests, the #expect macro for assertions, and enhanced feedback in Xcode for test results.PHP🎓Look out, kids - PHP is the new JavaScript: Shows how Laravel has revitalized PHP, offering developers an easy and efficient way to build dynamic web applications, making PHP fun and relevant again.SQLDissecting a Hybrid Search query in SQL: Explains how to use Common Table Expressions (CTEs) in SQL to build hybrid search queries, focusing on combining vector and full-text search results.KotlinLoading Initial Data in LaunchedEffect vs. ViewModel: Compares two approaches for loading initial data in Jetpack Compose: using LaunchedEffect within a composable and ViewModel.init().🌟Best Practices and Advice🚀💼Case Study | Protocol Buffer Design - Principles and Practices for Collaborative Development: Highlights the benefits of Protobuf for scalability, backward compatibility, and consistency in multi-language environments.How to Make Technical Debt Your Friend: Argues that not all TD needs to be repaid, and using a Minimum Viable Architecture (MVA) approach allows teams to focus on delivering Minimum Viable Products that meet immediate needs.Mastering Impact Analysis and Optimizing Change Release Processes: Emphasizes focusing on "why" rather than "who" when analyzing failures, improving pre-production testing, and minimizing the blast radius of bugs.Do we need enterprise software marketplaces?: Explores the evolution of marketplaces, from gadget collections to API-driven models, and the importance of maintaining strong vendor relationships for future success.🧠Expert Insight📚Here’s an excerpt from “Chapter 8: Microservices in the Cloud and Java’s Concurrency” in the book, Java Concurrency and Parallelism, by Jay Wang, published in August 2024.Use case 2 – building a data processing pipeline with microservicesThis case study delves into designing and implementing a data processing pipeline using amicroservices architecture:The first step is to design the microservices. We’ll construct the pipeline with threedistinct microservices:Data ingestion service: This service acts as the entry point, which is responsible for receiving and validating incoming data from external sources. Once validated, it publishes the data to an Amazon SQS queue for further processing. The service depends on the Amazon SQSclient library.Data processing service: This service subscribes to the Amazon SQS queue used by the data ingestion service. It consumes the data, applies business logic for transformation, and publishes the processed data to another SQS queue for persistence. This service relies on both the Amazon SQS client library and the AWSGlue SDK.Data persistence service: The final service consumes the processed data from the second SQS queue. Its primary function is to store the data persistently in Amazon RDS for long-term accessibility. This service utilizes both the Amazon SQS client library and the Amazon RDS client library...The next step is to set upthe AWSs:Two AWS Simple Queue Service(SQS)queueswill beset up:Initial data queue: Create a queue intended for receiving initialunprocessed dataProcessed data queue: Set up another queue for holding processed data ready for further actionsor storageAWS RDS instance: Set up an RDS instance to provide persistent storage for your application. You can choose MySQL, PostgreSQL, or any other available RDS database engine depending on your application requirements. This database will be used to store and manage the data processed byyour application.AWS Simple Notification Service(SNS): Create an SNS topic to facilitate the notification process. This topic will be used to publish messages notifying subscribers of successful data processing events and other important notifications. Determine the subscribers to this topic, which could include email addresses, SMS, HTTP endpoints, or even other AWS services such as Lambda or SQS, depending on yournotification requirements.The third step is to set up a Maven project. Create a new Maven project for each microservice (DataIngestionService, DataProcessingLambda, and DataPersistenceService) in your preferredIntegrated Development Environment(IDE) or using the command line. Open thepom.xmlfile in each project’s root directory and add therelated dependencies.The fourth step is to implement the dataingestion service:@Servicepublic class DataIngestionService { private final AmazonSQS sqsClient; public DataIngestionService(AmazonSQS sqsClient) { this.sqsClient = sqsClient; } public void ingestData(Data dat{ // Validate the incoming data if (isValid(data)) { // Publish the data to Amazon SQS SendMessageRequest sendMessageRequest = new SendMessageRequest() .withQueueUrl("data-ingestion-queue-url") .withMessageBody(data.toString()); sqsClient.sendMessage(sendMessageRequest); } } private boolean isValid(Data dat{ boolean isValid = true; // Implement data validation logic // ... return isValid; }The code represents the implementation of the data ingestion service, which is responsible for receiving incoming data, validating it, and publishing it to Amazon SQS forfurther processing.TheDataIngestionServiceclass is annotated with@Service, indicating that it is a Spring service component. It has a dependency on theAmazonSQS client, which is injected throughthe constructor.TheingestData()method takes adata objectas input and performs data validation by calling theisValid()method. If the data is valid, it creates aSendMessageRequestobject with the specified SQS queue URL and the data payload as the message body. The message is then sent to the SQS queue using thesqsClient.sendMessage()method.The fifth step is to implement the data processing service usingAWS Lambda:public class DataProcessingLambda implements RequestHandler<SQSEvent, Void> { private final AmazonSQS sqsClient; public DataProcessingLambda() { this.sqsClient = AmazonSQSClientBuilder.defaultClient(); } @Override public Void handleRequest(SQSEvent event, Context context) { for (SQSEvent.SQSMessage message : event.getRecords()) { String data = message.getBody(); // Transform the data within the Lambda function String transformedData= transformData( data); // Publish the transformed data to another Amazon SQS for persistence or further // processing sqsClient.sendMessage( new SendMessageRequest() .withQueueUrl( "processed-data-queue-url") .withMessageBody(transformedData)); } return null; } /** * Simulate data transformation. * In a real scenario, this method would contain logic to transform data based * on specific rules or operations. * * @param data the original data from the SQS message * @return transformed data as a String */ private String transformData(String dat{ // Example transformation: append a timestamp or modify the string in some way return "Transformed: " + data + " at " + System. currentTimeMillis(); }}This Lambda function,DataProcessingLambda, processes data from an Amazon SQS queue by implementing theRequestHandlerinterface to handleSQSEventevents. It initializes an Amazon SQS client in the constructor and uses it to send transformed data to another SQS queue for further processingor storage.ThehandleRequest()method, serving as the function’s entry point, processes eachSQSMessagefrom theSQSEvent, extracting the data and transforming it directly within the function through thetransformData()method. Here, the transformation appends a timestamp to the data as a simple example, but typically this would involve more complex operations tailored to specific dataprocessing requirements.Following the data transformation, the function sends the processed data to a specified SQS queue by invoking thesendMessage()method on theSQS client.The next step is to create a Spring-managed service that handles storing processed data in a database and notifies subscribers via AWS SNS uponsuccessful persistence:@Servicepublic class DataPersistenceService { private final AmazonSNS snsClient; private final DataRepository dataRepository; public DataPersistenceService(DataRepository dataRepository) { // Initialize the AmazonSNS client this.snsClient = AmazonSNSClientBuilder.standard(). build(); this.dataRepository = dataRepository; } public void persistData(String data{ // Assume 'data' is the processed data received // Store the processed data in a database Data dataEntity = new Data(); dataEntity.setProcessedData(data); dataRepository.save(dataEntity); // Send notification via SNS after successful persistence sendNotification("Data has been successfully persisted with the following content: " + data); } private void sendNotification(String message) { // Define the ARN of the SNS topic to send notification to String topicArn = "arn:aws:sns:region:account-id:your- topic-name"; // Create the publish request PublishRequest publishRequest = new PublishRequest() .withTopicArn(topicArn) .withMessage(message); // Publish the message to the SNS topic snsClient.publish(publishRequest); }}DataPersistenceService is a Spring-managed bean responsible for handling data persistence and notifying other components or services via Amazon SNS....Java Concurrency and Parallelismwas published in August 2024. Packt library subscribers can continue readingthe entire book for free or you can buy the bookhere!Get the eBook for $33.99$22.99🛠️Useful Tools⚒️dokku: an open-source PaaS using Docker, allowing developers to deploy Heroku-compatible apps via git and run them in isolated containers.R3: a modern, high-performance reimplementation of Reactive Extensions for .NET, optimized for game engines and aligned with new C# features.nomadic: An enterprise-grade toolkit by NomadicML for optimizing compound AI systems, allowing teams to refine hyperparameters and prompts.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 usefulhere. Complete ProgrammingPro archives can be foundhere. Complete PythonPro archives arehere.If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want toadvertise with us.*{box-sizing:border-box}body{margin:0;padding:0}a[x-apple-data-detectors]{color:inherit!important;text-decoration:inherit!important}#MessageViewBody a{color:inherit;text-decoration:none}p{line-height:inherit}.desktop_hide,.desktop_hide table{mso-hide:all;display:none;max-height:0;overflow:hidden}.image_block img+div{display:none}sub,sup{line-height:0;font-size:75%}#converted-body .list_block ol,#converted-body .list_block ul,.body [class~=x_list_block] ol,.body [class~=x_list_block] ul,u+.body .list_block ol,u+.body .list_block ul{padding-left:20px} @media (max-width: 100%;display:block}.mobile_hide{min-height:0;max-height:0;max-width: 100%;overflow:hidden;font-size:0}.desktop_hide,.desktop_hide table{display:table!important;max-height:none!important}}
Read more
  • 0
  • 0
  • 899

Divya Anne Selvaraj
05 Sep 2024
Save for later

ProgrammingPro #72: Optimizing Builds with CMake & ccache, Android 15 Developer Tools, PyPi Security Risks, and JDK 23 Updates

Divya Anne Selvaraj
05 Sep 2024
Bite-sized actionable content, practical tutorials, and resources for programmers#72:Optimizing Builds with CMake & ccache, Android 15 Developer Tools, PyPi Security Risks, and JDK 23 UpdatesHi ,Welcome to this week’s edition of ProgrammingPro!In today’sExpert Insight, we bring you an excerpt from the recently published book, CMake Best Practices -Second Edition, which discusses how to optimize and maintain CMake projects using a compiler cache, specifically ccache, to speed up C and C++ builds.Related Titles from PacktGet to grips with CMake and take your C++ development skills to enterprise standardsUse hands-on exercises and self-assessment questions to lock-in your learningUnderstand how to build in an array of quality checks and tests for robust codeGet the eBook for $39.99 $27.98Get the Print Book for $49.99 $39.98Comprehensive introduction to C++ programming and detailed explanations of algorithmic concepts.Step-by-step setup of development environments, with practical exercises and real-world examples.In-depth coverage of control structures, and visual aids such as trace tables and flowcharts.Get the eBook for $9.99News Highlights: Android 15 launches with enhanced developer tools; PyPi faces security risks in package management; .NET 9 introduces crucial security updates, .NET Framework remains vulnerable; and Elasticsearch reverts to open source amid tech shifts.My top 5 picks from today’s learning resources:Web Scraping With Scrapy and MongoDB🕸️.NET and C# are in trouble. Here is what I'd do🚨JDK 23 and JDK 24 - What We Know So Far🔍Efficient DevSecOps Workflows With a Little Help From AI🤖Gemma explained - RecurrentGemma architecture🧠But there’s more, so dive right in.Stay Awesome!Divya Anne SelvarajEditor-in-ChiefPS: Thismonth’ssurvey is now live. Do take the opportunity to tell us what you think of ProgrammingPro, request learning resources, and earn your one Packt Credit for this month.Developing for iOS? Setapp's 2024 report on the state of the iOS market in the EU is a must-seeHow do users in the EU find apps? What's the main source of information about new apps? Would users install your app from a third-party app marketplace?Set yourself up for success with these and more valuable marketing insights in Setapp Mobile's report, "iOS Market Insights for EU."Get Insights FreeSign Up|Advertise🗞️News and Analysis🔎Android 15 is now officially available: The version introduces a range of developer tools in Android Studio and Jetpack including new PdfRenderer API capabilities, new OpenJDK APIs, new SQLite APIs, and new Canvas drawing capabilities.TypeScript 5.6 enters release candidate stage: Changes include renamed types, reverted search behavior for tsconfig.json files, and improvements from the prior beta phase.PyPi repository vulnerable to deleted package hijack, say researchers: Researchers at JFrog have identified a vulnerability in the PyPi package repository where attackers can hijack deleted package names and upload malicious versions.Microsoft makes breaking change in .NET 9 for security, leaves .NET Framework insecure: Microsoft is removing the BinaryFormatter class from .NET 9 due to its unfixable security risks, although it will remain in the .NET Framework.Elasticsearch will be open source again as CTO declares changed landscape: This move comes after the projects shifted from the Apache 2.0 license to more restrictive terms in 2021, aimed at preventing companies like AWS from offering these products as managed services without collaboration.Uno Platform 5.3 Released: The version Introduces official support for JetBrains Rider, enhances the Hot Reload experience across all supported IDEs, and includes new UI controls..NET Aspire 8.2: Components Renamed to Integrations, Enhanced Testing, and More Improvements: The version also introduces a Hosting package to simplify resource management in local development and enhanced setup.🎓Tutorials and Learning Resources💡Sponsored Mini Course on AI worth $399 for free: 200+ hours of research on AI-led career growth strategies & hacks packed in 3 hours. This course on AI has been taken by 1 Million people across the globe. Register Now.Sponsored Live Webinar - The Power of Data Storytelling in Driving Business Decisions: Join to learn about Data Storytelling and turn complex information into actionable insights for faster decision-making. Register for free.PythonWeb Scraping With Scrapy and MongoDB:Guides you through setting up a Scrapy project, building a web scraper, extracting data, and storing it in MongoDB.Readto also learn about testing and debugging techniques.For more Python resources, go to PythonProC# and .NETLesser-known operators in C#: Details unique logical and null operators alongside functional ones, which enhance code expressiveness and error handling.🎥.NET and C# are in trouble. Here is what I'd do: Delves into the debate surrounding the rapid evolution of .NET and C#, featuring community reactions and proposals for enhancing adoption and support.🎥🎓Tutorial | Let's Build Our Own ArrayPool - Deep .NET with Stephen & Scott: Explores the intricacies of object pooling, optimizing array length, and managing memory pressure, alongside concurrent queue operations and thread management.C and C++Qt/.NET — Using QML in a .NET WPF application: Discusses the integration of QML into .NET WPF applications through the proposed Qt/.NET toolkit, allowing seamless interoperability between C++ and .NET.Honey, I shrunk {fmt}: bringing binary size to 14k and ditching the C++ runtime: Covers strategies including using type erasure to minimize template bloat and applying the Dragonbox algorithm for efficient numeric formatting.HashMap in 25 lines of C: Demonstrates how to construct a simple hash table in C, accommodating any value that C understands.Java🎓Tutorial | Static classes and inner classes in Java: Shows how nested classes can organize code and explains static member classes. Read to gain insights into using nested classes in Java to maintain cleaner code structure.JDK 23 and JDK 24 - What We Know So Far: Provides a breakdown of new Java Enhancement Proposals (JEPs) across different categories and updates on major Java projects like Amber, Loom, Panama, and Valhalla.Hide and Seek with Collections in Java: Delves into the Collection Accessor Method pattern using Eclipse Collections, analyzing various strategies to manage relationships within object-oriented domains in Java.JavaScript and TypeScriptPoor man's signals: Explains how signals can be implemented using JavaScript's EventTarget class, providing a simplified, event-driven approach to track changes to data.Compilation of JavaScript to Wasm, Part 3 - Partial Evaluation: Explores the use of the first Futamura projection to transform interpreter code into compiled WebAssembly code, highlighting the practical challenges and solutions.Advanced React Component Design with TypeScript: Focuses on creating reusable, flexible, and type-safe components while enhancing developer experience (DX).GoExploring Goja - A Golang JavaScript Runtime: Explores how Goja, a JavaScript runtime for Golang, effectively simplifies embedding JavaScript in Go applications, particularly for tasks involving complex data manipulation.Telemetry in Go 1.23 and beyond: Discusses the introduction of telemetry in Go 1.23, allowing developers to opt-in to sharing toolchain usage data to improve bug fixes, prevent regressions, and enhance decision-making.RustUnmaking the Makefiles - exorcising the Rust compiler test suite one file at a time: Narrates the journey of rewriting 352 Makefiles into Rust using the run-make-support crate, which was part of a Google Summer of Code project.Async Rust can be a pleasure to work with (without `Send + Sync + 'static`): Explains how to simplify async Rust development by avoiding Send + Sync + 'static bounds through Structured Concurrency and thread-per-core.SwiftCross-Platform Swift - Building a Swift app for the browser: Discusses the development of Swift applications for non-Apple platforms, specifically focusing on creating a simple Swift app that runs in a browser using WebAssembly.Swift Enums 🤝 Design Systems: Elaborates on the advantages of using enums to define UI components, providing a clean and maintainable way to encapsulate branding elements like colors and icons into reusable components.PHP🎓Tutorial | PHP and Web Dev Phobia: Guides you through setting up a virtual machine using Vagrant and VirtualBox, installing PHP and Lighttpd on Debian, and creating a simple PHP page.SQLBest practices for prompt engineering with Meta Llama 3 for Text-to-SQL use cases: Outlines the process of setting up the model with Amazon SageMaker JumpStart, using structured prompts, and leveraging model versions for optimized dialogue and SQL parsing.RubyWrite a Ruby C Extension to Use CLIPS from Ruby - Part 3: Focuses on enabling Ruby methods to be called from CLIPS rules, showcasing how to manipulate and interact with Ruby objects and data types within the CLIPS environment.Transpiling Go & Java to Ruby using GPT-4o & Claude 3.5 Sonnet: Discusses the extension of the DevQualityEval LLM code generation benchmark to include Ruby and utilizing LLMs like Claude 3.5 Sonnet.Kotlin🎓Tutorial | Data Analytics With Kotlin Notebooks, DataFrame, and Kandy: Guides beginners on how to set up and use Kotlin Notebook to analyze and visualize data, specifically using a weather data CSV file as an example.🌟Best Practices and Advice🚀Efficient DevSecOps Workflows With a Little Help From AI: Explores how AI aids in identifying security vulnerabilities, offering explanations and fixes, and streamlining operations with features like root cause analysis.Glue and coprocessor architectures: Highlights how systems can efficiently handle complex computations by separating them into highly specialized tasks performed by coprocessors and more general, flexible operations.Gemma explained - RecurrentGemma architecture: Discusses how the architecture employs a hybrid model called Griffin that combines gated linear recurrences with local sliding window attention for efficient long context processing.Lean Architecture: Proposes a 'Lean Architecture,' focusing on efficiency, minimal design waste, and maintaining software with an adaptable, problem-solving approach rather than following strict architectural guidelines.🧠Expert Insight📚Here’s an excerpt from “Chapter 14: Optimizing and Maintaining CMake Projects” in the book, CMake Best Practices -Second Edition, by Dominik Berner and Mustafa Kemal Gilor, published in August 2024.Using a compiler cache (ccache) to speed up rebuildsCcaches work by caching compilations and detecting when the same compilation is done again. At the time of writing this book, the most popularprogram for caching compile results isccache, which is open source and distributed under the Lesser General Public License 3(LGPL 3). The ccache program not only affects incremental builds but also fresh builds, as long as the cache is not deleted between the two runs. The cache created is portable between systems running the same compilers and can be stored in remote databases so that multiple developers may access the same cache. Officially, ccachesupports GCC, Clang, andNvidia CUDA Compiler(NVCC), but people claim to have run it for MSVC and Intel compilers. When usingccachewith CMake, it works best with Makefile and Ninja generators. At the time of writing this book, Visual Studio wasnot supported.To useccache with CMake, the CMAKE_<LANG>_COMPILER_LAUNCHER cache variable is used, where <LANG>is replaced with the respective programming language. The recommended way is to pass this in using a preset, but to enableccachefor C and C++ inside aCMakeLists.txt file, the following code canbe used:find_program(CCACHE_PROGRAM ccache)if(CCACHE_PROGRAM) set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM}) set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM})endif()Passing the variable from a preset or from the command line or a preset is also a good alternative, especially because the configuration ofccacheis done easiest by usingenvironment variables.Usingccachewith the default configuration might already bring a considerable improvement regarding build times, but if the build is a bit more complex, further configuration might be necessary. To configureccache, certain environment variables starting withCCACHE_can be used; for full documentation of all configuration options, refer to theccachedocumentation. Common scenarios that need special attention are combiningccache with precompiled headers, managing dependencies that are included usingFetchContent, and combiningccache with other compiler wrappers, such asdistcc or icecc for distributed builds. For these scenarios, the following environment variables are used:To work efficiently with precompiled headers, set CCACHE_SLOPPINESS to pch_defines,time_macros. The reason for this is that ccachecannot detect changes in#definesin the precompiled header, and it cannot tell if__TIME__,__DATE__, or__TIMESTAMP__ are used when creating precompiled headers. Optionally, setting include_file_mtime to CCACHE_SLOPPINESS might further increase the cache hit performance, but it carries a very small risk of arace condition.When including big dependencies that are built from source (for instance, by usingFetchContent), setting CCACHE_BASEDIR to CMAKE_BINARY_DIR might increase the cache hit rate; this might bring a performance boost especially if there are many (sub)projects fetching the same dependency. On the other hand, if the sources in the project itself are the ones that take more time to compile, setting this toCMAKE_SOURCE_DIRmight bring better results. It needs to be tried out to learn which one brings thebetter result.To work with other compiler wrappers, theCCACHE_PREFIX environment variable is used to add commands for these wrappers. It is recommended to useccache first when chaining multiple wrappers so that the results of other wrappers may alsobe cached.Passing environment variables to CMake using a configure preset, as described in "Chapter 9,Creating Reproducible Build Environments", is the recommended way; this can either be combined with detectingccache inside the CMakeLists.txt file or the ccache command may also be passed using the following preset:{"name" : "ccache-env",... "environment": { "CCACHE_BASEDIR" : "${sourceDir}", "CCACHE_SLOPPINESS" : "pch_defines,time_macros" }},With these configurations, usingccachecan yield very large benefits to the compile time, but caching compiler results is a complicated matter, so to get the full benefit, theccachedocumentation should be consulted. In most cases, usingccachewill probably bring the most performance benefit with a relatively trivial setup. Other tools, such asdistccfor distributed builds, work very similarly from the CMake perspective, but require a bit moresetup work.CMake Best Practices -Second Edition was published in August 2024. Packt library subscribers can continue readingthe entire book for free or you can buy the bookhere!Get the eBook for $33.99$22.99Get the Print Book for $41.99🛠️Useful Tools⚒️Daytona: An open-source tool that simplifies the setup of development environments, allowing developers to configure and launch their workspaces with a single command across various platforms and architectures.Sparo: Anopen-source tool developed by TikTok engineers to enhance the performance of large monorepos by utilizing sparse checkout and partial clone features of Git for more efficient operations.lmnr: an open-source observability and analytics platform tailored for complex LLM applications, integrating automatic telemetry, analytics, and prompt chain management with a focus on performance, transparency, and scalability.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 usefulhere. Complete ProgrammingPro archives can be foundhere. Complete PythonPro archives arehere.If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want toadvertise with us.If you have any suggestions or feedback, or would like us to find you a Programming learning resource on a particular subject, take the surveyor just respond to this email!*{box-sizing:border-box}body{margin:0;padding:0}a[x-apple-data-detectors]{color:inherit!important;text-decoration:inherit!important}#MessageViewBody a{color:inherit;text-decoration:none}p{line-height:inherit}.desktop_hide,.desktop_hide table{mso-hide:all;display:none;max-height:0;overflow:hidden}.image_block img+div{display:none}sub,sup{line-height:0;font-size:75%}#converted-body .list_block ol,#converted-body .list_block ul,.body [class~=x_list_block] ol,.body [class~=x_list_block] ul,u+.body .list_block ol,u+.body .list_block ul{padding-left:20px} @media (max-width: 100%;display:block}.mobile_hide{min-height:0;max-height:0;max-width: 100%;overflow:hidden;font-size:0}.desktop_hide,.desktop_hide table{display:table!important;max-height:none!important}}
Read more
  • 0
  • 0
  • 1509
Subscribe to Packt _ProgrammingPro
A weekly Programming newsletter that helps to keep you up to date on industry trends and advance your skills as a developer or software engineer. ProgrammingPro combines original ideas and curated content, deep dives and tools, all in one place.

Divya Anne Selvaraj
29 Aug 2024
Save for later

ProgrammingPro #71: Nullable Reference Types in C#, Prompty for VS Code, Python Packaging Tools

Divya Anne Selvaraj
29 Aug 2024
Bite-sized actionable content, practical tutorials, and resources for programmers#71:Nullable Reference Types in C#, Prompty for VS Code, Python Packaging Tools, and Rust Error HandlingHi ,Welcome to this week’s edition of ProgrammingPro!In today’sExpert Insight, we bring you an excerpt from the recently published book, Functional Programming with C#, which discusses the implementation of Nullable Reference Types (NRTs) in C#, as a tool for developers to handle null references more safely and transparentlyNews Highlights: OSI releases latest draft of Open Source AI Definition; Microsoft releases Prompty, a new VS Code extension for integrating LLMs into .NET development; JetBrains Workspaces offers monorepo benefits exclusively in IntelliJ IDEA; and Survey shows game engines like Godot gaining traction in non-game projects.My top 5 picks from today’s learning resources:What's the deal with setuptools, setup.py, pyproject.toml, and wheels?🛠️Supercharge your testing experience with MSTest.Analyzers⚡The definitive guide to error handling in Rust🛡️Simplicity, Speed, and Re-Use. Shipping Threads in 5 Months🚀Best practices for event logging and threat detection🛑But there’s more, so dive right in.Stay Awesome!Divya Anne SelvarajEditor-in-ChiefPS:We have finished covering all requests made by you so far through the August survey. We did receive some specific and comprehensive requests around Java and are therefore planning to take out a Collector's Edition on Java sometime next month. If you have any more Java specific requests you would like covered in the special issue, reply to this email and let me know.Sign Up|Advertise🗞️News and Analysis🔎OSI releases latest draft of Open Source AI Definition: The draft clarifies that all components of an AI system must meet open source standards, excludes training data from classification, and updates key terminologies.Kotlin update shines on garbage collector:The update also includes bug fixes, support for newer Gradle versions, and improvements in Kotlin Multiplatform development.The slow evolution of enterprise tech: argues that despite the rapid hype cycles around technologies like cloud computing and gen AI, enterprise tech evolves slowly, with core programming languages and databases remaining largely unchanged over the past decade.JDK 24 preps for restrictions on JNI use: This feature will introduce warnings to prepare for future restrictions, aligning JNI usage with the Foreign Function and Memory (FFM) API.Microsoft Releases Prompty - New VS Code Extension for Integrating LLMs into .NET DevelopmentLike: This free tool simplifies adding AI-driven capabilities to applications, such as generating content or creating chatbots, directly within the development environment.JetBrains Workspaces aims for benefits of monorepos without the downside – but only in IntelliJ IDEA: The plugin addresses issues like monorepo fragility and performance problems by keeping projects independent.Survey finds game engines used equally by non-game projects, rise of interest in open source Godot: The survey also noted the increasing use of JetBrains Rider and VS Code, and challenges in collaboration due to the handling of large files in game development.🎓Tutorials and Learning Resources💡PythonWhat's the deal with setuptools, setup.py, pyproject.toml, and wheels?:Provides a detailed explanation of Python packaging tools and practices, offering insights and recommendations for how to approach packaging in modern projects.Debugging and Profiling in Python: Discusses debugging and profiling tools for Python, highlighting key libraries like pdb, faulthandler, cProfile, and tracemalloc.For more Python resources, go to PythonProC# and .NET🎓Tutorial | Introducing the Pinecone .NET SDK: Provides a step-by-step guide on setting up the SDK, creating an index, adding records, and querying data.Supercharge your testing experience with MSTest.Analyzers: Showcases specific examples of how MSTest.Analyzers help catch common mistakes, and provides recommendations for best practices in test writing.The C# type system: Explains built-in and custom types, the common type system (CTS), and how types influence memory allocation, type safety, and program behavior.C and C++C++ unwind exception metadata - A hidden reverse engineering bonanza: Discusses how C++ unwind exception metadata can aid reverse engineering by revealing hidden details about data structures in C++ programs, particularly those using MSVC/x64 targets.An Overview of C++26 - Core Language: Highlights key features such as reflection, which enhances compile-time programming, and contracts, which allow precise and checkable interface specifications.How to run valgrind on a CGI program in C: Explains how to use Valgrind to debug a memory corruption issue in a CGI program that only manifests during a POST request.Java🎓Tutorial | Better than reflection: Using method handles and variable handles in Java: Discusses replacing Java reflection with MethodHandle and VarHandle for accessing methods and fields programmatically.🎓Tutorial | Method overloading in the JVM: Focuses on techniques like widening, boxing, and varargs. Read to learn about the advantages of method overloading for cleaner code and common pitfalls to avoid.WebAssembly, the Safer Alternative to Integrating Native Code in Java: Highlights the use of Chicory, a pure JVM Wasm runtime, to integrate Wasm-compiled code, such as SQLite, into Java applications, providing strong security guarantees.JavaScript and TypeScriptCompilation of JavaScript to Wasm, Part 2 - Ahead-of-Time vs. JIT: Discusses the challenges of compiling JavaScript due to its dynamic typing and the limitations of traditional JIT (just-in-time) compilation in Wasm-first platforms.Frontend Strategies - Frameworks or Pure JavaScript?: Clarifies when to use frameworks versus pure JavaScript, along with the advantages of modular code, reusable components, and integration with modern development tools.Announcing TypeScript 5.6 RC: Details new features like disallowed nullish and truthy checks, iterator helper methods, and improved built-in iterator checks.GoC# (.NET) vs. Go (Golang): Performance Benchmark in Kubernetes: Focuses on metrics like CPU and memory usage, request handling capacity, and end-user latency. Read to learn how Golang generally performed better.The 4-chan Go programmer: Humorously explores the complexities of using channels in Go by demonstrating a convoluted example of sending channels over channels, inspired by the concept of "4-star programmers" from C.Rust💼Case Study | MiniJinja - Learnings from Building a Template Engine in Rust: Discusses the author's experience and technical challenges in creating MiniJinja, a Jinja2-compatible template engine in Rust.🎓Tutorial | The definitive guide to error handling in Rust: Covers the use of Result, dynamic errors like Box<dyn Error>, and structured errors. Read to also learn about downcasting errors, using the anyhowcrate.SwiftSwift Macros at scale: Introduces Tuist, a tool for managing Xcode projects, which supports caching for Swift Macros, improving build times for developers.Designing Apps: 5 Methods to improve your workflow: Highlights techniques such as using the Golden Ratio, proper spacing for visual hierarchy, designing directly with SwiftUI, gradually enhancing app visuals from basic to vibrant, and more.PHP🎓Tutorial | How to build a game engine in a CMS, in PHP:While acknowledging that it's not an ideal approach, the author details creating a rendering system, implementing game logic, handling collisions, adding animations, and more.SQLEfficient Data Cleanup in Partitioned PostgreSQL Tables using Common Table Expressions: Demonstrates using CTEs to identify deletable data, optimizing the deletion process through batch processing, and maintaining database consistency.Scala and Spark"Domain Modeling" in the Scala 3 - Book: Covers the tools available in Scala, such as classes, traits, and enums, to build models. Read to learn how to effectively represent attributes and behaviors within each paradigm.Spark — debugging a slow Application: Outlines common reasons why Apache Spark applications may run slowly, highlighting issues such as input/source inefficiencies, uneven or excessive partitioning, and slow transformations.[Solution] Spark — debugging a slow Application: Covers techniques such as partitioning, bucketing, and file compaction, and advises on managing partition sizes, leveraging adaptive query execution, avoiding slow transformations, and more.KotlinKotlin's Type System is (Also) Unsound: Presents a proof that Kotlin's type system can allow operations that should not be permissible at runtime. Read to learn about the specific language features involved, and potential solutions.🌟Best Practices and Advice🚀Podcast: Misconceptions around Agile in an AI world: Featuring insights from David Ross, Agile evangelist for Miro, highlights how Agile practices have evolved, moving away from rigid frameworks towards more adaptive and pragmatic approaches.Simplicity, Speed, and Re-Use. Shipping Threads in 5 Months: Describes how despite technical debt and challenges, such as scaling issues on launch day, the team prioritized simplicity and leveraged a battle-tested codebase to meet tight deadlines.Best practices for event logging and threat detection: Developed by the Australian Cyber Security Centre in collaboration with international cybersecurity agencies, this document emphasizes creating an enterprise-approved logging policy, ensuring log quality, centralizing log collection, and implementing secure storage.The Terralith: Monolithic Architecture of Terraform & Infrastructure as Code: Argues for breaking down monolithic structures into smaller, more manageable modules to enhance scalability, maintainability, and reduce risk.🧠Expert Insight📚Here’s an excerpt from “Chapter 4: Honest Functions, Null, and Option” in the book, Functional Programming with C# by Alex Yagur, published in July 2024.Embracing honesty with nullable reference typesHandling null in C# has alwaysbeen quite a challenge. Many software developers (me included) advocate doing a check for NullReferenceExceptions as a mandatory task in a code review checklist. In most cases, it is really easy to check for possible null values just by looking at the pull request, even without an IDE. Recently, we received help when Microsoft introduced nullable reference types. So, now, the compiler will join us in the search of possible disasters causedby null.What are nullable reference types?In the simplest terms,Nullable Reference Types(orNRTsfor short) are a feature in C# that allows developers to clearly indicate whether a reference type can be null or not. With this, C# gives us a tool to make our intentions clear right from the start. Think of it as a signpost, guiding other developers (and even our future selves) about what to expect fromour code.Without NRTs, every reference type in C# could potentially benull. This would create a guessing game. Is this variable going to have a value or is it going to benull? Now, with NRTs, we don’t have to guess anymore. The code itself tellsthe story.Let’s look at a basic example to graspthe concept:string notNullable = "Hello, World!";string? nullable = null;In the preceding snippet, thenotNullablevariable is a regular string that can’t be assignednull(if you try, the compiler will warn you). On the other hand, since C# 8.0, nullable is explicitly marked with?, indicating that it canbenull.In some cases, you might want to assignnullto a variable that is not marked as nullable. In this case, to suppress warnings, you can use the! sign to let the compiler know that you are aware of what you are doing and everything is going according to plan:string notNullable = "Hello, World!";notNullable = null!;One of the biggest advantages of NRTs is that the C# compiler will warn you if you’re potentially doing something risky with null values. It’s like having a friendly guide always looking over your shoulder, ensuring you don’t fall into the common traps ofnull misuse.For instance, if you try to access properties or methods on a nullable reference without checking fornull, the compiler will give you a heads-up.Transitioning to NRTsFor those with existing C# projects, you might be wondering:Will my project be littered with warnings if I enable NRTs?The answer is no. By default, NRTs are turned off. You can opt into this feature, file by file, allowing for asmooth transition.NRTs are a good answer to the long-standing challenge posed by null references. By making the potential presence of null explicit in our code, we take a giant leap toward clarity, safety, and functional honesty. In the end, embracing NRTs not only makes ourcode more resilient but also ensures that our intentions, as developers,are transparent.Enabling nullable reference typesTo enable NRTs, we need to tell the C# compiler that we’re ready for its guidance. This is done using a simple directive:#nullable enable.Place this at the start of your.csfile:#nullable enableFrom this point onward in the file, the compiler creates a specific nullable context and assumes that all reference types are non-nullable by default. If you want a type to be nullable, you’ll have to mark it explicitlywith?.With NRTs enabled, the C# compiler becomes your safety net, pointing out potential issues with nulls in your code. Whenever you try to assign null to a reference type without the?marker or when you attempt to access a potentially null variable without checking it, the compiler willwarn you.Here’san example:string name = null; // This will trigger a warningstring? maybeName = null; // This is okayDisabling nullable reference typesWhile transitioning a project to use NRTs, there may be sections of your code where you’d prefer to delay the transition. You can turn off NRTs for those specific sections using the #nullable disabledirective:#nullable disableThis tells the compiler to revert to the old behavior, treating all reference types aspotentially nullable.You might wonder why C# chose to use directives for this feature. The reason is flexibility. By using directives, developers can gradually introduce NRTs into their projects, one file or even one section of code at a time. This phased approach makes it easier to adaptexisting projects.Warnings and annotations optionsSpeaking of a phased approach, there are two more options to set our nullable contexts:warningsandannotations. You can use them by writingthe following:#nullable enable warningsOr, you canwrite this:#nullable enable annotationsThe main purpose of these options is to ease the migration of your existing code from a fully disabled null context to a fully enabled one. In short, we want to start with thewarningsoption in order to get dereference warnings. When all warnings are fixed, we can switch toannotations. This option will not give us any warnings, but it will start to treat our variables as non-nullable unless declared with the?mark.To get more information about these options and nullable context in generated files, and to find out more about three nullabilities – oblivious, nullable, and non-nullable, I recommend you read the article "Nullable reference types". You might also want to read the article “Update a codebase with nullable reference types to improve null diagnostic warnings”.Functional Programming with C# was published in July 2024. Packt library subscribers can continue readingthe entire book for free or you can buy the bookhere!Get the eBook for $38.99$26.99🛠️Useful Tools⚒️teable: a no-code database platform that combines the ease of a spreadsheet interface with the performance of a database, enabling users to create and manage applications without coding.RealtimeSanitizer (a.k.a. RTSan): a real-time safety testing tool for C and C++ projects that detects and raises errors when non-deterministic functions are called within real-time contexts.Rspack 1.0: a Rust-based JavaScript bundler, fully compatible with the webpack API, offering much faster performance than webpack while supporting modern web standards and improving build efficiency.awesome-decentralized-autonomous-organizations: a curated list of resources and projects for decentralized autonomous organizations (DAOs) to help users start and participate in their own DAOs.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 usefulhere. Complete ProgrammingPro archives can be foundhere. Complete PythonPro archives arehere.If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want toadvertise with us.If you have any comments or feedback, just respond to this email.*{box-sizing:border-box}body{margin:0;padding:0}a[x-apple-data-detectors]{color:inherit!important;text-decoration:inherit!important}#MessageViewBody a{color:inherit;text-decoration:none}p{line-height:inherit}.desktop_hide,.desktop_hide table{mso-hide:all;display:none;max-height:0;overflow:hidden}.image_block img+div{display:none}sub,sup{line-height:0;font-size:75%}#converted-body .list_block ol,#converted-body .list_block ul,.body [class~=x_list_block] ol,.body [class~=x_list_block] ul,u+.body .list_block ol,u+.body .list_block ul{padding-left:20px} @media (max-width: 100%;display:block}.mobile_hide{min-height:0;max-height:0;max-width: 100%;overflow:hidden;font-size:0}.desktop_hide,.desktop_hide table{display:table!important;max-height:none!important}.reverse{display:table;width: 100%;
Read more
  • 0
  • 0
  • 13887
Success Subscribed successfully to !
You’ll receive email updates to every time we publish our newsletters.