AI 资讯
Delegating to AI Means Governing the Environment
In the previous article , I argued that AI isn't simply changing the tools we use to develop software, but shifting our work to a new level of abstraction. In this one, I want to address the problem that immediately follows: if we're going to write less and less code directly and agents are going to produce an increasingly larger part of it, how the hell do we know whether what they code is actually right? Because the answer obviously can't be “trust the AI, it's very smart”. Even though I personally develop code with AI today with practically no review, I don't blindly trust AI. Just as I don't blindly trust an engineer on my team. I don't even blindly trust myself. Blind trust is a security hole. And not blindly trusting someone doesn't mean distrusting them, it means having mechanisms to prevent their mistakes, or mine, from causing problems. That's why we've spent decades building mechanisms and methodologies around software development to detect, and avoid as much as possible, our mistakes. XP. Scrum. Tests. Code reviews. Pair Programming. CI. Static analysis. Permissions. Observability. Environments. Containers. Auditing... The question, therefore, shouldn't be whether we can trust an AI. The question should be what system do we need to build so we can use it without needing to blindly trust it? It's not deterministic One of the first objections is usually that if you ask it the same thing twice, it generates two different pieces of code. True. But if you give the same task to two different programmers, or to the same programmer with enough time in between, we'll very probably get two different implementations too, depending on the complexity of what we're asking. And if we've never required two developers to produce exactly the same code, why do we expect AI to produce exactly the same code from the same request? Isn't it enough for the result to satisfy the requested requirements? That it does what it's supposed to do. That it passes all kinds of tests. That
AI 资讯
I Built This to Fix One Task. It Turned Into Something You Can Run.
There are two ways to work with an AI agent and I had tried both. Write the thing yourself and hand over only the tedious parts. Or hand over the whole task and audit whatever comes back at the end. The first is slow. The second is fast right up until it is wrong, and by then the wrong thing is finished. I expected this series to be about forcing a third option into existence. Nine parts of making an agent follow a workflow it would rather skip. That is not what happened. I never had to enforce it once. The queue that started this had a payload contract nobody had verified, and each phase after that cost me something before it gave anything back. A plan that would not move until the risk register named the provider contract the brief had only guessed at. A build that missed nothing except what my own brief left out. A review that stopped handing back a feeling and started handing back a verdict on every requirement I had already called done. A matrix instead of a trusted green run. A rollback with a name on it before anything got called shipped. And a retrospective that would not let a lesson through until it had checked itself against the trail. Eight parts of that. What I did not expect was which part turned out to be automatic. The Fight I Expected Never Started By the time I finish writing a requirement, I already know roughly what it is going to cost. Most engineers do. You can feel the difference between a one-line fix and something that is going to touch four files and a migration before you have written a single line of it. What I assumed was that the agent could not feel that, and that policing the gap would be my job forever. Reminding it to run the chain. Catching it when it decided a spike was small enough to skip. It has not needed the reminder. Small bugs do not trigger a brief and a plan, and they should not. A standard requirement, a spike, anything long or cross-cutting, runs the full cycle in order. The classification lands where I would have put i
AI 资讯
Processes vs Threads
📺 Prefer to watch? 90-second YouTube Short · 💬 Telegram Originally published on software-engineer-blog.com . You run code concurrently all the time. But "concurrent" hides a critical choice: are you spawning separate processes or threads inside the same process? That choice decides whether one crash takes down your entire system or stays contained, and whether you're copying data between isolated worlds or racing to read the same memory. Mental model: A process is its own house; threads are roommates sharing one. Processes: Isolation at the Cost of Weight When you start a process, the operating system hands it its own private address space. That address space is walled off. Your process can't touch another process's memory—the OS enforces it at the CPU level. If your process crashes, it corrupts only its own memory. The kernel cleans it up. Every other process keeps running untouched. This is why browsers put each tab in its own process. One tab runs malicious JavaScript, spins into an infinite loop, or has a memory leak—that tab's process dies. The rest of your browser lives. You close the dead tab and open a new one. Your other tabs don't even hiccup. But isolation isn't free. Each process carries: Its own copy of the heap, stack, and memory pages Its own file descriptor table, open sockets, and kernel resources OS overhead to track and protect it Spawning a process is expensive—milliseconds on modern hardware, but measurably heavier than a thread. And if two processes need to share data, they can't just read the same memory. One process must copy data into a pipe or socket, send it across, and the other process must copy it out and into its own memory. That's overhead on every exchange. Threads: Speed and Sharing, With a Trap Threads live inside a single process and share that process's entire memory. The kernel doesn't wall them off from each other. When you spawn a thread, you're not duplicating the heap, the file descriptors, or the kernel state—you're just cr
AI 资讯
The automation post pipeline
I am testing my first automated end to end social media post automation system. which is created using the free tools. But it is very efficient and productive. i can use this thing in future posting on various platforms to tell people about my learning's and update about me. Tools : Make.com = I use this tool to mainly automate my system it include flow how things works and system is linked. Hashnode = I use this as a central blog and article publishing tool other tools is connected with it so content links is properly distributed. Google Ai Studio = I use this to integrate the ai in between this whole process which just do small job to add the engaging hook and the tags for the reach Buffer = I use to connect X (twitter) with this Because Make.com remove the platform X (twitter) to His integration. After the policy change of the platform. Dev.to = I use this to improve SEO of my post over the google search engine. Challenges : I cannot integrate the github actions with the hashnode becuase this feature is become paid on hashnode. May be in future i can do this thing using self written yml file, i am guessing Not sure will this 100 % work or not. Twitter integration as i described early that twitter integration is not present in the make.com so i use the another tool Buffer. The limits calculation, Their was a limits on each tools for their specific use case so i have to intentionally calculate them properly. Even the free tear of the twitter which is X is few hundreds words that's why i have to limit the text of the post, which is hook only, The threads creation i don't think it will be their in this tools which i am using, i will definitely find it if their. Solutions : Simply use other Way if this way is closed, use different tool for twitter May be in future i create yml file for the github actions but for now i am directly writing on hashnode. The dev.to does not provide feature of direct posting it save your cycle into draft so you have to manually click on pu
AI 资讯
Architectural Foundation: The Host-Guest Split
A compiled application cannot hot-reload itself if its main loop, window context, and memory allocations live inside the binary being recompiled. The application must be split into two layers:Host Shell (Stable Execution Root):Statically compiled once.Manages the OS window, render loop, event polling, network sockets, and high-level heap allocations.Exposes a dynamic symbol loader (dlopen / LoadLibrary or a dynamic WebAssembly runtime execution context).Guest Module (Hot-Swappable Logic):Compiled as a shared dynamic library (.so, .dylib, .dll) or an isolated WebAssembly (.wasm) module.Contains frame updates, business rules, rendering instructions, and component tree logic.Exports explicit interface hooks (init, update, render, pre_reload, post_reload).The Hot-Reload PipelineWhen a developer edits source code in a compiled language (e.g., modifying a Rust UI render function or a C# algorithm), the dev server orchestrates a zero-downtime swap through this explicit pipeline:1.File Watcher & Fast Incremental Compile:Sub-second artifact generation.The watcher detects source changes and invokes an incremental compilation pass using dynamic linking configurations (e.g., -rdynamic, dynamic C-runtime links, or fast lld/mold linkers) to output a versioned binary artifact (logic_v2.so).2.Live Manifest Update:Atomic state & symbol mapping emit.The dev server emits an updated JSON manifest containing module hash, exposed symbol tables, binary payload locations, and updated asset hashes over a WebSocket/IPC stream to the Host Shell.3.State Snapshot & Freeze:Preserving user context.The Host Shell signals pre_reload() to the currently loaded logic_v1.so. The guest logic serializes volatile runtime state into a host-managed memory buffer or leaves pointers active inside a host arena.4.Dynamic Unload & Library Swap:Operating system symbol rotation.The Host Shell unloads logic_v1.so (releasing file locks via temporary copy paths on OS platforms like Windows), loads logic_v2.so, and re
AI 资讯
Why stock backtesting results deviate: The hidden pitfalls of API timestamp handling
When building and validating US stock quantitative strategies, I used to focus solely on core market data metrics. Like most individual quantitative developers, I prioritized the integrity of price candlesticks and trading volume data, assuming that complete K-line datasets would guarantee reliable backtesting outcomes that align with real-market performance. This assumption held true for small-scale tests and short-cycle verification, until I encountered persistent inconsistencies between historical backtest reports and live trading results. After thorough troubleshooting of strategy logic, parameter settings, and sliding point simulation, I finally pinpointed the root cause — inconsistent and inaccurate timestamp processing from market data APIs, a trivial-looking but critical engineering detail that most developers overlook. Most engineering teams devote massive effort to verifying the accuracy of US stock API quote data, yet ignore standardized processing for time fields. In quantitative trading systems, timestamp offset and timezone disorder are far more impactful than superficial chart display errors. They directly distort candlestick combinations, disrupt technical indicator calculations, and ultimately mislead the entry and exit signal judgments of trading strategies. Core Requirement: Time-series consistency for valid backtesting Market data is essentially a continuous time-series stream, where price and volume merely represent transaction outcomes at specific timestamps. The time dimension acts as the fundamental anchor that defines the exact position of every single trade in the market timeline. Unlike A-share market data that adopts a unified time standard, US stock data providers deliver multiple incompatible time formats across different APIs, including pure UTC time, US Eastern trading time, and original exchange timestamp fields. Without unified parsing and conversion logic in your program, timestamp misalignment and data dislocation are inevitable.
AI 资讯
The Lombok Illusion (Chapter 5)
You open a new Spring Boot project and you create a DTO, then an entity, and you’re staring at getters, setters, constructors, equals() , hashCode() , toString() . Someone on the team suggests to put lombok’s @Data , or “just slap @Builder on it, it’ll be cleaner.” Forty lines become five and it looks great in the PR. Then it hits a real codebase, OpenAPI generation doesn't behave the way the build expects. Hibernate meets an auto-generated equals() and gets confused about identity. Something throws through a generated builder hierarchy at 2 AM, and the method you need to inspect doesn't exist in any file you can open. Eleven years into enterprise Java, my rule is simple: Lombok doesn't touch core application behavior. Not because writing a getter is interesting - it isn't, but because the handful of lines it saves rarely covers the compiler magic, tooling friction, and debugging problems it adds to something that has to survive for years after you've moved on to another project. "It just removes boilerplate" Worth asking what's actually being removed, though. A getter is part of your public API. A setter is a mutation point someone decided to expose. A constructor defines what states an object is allowed to enter. equals() and hashCode() define identity. toString() is what shows up in your logs when things go wrong at 3 AM. Write those by hand and they live in the source - visible, searchable, debuggable, owned by whoever's reading the file. Generate them with Lombok and the behavior is still there, it's just moved somewhere you can't see it without a separate step. The annotation most people reach for first time is @Data : @Data @Entity public class CustomerEntity { @Id @GeneratedValue private Long id ; private String email ; @OneToMany ( mappedBy = "customer" ) private List < OrderEntity > orders ; } One line and you get getters, setters, toString() , equals() , hashCode() across every field. For a JPA entity that's already a problem before you've written any bus
AI 资讯
Grep won't find your dead gates. A fill-rate query will.
Originally published on hexisteme notes . A predecessor note diagnosed three production features that passed every dedicated unit test and never executed at all, and why a unit test structurally can't see that gap. That note answered three cases I already knew about, because I'd already tripped over them. It didn't answer the question that matters once you've found three: how do you find the rest — the ones nobody happened to notice yet? This is that search: the tool that actually works, what it found across seven projects, and a fourth failure shape that the predecessor note's two fixes don't reach at all, because in that fourth shape the code was never the thing that was broken. The query, before the argument Before any of the specifics, here is the shape of the query, so you can run something like it against your own tables in under a minute: SELECT COUNT ( * ) AS total , SUM ( some_column IS NOT NULL ) AS filled FROM some_table ; If that comes back near 100%, this note may simply not apply to your codebase, and that's a real result, not a failure to reproduce it. Keep that in mind through the rest of this — every finding below is downstream of a query shaped like this one, not downstream of reading code and guessing. Grep is not the detector My first instinct, the same one the predecessor note's fixes point toward, was to grep for the failure shape — a default value, an unpopulated argument, a call site missing a keyword. In one afternoon it produced both a false positive and a false negative. The sharper miss: a literal grep for a write path failed to find an INSERT OR REPLACE statement that was, in fact, live and doing exactly the writing I was looking for. Grep matched the shape of the bug I expected walking in, not the shape the code actually had. Everything that survived scrutiny below came from asking a database a question, not from asking a shell how a string was spelled. The question that works is: of all the rows that exist, how many have this column fi
AI 资讯
Technical Documentation Template: Build Product Docs With a Tested Structure
Originally published at https://ninadpathak.com/articles/technical-documentation-template/ . Creating documentation often forces several decisions at once: where readers begin, how they complete the first task, where exact details belong, and how they recover when a step fails. A template reduces that first pass to a structure you can inspect and adapt. I built this template to solve a narrow problem: an empty documentation repository leaves every contributor to invent navigation, page responsibilities, and release checks again. It provides five focused pages, a local validator, and a strict build path so the structure is useful before the product-specific writing begins. Download the technical documentation template Download the template Unpack the archive, then replace the placeholders with evidence from your product. The remaining sections show what belongs in each page and how to verify the result. What a technical documentation template should include A technical documentation template is a reusable starting structure for product or engineering documentation. It should tell a contributor where a reader begins, where they complete a task, where they look up stable details, and where they recover from a known failure. A table of contents alone cannot do that work. It can label a page “Getting started” without establishing prerequisites, a tested command, an expected result, or a recovery path. The starter contains five pages because they create a complete first route without pretending every product needs the same collection. Page Reader job Evidence to add before publishing index.md Choose the first useful task A direct route to the right starting page getting-started.md Complete first setup Prerequisites, a tested command, expected output guides/send-a-request.md Perform one bounded task A full request and response or observable state reference/configuration.md Look up stable details Names, types, defaults, and constraints troubleshooting.md Recover from a know
AI 资讯
Testing an LLM Input Layer for Poker Calculators: Verified Math, Unverified Interpretation
This article is about a poker-analysis framework, but the engineering problem is common to LLM tool use. The framework uses an LLM as an input and control layer. It reads a natural-language poker question, chooses a local calculator, and proposes typed fields. A Python program, not the LLM, performs the numerical calculation and returns a structured result with verification data. In this evaluation, a coordinator manually passed each calculator-eligible saved proposal to the command-line calculator; no automatic runtime bridge connected them. The design intent was to reduce manual arithmetic checking by sending numerical claims to deterministic, internally verified local software. The evaluation below tests whether those claims were checked and whether the handoff remained auditable. It did not measure time saved or the overall quality of the resulting poker analysis. The calculator catalog is poker-specific. This is not a poker strategy guide, and you do not need to know poker strategy to follow the failure. The question is whether a correct calculator can produce a verified result after the LLM chooses an interpretation without asking the user to confirm it. The workflow was tested with 25 hand-authored cases that were fixed before execution. They are labeled C01 through C25: C01–C23 tested the LLM's routing, proposed input, and boundary decisions; C24 and C25 repeated two accepted inputs to check non-volatile result semantics. The labels are test numbers, not poker terminology. The main example uses one small pot-odds model. In this model, the pot is the shared pool of chips the players are competing for. The calculator's inputs are: pot_before_bet : the amount already in the pot before the opponent's new bet; opponent_bet : the amount the opponent adds; call_cost : the amount the player must add to continue; expected_rake : an optional amount removed from the final pot. The calculation is: net final pot = pot_before_bet + opponent_bet + call_cost - expected_rake
AI 资讯
Phase 7a — Getting Opinionated: Rules-Based Auto-Categorization (and a Seam for the AI Later)
My expense app finally has a point of view on what I'm spending money on. No AI yet — just honest keyword rules, a nullable column, and one interface that means I can bolt an LLM on later without ripping anything out. Here's the build, three "empty value" bugs that bit me, and the habits that kept it clean. Index Where we left off The plan: rules first, AI behind the same door Step 1 — A nullable column (and why nullable matters) Step 2 — The migration: generate → review → apply Step 3 — A dumb-but-working categorize() Step 4 — Wiring it into create (with override precedence) Step 5 — The seam: extracting behind a Categorizer interface Step 6 — The UI loop: show, add, edit 🐛 The war story: three ways "empty" lied to me Thinking like an attacker Learning shortcut vs. production Key habits to keep Next up: Phase 7b Where we left off Phase 6 gave me the receipts — date-range reports and CSV export. I ended that post with a promise: Next up: Phase 7, where categories finally enter the schema and the app starts to get opinionated about what I'm spending on. This is that. But it turned into a bigger beast than one post, so I'm splitting it: Phase 7a (this post): the schema, a rules-based categorizer, the interface seam, and the full UI loop. Phase 7b (next): the actual LLM — an LLMCategorizer that slots in behind the same interface, with caching and a rules fallback. Doing rules first isn't a cop-out. It's the whole strategy. The plan: rules first, AI behind the same door The temptation with "AI categorization" is to reach straight for the API key. I didn't. Here's the order I actually built in, and why: Step What Why this order 1 Nullable category column The app needs somewhere to store a category before it can fill one 2 Rules categorize() A working, free, offline fallback — and a baseline to test against 3 Extract behind an interface So the LLM can slot in later without touching call sites 4 UI loop (show / add / edit) Give the human final say, no matter how smart the
AI 资讯
Will AI Replace Software Engineers?
Will AI replace software engineers? No. As a staff software engineer who works with AI extensively, I can say that the fear a lot of people have is valid and understandable, but total replacement is not going to happen. Why? Software engineering requires decisions. Architecture, tech stack, workflow design, and many others. AI does not understand how to make those decisions, it was not designed for that, and it is not heading in that direction. Artificial intelligence is a tool designed to improve the productivity of humans, including but not limited to software engineering, and in that realm it is the biggest jump in day to day productivity I have seen in my career. It has increased the output of software engineering by orders of magnitude, and that is what makes it so good. It is also why some people think it might replace software engineers. Large language models, with access to the right tools and when they run in loops, are very strong and very good at improving the productivity of software engineers. They also help engineers improve the quality of their decisions. Even with the best AI models out there, and with unlimited tokens, if you instruct one to implement a product, and I am emphasizing the word product here, not just a feature, it will get it done with the happy paths only, the absolute bare bones proof of concept. It does not know how to complete the product end to end, it does not know how to integrate it into the real world, and it certainly does not know how to architect and design the flow or how to make decisions. At best it can guess, and those guesses will always fall short of what a human can do. That is why I believe software engineers will not be replaced by AI. AI is a tool, and a tool replaces parts of a job. It makes the work faster, more accurate, better documented, but it is not a total replacement.
AI 资讯
Beyond Autocomplete: Meta Muse Code, AWS Kiro, and the Rise of Multi-Agent AI Planning 🤖⚡
Remember when "AI coding" just meant inline tab-completion suggesting a for loop in VS Code? Those were simpler times. 😅 Fast forward to this week, and we’ve officially crossed the threshold into the Autonomous Multi-Agent Era . The industry is shifting away from single-turn autocomplete prompts toward async, parallelized agentic workflows that inspect, plan, write, test, and validate code across entire repositories. Three major developments dropped almost simultaneously: ⚡ Meta launched Muse Code (powered by Muse Spark 1.2) in beta, introducing parallel sub-agent execution. ☁️ AWS added an Agentic Workspace to Kiro , enabling async background task delegation for developers. 🎓 New Academic Research surfaced on how AI coding agents leverage structured "Agent Plans" for full-lifecycle repo maintenance, design, construction, testing, and validation. Let's break down why this is a massive engineering paradigm shift and what it actually means for our daily developer workflows. 🧬 1. Meta Muse Code & Parallel Sub-Agent Swarms Meta’s latest drop— Muse Code , driven by their Muse Spark 1.2 model—takes aim at one of the biggest bottlenecks in single-agent LLM systems: context dilution and linear execution delays . When you ask a traditional LLM to refactor a complex microservice, it processes everything sequentially. It reads your files, thinks, writes code, tries to debug, and eventually runs out of context space or hits token output limits. How Parallel Sub-Agent Execution Changes the Game Muse Code doesn't just run one linear chat session. Instead, a primary orchestrator agent decomposes a high-level goal into specialized sub-agents running concurrently: ┌──────────────────────────────┐ │ PRIMARY ORCHESTRATOR AGENT │ └──────────────┬───────────────┘ │ ┌──────────────────────────┼──────────────────────────┐ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ SUB-AGENT A │ │ SUB-AGENT B │ │ SUB-AGENT C │ │ AST Parsing & │ │ Unit Test Suite │ │ Static Analysis
开发者
Paradigma de Programação Orientada a Objetos (POO)
Introdução A Programação Orientada a Objetos nasceu com a linguagem Simula 67 , considerada a primeira linguagem orientada a objetos, e foi consolidada e popularizada por Smalltalk nos anos 1970. Ganhou adoção massiva na indústria com C++ e, posteriormente, Java e C#. A ideia central é organizar o código em torno de objetos : unidades que combinam dados (atributos/estado) e comportamento (métodos) em uma única estrutura. Os quatro pilares Encapsulamento — os dados internos de um objeto são protegidos e só podem ser acessados/alterados através de métodos expostos, escondendo detalhes de implementação do mundo externo. Abstração — o objeto expõe apenas o que é relevante para quem o utiliza, escondendo a complexidade interna (ex.: você chama CalcularSalario() sem precisar saber como o cálculo é feito por dentro). Herança — uma classe pode herdar atributos e métodos de outra, permitindo reaproveitamento e especialização (uma classe Desenvolvedor pode herdar de Funcionario ). Polimorfismo — objetos de classes diferentes podem responder de forma diferente ao mesmo "chamado" (o mesmo método CalcularSalario() se comporta de forma distinta para um Desenvolvedor e para um Gerente , por exemplo). Exemplo // Exemplo de Programação Orientada a Objetos em C# public abstract class Funcionario { public string Nome { get ; } protected decimal SalarioBase { get ; } protected Funcionario ( string nome , decimal salarioBase ) { Nome = nome ; SalarioBase = salarioBase ; } // Abstração: cada subclasse decide como calcular seu próprio salário public abstract decimal CalcularSalario (); } public class Desenvolvedor : Funcionario { private int BonusPorProjeto { get ; } public Desenvolvedor ( string nome , decimal salarioBase , int bonusPorProjeto ) : base ( nome , salarioBase ) // Herança { BonusPorProjeto = bonusPorProjeto ; } // Polimorfismo: implementação específica do método herdado public override decimal CalcularSalario () { return SalarioBase + BonusPorProjeto ; } } public class Gere
产品设计
Verify before you break the lock
I built a stale-lock breaker: if the lockfile's owner looked dead, delete the file and take over. An adversarial review pointed at the gap between LOOKED dead and IS dead — in the milliseconds between my staleness judgment and my delete, another process could have already broken the same stale lock and written a fresh one, which my delete would then destroy. Two owners, both convinced they won. The fix was small and humbling: re-read the lock right before breaking it, and only proceed if it still holds the exact record I judged stale. Every check-then-act on shared state has a gap in the middle, and the gap doesn't care how fast your code is. Re-validate at the moment of the irreversible act, not just before it.
AI 资讯
Avoiding the 5 Mistakes Most Tutorials Make When Creating a File Encryption Tool
Why “it encrypts” doesn't equate to “it’s secure” If you want to find a tutorial for encrypting files in code, your search results will provide dozens of tutorials. Most of these tutorials will produce code that, on the surface, performs encryption. Users can provide plaintext, receive ciphertext, and the code also performs decryption. Unfortunately, the phrase “the output looks scrambled” is an unsecure way to test a program for security. These tutorials fail to incorporate security practices, which will result in these tools being rejected in real life security assessments. By identifying these mistakes, we can reason about the validity of these encryption schemes. This article covers the correct way to build a file encryption tool and the mistakes that beginner encryption tools include. These mistakes will help you learn the correct way to build an encryption tool. SecureVault (Node.js, packaged with no dependencies) is a command-line tool that is referenced throughout to help provide context to the design decisions that were made for this tool. Prerequisite mindset: When designing secure systems, always assume that the attacker knows more than you. Do you really think that your adversary will only submit the inputs you assumed they would submit? They will submit corrupted inputs, they will submit old ciphertexts, and they will do anything you thought was impossible. You need to have a secure design. You must think "what malicious inputs can I handle here?" . The goal: three guarantees, not one Before you even think about writing code, you need to know exactly what you mean by that something is secure. A good file encryption tool must provide three guarantees. Most of the tutorials that I have seen think only about the first one. Confidentiality - the attacker that steals the file should not be able to read the file. Integrity - If the attacker alters the encrypted file, you will know. Authenticity - The file can only be generated by a user that knows the passwor
开发者
LLD Design Patterns: How We'll Learn Design Patterns Throughout This Series
So far in this mini-series, we've answered the biggest questions that confuse developers when they first encounter Design Patterns. We've learned: why SOLID isn't the final destination, why recurring design problems exist, why copying code doesn't create good design, what Design Patterns really are, how experienced engineers recognize them, and how every pattern can be understood through its Problem, Intent, Solution, and Consequences . Now it's time to answer one final question before we begin exploring the individual patterns. How should we learn Design Patterns so that we can actually use them in real-world software instead of just recognizing their names? The answer may surprise you. We're not going to learn Design Patterns the way they're usually taught. The Traditional Way of Learning Design Patterns Open almost any Design Patterns book or tutorial, and you'll often see something like this. Pattern Name ↓ Definition ↓ UML Diagram ↓ Code Example ↓ Advantages ↓ Disadvantages Technically, there's nothing wrong with this approach. But many developers finish reading the chapter and still wonder: "When would I ever use this?" That's because they learned the solution before understanding the problem. It's like learning how to use a fire extinguisher before understanding what kinds of fires it can safely put out. Knowledge without context is difficult to apply. The Way Experienced Engineers Learn Experienced engineers don't begin with the pattern. They begin with the software. They observe where the current design starts struggling. Only then do they search for a better design approach. Their thinking looks more like this. Business Requirement ↓ Design Challenge ↓ Current Design Starts Breaking ↓ Understand Why ↓ Explore Better Design ↓ Recognize a Design Pattern The pattern is never the starting point. It's the result of understanding the problem. The Learning Framework We'll Use Every pattern in this series will follow exactly the same structure. Business Problem ↓
AI 资讯
How We Evolved a Cultural Recommendation Feed From a Weighted SQL Ranker to a Narrative Affinity Model
Building a personalization engine for a multi-format content feed, without machine learning, and the testing process that forced us to rebuild it. TL;DR We run a collaborative cultural curation platform (think: user-submitted recommendations for movies, books, games, music, and long-form posts, all mixed into one feed) on a fairly ordinary PHP + MySQL stack. Over about a year we went through two full generations of the feed ranking algorithm. The first version solved the obvious problem (stop being purely chronological) but quietly failed at real personalization. The second version fixed that by rethinking what "user taste" even means, moving scoring out of SQL and into application code, and adding a layer of post-ranking business rules. This post walks through both generations, why the second one had to happen, and how we actually tested and calibrated a feed ranking system without a data science team or an ML pipeline. No exact weights, table names, or formulas below — just the engineering story. The starting problem: one feed, five content shapes Before personalization is even on the table, a multi-format feed has a normalization problem. Movies, books, games, music, and editorial posts live in different tables, with different columns, different publishing cadences, and engagement numbers on completely different scales. "1,000 likes" on a music post and "1,000 likes" on a book review are not the same signal. So the very first architectural decision — before any ranking logic existed — was building a unification layer that maps every content type into a shared shape (type, author, title, cover, category, engagement counters, timestamp) before any scoring happens. Everything downstream depends on that layer being consistent. Generation 1: a weighted ranker living inside a single SQL query The first real version of the algorithm — internally we called it the hybrid model — had a modest goal: get away from a purely chronological feed without building anything resembl
AI 资讯
Factory Method Design Pattern in Software Engineering: A Smarter Way to Create Objects
Introduction As software applications grow in size and complexity, managing object creation becomes challenging. Creating objects directly using constructors can result in tightly coupled code that is difficult to maintain and extend. The Factory Method Design Pattern solves this problem by separating object creation from object usage. It provides a flexible and reusable approach for creating objects, making applications easier to modify and scale. What is the Factory Method Design Pattern? The Factory Method Design Pattern is a Creational Design Pattern that provides an interface for creating objects without specifying their exact classes. Instead of directly instantiating objects using the new keyword, a factory class creates and returns the required object. Definition Factory Method Design Pattern: A creational design pattern that defines an interface for creating objects while allowing subclasses or factory classes to decide which object to instantiate. Why Do We Need It? In traditional programming: The client creates objects directly. Code becomes tightly coupled. Adding new object types requires modifying existing code. Maintenance becomes difficult. The Factory Method pattern solves these problems by centralizing object creation inside a factory class. How It Works The client requests an object from the factory. The factory checks the requested type. The appropriate concrete object is created. The factory returns the object to the client. The client uses the object without knowing how it was created. Java Example interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } } class ShapeFactory { public Shape getShape(String type) { if(type.equalsIgnoreCase("Circle")) return new Circle(); if(type.equalsIgnoreCase("Rectangle")) return new Rectangle(); return null; } } public class FactoryPatternDem
开发者
Prototype Design Pattern in Java: A Practical Guide with Real-World Examples
Understanding the Prototype Design Pattern in Java Introduction When developing software, there are situations where creating a new object from scratch is expensive or time-consuming. For example, an object may require complex initialization, database access, or extensive configuration. In such cases, instead of creating a new object every time, we can duplicate an existing object. This is where the Prototype Design Pattern becomes useful. The Prototype Design Pattern is one of the Creational Design Patterns in Java. It allows developers to create new objects by cloning existing ones rather than instantiating them using constructors. What is the Prototype Design Pattern? The Prototype Design Pattern creates new objects by copying an existing object, known as the prototype. This approach improves performance by avoiding repeated initialization and allows developers to create multiple similar objects efficiently. In Java, cloning is commonly implemented using the Cloneable interface and overriding the clone() method. Why Use the Prototype Pattern? The Prototype Pattern offers several benefits: Reduces the cost of object creation. Improves application performance. Simplifies the creation of complex objects. Avoids repeated initialization code. Makes object creation more flexible. Real-World Example Imagine an online shopping application where thousands of product objects share similar properties. Instead of creating every product from scratch, the application can clone a prototype product and modify only the required attributes such as name or price. Other real-world examples include: Document templates Game characters Employee records Vehicle configurations Graphic design objects UML Structure The Prototype Design Pattern generally includes: Prototype Interface – Declares the clone operation. Concrete Prototype – Implements the cloning functionality. Client – Creates new objects by cloning existing prototypes. Java Implementation Step 1: Create the Prototype Class cla