ProgrammingPro #34: Flutter for the Web, AI Coding Assistants Gone Rogue, and the New Coding Interview!
Bite-sized actionable content, practical tutorials, and resources for programmers
"Unix was built for me. I didn't build it as an operating system for other people; I built it to do games and to do my stuff. I was always into games; games were my thing."
– Ken Thompson (2019), Pushing the Limits of Technology: The Ken Thompson and Dennis Ritchie Story
The principles and design concepts of Unix have influenced the development of various widely used modern operating systems like Lunux. Not bad for a personal project huh? Welcome to today’s issue of ProgrammingPro!
News Highlights: In 2024, Forrester predicts three major breaches tied to flaws in AI-generated code. Microsoft's bug bounty program celebrates a decade of $63 million in payouts, but questions linger about its impact on software security. Java's Project Valhalla aims to bridge primitive-object gaps, shaping the language's future.
And here are my top 5 picks from today’s learning resources:
🐍How to use Python's new monitoring API, for more performant debugging and monitoring
🛠️Enhancing Readability in C++23 with \N Escapes for Unicode Characters
Improve Runtime Type Safety with Branded Types in TypeScript🎛️
And, yes, we have an exclusive excerpt for you in our Expert Insight section from the Flutter Cookbook - Second Edition that will teach you how to create a responsive Flutter app that can be run on the web, addressing considerations like adjusting the UI for larger screens and solving Cross-Origin Resource Sharing (CORS) issues when loading images, using practical steps and code examples. So dive right in!
Stay awesome!
Divya Anne Selvaraj
Editor-in-Chief
PS: We received quite a few tutorial requests last week of which several were Python related. We will cover these in our next issue of PythonPro. If you haven’t subscribed yet, subscribe here, or visit the archives here. Also, would you like us to start a game development focused newsletter? Let us know in today’s survey. Anything apart from these which we haven’t covered this week will be covered in next week’s issue.
🗞️News, 💡Opinions, and 🔎Analysis
🗞️News
AI coding assistants — A double-edged sword for DevOps in 2024: Forrester predicts flaws in AI-generated code may lead to 3 breaches in 2024, and threaten API security. Read to learn why the trend of 'Shadow IT,' where teams experiment with various assistants, poses challenges in maintaining cybersecurity standards.
TypeScript 5.3 arrives with support for import attributes: The release improves TypeScript's ability to inspect super property accesses, enhances inlay hints, and optimizes parsing time when running TypeScript via tsc, and more. Read to learn about the latest features including ECMAScript import attributes.
Microsoft's bug bounty turns 10. Are these kinds of rewards making code more secure?: Microsoft's bug bounty program has payed out $63 million over the past decade, with $60 million awarded in the last five years. Read to learn why Katie Moussouris, a key figure in establishing the program, argues that the rise of bug bounty platforms hasn't necessarily made software more secure.
Project Valhalla: A look inside Java’s epic refactor: The project is a significant Java language refactor aimed at addressing performance issues stemming from the design decision that treated everything in Java as an object, except for primitives like int. Read to learn more about the overhaul which introduces value classes and primitive classes, bridging the gap between primitives and objects.
Apple’s Objective-C ‘appears to be reaching its end of life’ – or so says JetBrains survey: JetBrains' State of Developer Ecosystem report suggests Apple's Objective-C is nearing its end of life, with just 2% of developers using it and none planning to adopt it. Read to learn how the rise of Swift and the availability of cross-platform languages targeting iOS like Kotlin and Dart is leading to this.
OpenAI researchers warned board of AI breakthrough ahead of CEO ouster, sources say: We just had to include a link for you about what’s buzzing. OpenAI researchers reportedly warned the board of directors about a significant AI discovery, with potential risks to humanity. Read to know more about the alleged breakthrough which involves a project called Q* (Q-Star), aiming for artificial general intelligence (AGI) with enhanced reasoning capabilities in mathematics.
💡Opinions and Analysis🔎
The Most Valuable Code Is the Code You Should Not Write: The author argues that as AI becomes proficient in coding, traditional coding skills may become less relevant. Read to learn why they suggest a shift towards evaluating programmers based on decision-making and problem-solving skills rather than coding prowess.
Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone: This article critiques the concept of the test pyramid, arguing that it doesn't consider all aspects of testing. Read to learn why the author recommends a more comprehensive approach using mutation testing for efficient bug detection and emphasizes the importance of optimizing test design for each level independently.
Why I think C++ is still a desirable coding platform compared to Rust: The author questions the tangible benefits of Rust's safety features in practical scenarios and concludes that, for now, transitioning to Rust may not be worth the effort. Read to learn why they believe C++ remains more desirable for low-latency trading.
A Comprehensive Approach to Performance Monitoring and Observability: This article describes the shift from traditional APM tools to a modern observability approach. Read for insights into modern observability practices, data quality optimization, and the collaborative role of monitoring and observability in building efficient application performance monitoring frameworks.
React memo is good actually: This article discusses the positive aspects of React.memo, React.useMemo, and React.useCallback for performance optimization in React applications. Read to understand common misconceptions and challenges, and the benefits of these APIs when used strategically.
🎓 Tutorials and Guides🤓
How to use Python's new monitoring API, for more performant debugging and monitoring: This video tutorial covers Python's new monitoring API in version 3.12. Watch to gain insights into efficient event hooking, behavior monitoring, and the creation of powerful profiling and coverage tools, demonstrated through a practical example and exploration of PEP 669.
C++ with Nix: Package Generation and Cross-Compilation: This guide takes you through creating a Nix package for a real world C++ application, enabling you to build and run it effortlessly. Read to master packaging and cross-compilation, and leverage Nix features for streamlined C++ development.
Implementing a simple garbage collector in C#: This series of 7 articles exhaustively takes you through garbage collection in C#, aiming to reimplement the .NET framework's garbage collector with step by step code examples. Read to understand the theoretical concepts, address challenges, and gain insights into memory management principles.
Spoofing Objective-C return values on Apple Silicon using LLDB: This article demonstrates using LLDB to manipulate Objective-C function return values on Apple Silicon using LLDB commands and highlights applicability to Swift. Read for insights into ARM architecture, details on procedure calls, and provides examples of spoofing scalar and object return values in Objective-C methods.
Live (re)compile, (re)load, (re)execute Java code in 100 LoC: This article
introduces "The Reloader" program which allows automatic recompilation, reloading, and execution of Java code upon file changes. Read for an illustrated PlayWithNumbers example which enables live coding with features such as detecting modifications, compiling, and reloading classes dynamically.Generating Secure Random Numbers in TypeScript: This article explains generating secure random numbers by leveraging JavaScript's typed arrays. Read for a guide that covers determining the range, selecting an appropriate typed array, and optimizing performance using code examples for practical applications like unique IDs and secure passphrases.
How to Use Node.js with Docker: This guide walks through creating a basic Node.js script, running it locally, and then containerizing it with Docker. Read for suggestions for a better development workflow, utilizing Docker Compose for live application restarts and debugging with VS Code.
A Guide to Shifting Left in the Software Development Lifecycle with Automation Tools: This guide highlights the importance of early identification and resolution of vulnerabilities. Read for insights into automation tools, such as Helix ALM, Helix QAC, and more, and continuous testing, test management, continuous security, secure coding standards, static analysis, and development at scale.
Getting Started with Raylib for Game Development in C++: The guide covers setting up Raylib, the basic program structure, drawing shapes, handling events, and includes a bonus code for a basic chasing game. Read for essential concepts, code examples, and build a foundation for creating your own games.
🔑 Secret Knowledge: Learning Resources🔬
Enhancing Readability in C++23 with \N Escapes for Unicode Characters: This new feature allows the use of \N{NAME} in source code to represent a single Unicode character, simplifying the inclusion of special characters like emojis. Read to learn more about this universally-readable solution, although its support is dependent on both the C++ standard and the compiler version.
The Role of Guidelines in C++ Development: This article discusses the importance of guidelines in C++ coding, emphasizing both automated tools like clang-format and non-automated guidelines for consistent and readable code. Read to learn how documenting and automating coding styles enhances communication and collaboration among developers.
Understanding Stack and Queues in JavaScript: This article demonstrates the significance of the principles, use cases, and implementation of stacks and queues in JavaScript, in memory management, undo features, and scenarios like shared printers. Read for detailed explanations and code examples.
Messin’ around with web components. Also—JavaScript, generally: This article exhaustively explores web components and JavaScript, focusing on the usage of custom elements (web components) through a code example. Read for insights constructor functions, the "new" keyword, and the concept of classes as a syntactic sugar for constructor functions, and much more.
Improve Runtime Type Safety with Branded Types in TypeScript: This article introduces Branded Types which add specificity and uniqueness to data types by incorporating labels and prevent interchangeable use of basic types. Read to learn about type ambiguity, and discover a better implementation using unique symbols.
3 key lessons in Node.js server optimization: This article discusses key lessons learned during a six-week effort to optimize Graphite's Node.js application server, focusing on verifying impact precision, addressing event loop blockers, and prioritizing optimizations based on real impact. Read to gain insights into Node.js server optimization and make informed prioritization decisions.
The Best Node.js Headless Browsers for Web Scraping: This article explores top Node.js headless browsers for web scraping, including Puppeteer, Playwright, ZombieJS, CasperJS, and Nightmare.js. Read for detailed use cases, advantages, and code examples.
💎Ruby Tip💎 — Interactive debugging without the need for gems: This article introduces a Ruby debugging tip using the Binding class and the integrated IRB console. Read to discover a straightforward alternative to installing additional gems for interactive debugging.
The Ultimate HTML::Parser Perl Cheat Sheet: The article provides an extensive cheat sheet, covering installation, parsing HTML from different sources, accessing elements, manipulating HTML, handling events with handlers, and more. Read for best practices, troubleshooting, and customization options for the HTML::Parser module.
🧠 Expert Insight 📚
Here’s an excerpt from “Chapter 15,
Flutter Web and Desktop” in the book Flutter Cookbook - Second Edition by Simone Alessandria.
Creating a responsive app leveraging Flutter Web
Running a web app with Flutter might be as simple as running the flutter run -d chrome command on your Terminal. In fact, most of the apps you create with Flutter may also run on the web without
any change, but some plugins might only
work for specific platforms, and you may
need to adjust the UI for larger screens.
In this recipe, you will see how to make your layout responsive, building your app so that it can later be published to any web server. You will also see how to solve a Cross-Origin Resource Sharing (CORS) issue when loading images.
You will build an app that retrieves data from the Google Books API and shows text and images. After running it on your mobile emulator or device, you will then make it responsive so that when the screen is large, the books will be shown in two columns instead of one.
Getting ready
There are no specific requirements for this recipe, but in order to debug your Flutter apps for the web, you should have the Chrome browser installed. If you are developing on Windows, Edge will work as well.
How to do it...
In order to create a responsive app that also targets the web, follow these steps:
Create a new Flutter project and call it books_universal.
Add the latest version of the http package by typing in your Terminal:
flutter pub add http
In the lib directory of your project, create three new directories called models, data, and screens.
In the models directory, create a new file called book.dart.
In the book.dart file, create a class called Book, with the fields specified here:
class Book {
final String id;
final String title;
final String authors;
final String thumbnail;
final String description;
}
In the Book class, create a constructor that sets all the fields:
const Book(this.id, this.title, this.authors, this.thumbnail, this.description);
Create a named factory constructor, called fromJson, that takes a Map and returns a Book, as shown in the code sample:
factory Book.fromJson(Map<String, dynamic> parsedJson) {
final String id = parsedJson['id'];
final String title = parsedJson['volumeInfo']['title'];
String image = parsedJson['volumeInfo']['imageLinks'] == null
? '' : parsedJson['volumeInfo']['imageLinks']['thumbnail'];
image.replaceAll('http://', 'https://');
final String authors = (parsedJson['volumeInfo']['authors'] ==
null) ? '' : parsedJson['volumeInfo']['authors'].toString();
final String description =
(parsedJson['volumeInfo']['description'] == null)
? ''
: parsedJson['volumeInfo']['description'];
return Book(id, title, authors, image, description);
}
In the data directory, create a new file and call it http_helper.dart.
At the top of the http_helper file, add the required import statements, as shown here:
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart';
import '../models/book.dart';
Under the import statements, add a class and call it HttpHelper:
class HttpHelper {}
In the HttpHelper class, add the strings and Map required to build the Uri object that will connect to the Google Books API:
static const String authority = 'www.googleapis.com';
static const path = '/books/v1/volumes';
Still in the HttpHelper class, create a new asynchronous method, called getBooks, that takes a String for the query and returns a Future of a List of Book objects, as shown here:
Future<List<Book>> getBooks(String query) async {
Map<String, dynamic> params = {
'q': query,
'maxResults': '40',
};
Uri uri = Uri.https(authority, path, params);
Response result = await http.get(uri);
if (result.statusCode == 200) {
final jsonResponse = json.decode(result.body);
final booksMap = jsonResponse['items'];
List<Book> books = booksMap.map<Book>((i) =>
Book.fromJson(i)).toList();
return books;
} else {
return [];
}
}
In the screens directory, create a new file called book_list_screen.dart.
At the top of the book_list_screen.dart file, add the required imports:
import 'package:flutter/material.dart';
import '../models/book.dart';
import '../data/http_helper.dart';
Under the import statements, create a new stateful widget and call it BookListScreen:
class BookListScreen extends StatefulWidget {
const BookListScreen({super.key});
@override
State<BookListScreen> createState() => _BookListScreenState();
}
class _BookListScreenState extends State<BookListScreen> {
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
At the top of the _BookListScreenState class, create two variables: a List of books called books, and a Boolean called isLargeScreen:
List<Book> books = [];
In the _BookListScreenState class, override the initState method, and then call the getBooks method to set the value of the books variable, as shown here:
@override
void initState() {
super.initState();
final HttpHelper helper = HttpHelper();
helper.getBooks('flutter').then((List<Book> value) {
setState(() {
books = value;
});
});
}
At the top of the build method, use the MediaQuery class to read the width of the current device, and based on its value, set the isLargeScreen Boolean to true when the number of device-independent pixels is higher than 600:
bool isLargeScreen;
if (MediaQuery.of(context).size.width > 600) {
isLargeScreen = true;
} else {
isLargeScreen = false;
}
Still in the build method, return a Scaffold that, in its body, contains a responsive GridView. Based on the value of the isLargeScreen variable, set the number of columns to 2 or 1, and childAspectRatio to 8 or 5, as shown in the following code sample:
return Scaffold(
appBar: AppBar(title: const Text('Books')),
body: GridView.count(
childAspectRatio: isLargeScreen ? 8 : 5,
crossAxisCount: isLargeScreen ? 2 : 1,
children: List.generate(books.length, (index) {
return ListTile(
title: Text(books[index].title),
subtitle: Text(books[index].authors),
leading: CircleAvatar(
backgroundImage: (books[index].thumbnail) == '' ? null :
NetworkImage(books[index].thumbnail),
),
);
}))
);
Edit the main.dart file so that it calls the BookListScreen widget:
import 'package:flutter/material.dart';
import 'screens/book_list_screen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const BookListScreen(),
);
}}
Run the app on your mobile device. You should see an app screen similar to the screenshot:
Figure 15.1: App on a mobile device
Stop the app, and run it on Chrome; you can select the device in your editor, or in the Terminal window in your project’s directory, run the command:
flutter run -d chrome
Note that the app is running on your web browser and showing two columns, but the images are not showing:
Figure 15.2: App in a browser — images are not showing
Stop the app.
In the Terminal, run the following command:
flutter run -d chrome --web-renderer html
This time, note that the images show correctly:
Figure 15.3: App in a browser, with images showing
Flutter Cookbook - Second Edition by Simone Alessandria was published in May 2023. You can read chapter 1 for free and buy the book here.
🛠️ Useful Tools ⚒️
IWYU (Include What You Use): an open source Clang-based tool for C and C++ code analysis, designed to optimize and manage #include directives by identifying and suggesting fixes for unnecessary or missing headers in source files.
worker: a PostgreSQL job queue for Node.js, facilitating background task execution to prevent delays, compatible with any PostgreSQL-backed app, and sustained through crowd-funded open-source development.
fuzzy_ruby_server: a high-performance Ruby language server with fuzzy search, supporting definitions, diagnostics, references, highlights, and renaming; compatible with VSCode and Neovim.
fury: a high-performance serialization framework with just-in-time compilation and zero-copy, offering up to 170x speed improvement with support for multiple languages and seamless integration with Java serialization frameworks.
refine: a headless React framework facilitating rapid web application development with decoupled business logic and customizable styling options.
We have an entire range of newsletters with focused content for tech pros. Subscribe to the ones you find the most useful here. Complete ProgrammingPro archives can be found here. Complete PythonPro archives are here.
📢 If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want to advertise with us.
If you have any feedback, leave your comments below!