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

32 Articles
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
  • 1412

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
  • 11387
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.
Success Subscribed successfully to !
You’ll receive email updates to every time we publish our newsletters.