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