Enjoy these free Code Nuggets?

Your support helps us create more high-quality content and unlocks exclusive premium nuggets via a personal activation link.

Support Our Work & Get Exclusive Access
πŸ€– New β€” AI Training

Learn to code with AI, not just about it.

Beyond free snippets, we run hands-on training in AI-assisted coding β€” teaching developers, teams and beginners how to build real software faster using modern AI tools. You bring the ideas; we show you how to ship them with an AI pair-programmer at your side.

  • βœ” Prompting & pairing with AI coding assistants to write, debug and refactor real code
  • βœ” Turning plain-English ideas into working apps, scripts and automations
  • βœ” Reviewing AI output safely β€” spotting bugs, security gaps and hallucinations
  • βœ” Live cohorts, team workshops and 1-on-1 mentoring β€” remote or on-site in Kenya
ai-pair-session.md

# You describe it…

"Build me a booking form that emails the client."

# …the AI drafts it…

β–Έ generating form + mailer…

β–Έ 24 lines written, 0 errors

# …and we teach you to lead it.

✱ You stay the engineer. AI is the tool.

All Code Nuggets

41 nuggets found

Hooking Business Logic with AL Event Subscribers (Premium)

Event subscribers are how you react to platform actions without touching base code. Subscribe to a published event β€” like validating a field β€” and run your own logic when...

codeunit 50100 "Loyalty Events"
{
    [EventSubscriber(ObjectType::Table, Database::"Sales Header",
        'OnAfterValidateEvent', 'Sell-to Customer No.', true, true)]
    local procedure OnValidateCustomer(var Rec: Record "Sales Header")
    var
        Cust: Record Customer;
    begin
        if...

Immutable Value Objects with readonly Properties (Premium)

PHP php

PHP 8.1 introduced readonly properties. Combined with constructor promotion, they let you build small value objects that cannot be mutated after creation β€” fewer bugs, clearer intent.

final class GeoPoint
{
    public function __construct(
        public readonly float $lat,
        public readonly float $lng,
    ) {}

    public function distanceTo(GeoPoint $other): float
    {
        $r = 6371; // km
        $dLat = deg2rad($other->lat - $this->lat);
        $dLng = deg2rad($...

Transforming Arrays with map, filter and reduce (Premium)

PHP php

Loops that build up a result variable are easy to get wrong. PHP's array functions let you describe what you want β€” transform, keep, or fold β€” in a single...

$orders = [
    ['item' => 'Pen',    'qty' => 3, 'price' => 50],
    ['item' => 'Book',   'qty' => 1, 'price' => 400],
    ['item' => 'Marker', 'qty' => 5, 'price' => 80],
];

// Only orders worth 200+, as "item: total"
$lines = array_map(
    fn ($o) => "{$o['item']}: " . ($o['qty'] * $o['price']),...

Concise Models with Records and Pattern Matching (Premium)

C# csharp

C# records give you immutable data types with value equality in one line. Pair them with switch expressions and pattern matching for branching that stays flat and readable.

public record Shape;
public record Circle(double Radius) : Shape;
public record Rectangle(double Width, double Height) : Shape;

static double Area(Shape shape) => shape switch
{
    Circle c            => Math.PI * c.Radius * c.Radius,
    Rectangle r         => r.Width * r.Height,
    _...

A Tiny HTTP API with ASP.NET Minimal APIs (Premium)

C# csharp

You do not need controllers and a pile of ceremony to expose an endpoint. Minimal APIs let you map routes to lambdas, wire up dependency injection, and return JSON in...

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IPatientStore, PatientStore>();
var app = builder.Build();

app.MapGet("/patients", (IPatientStore store) => Results.Ok(store.All()));

app.MapGet("/patients/{id:int}", (int id, IPatientStore store) =>
    store.Find(id)...

Composable Request Handling with Express Middleware (Premium)

Node.js javascript

Express middleware are just functions that run in order on every request. Chain them to add logging, authentication and error handling without repeating yourself in each route.

const express = require("express");
const app = express();

// Simple request logger
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Reusable auth guard
function requireAuth(req, res, next) {
  if (!req.headers.authorization) return res.status(401).json({ e...

Processing Large Files with Node.js Streams (Premium)

Node.js javascript

Reading a whole file into a Buffer does not scale. Streams process data piece by piece and can be piped together, so you can transform gigabytes with a tiny, constant...

const fs = require("fs");
const zlib = require("zlib");
const { pipeline } = require("stream/promises");
const { Transform } = require("stream");

// Uppercase each chunk as it flows through
const upper = new Transform({
  transform(chunk, _enc, cb) {
    cb(null, chunk.toString().toUpperCase());...

Keeping Controllers Skinny with Service Objects (Premium)

When a controller action does five things, it becomes hard to test and reuse. A service object captures one business operation in a single, callable class you can test in...

# app/services/register_patient.rb
class RegisterPatient
  def self.call(**args) = new(**args).call

  def initialize(name:, email:)
    @name = name
    @email = email
  end

  def call
    patient = Patient.create!(name: @name, email: @email)
    WelcomeMailer.with(patient: patient).greeting.deliv...

Readable Queries with ActiveRecord Scopes (Premium)

ActiveRecord scopes name your common queries so they read like intent, not SQL. They are chainable, composable, and keep filtering logic on the model where it belongs.

class Appointment < ApplicationRecord
  scope :upcoming,  -> { where("starts_at > ?", Time.current) }
  scope :for_doctor, ->(doctor) { where(doctor: doctor) }
  scope :confirmed, -> { where(status: :confirmed) }

  # Combine scopes into a higher-level one
  scope :doctor_agenda, ->(doctor) { upcomi...