今日已更新 133 条资讯 | 累计 37382 条内容
关于我们

标签:#att

找到 184 篇相关文章

AI 资讯

The State Pattern Trap: Why GoF Is Not Always the Best Choice

Have you ever tried to use the classic Gang of Four (GoF) State Pattern in real code? You might have hit a wall. You might have thought, "Wait, this feels way too connected." You are not wrong about that. In school and many engineering interviews, the GoF State Pattern looks great. It promises to fix big, ugly switch statements. But real business rules are hard. When you use this pattern in real life, it can become a huge mess. Every state knows too much about the other states. Let us look at why this happens. We will learn the difference between the GoF pattern and a Finite State Machine (FSM). We will also learn when to use each one. The False Promise of the GoF State Pattern The main idea of the GoF State Pattern is to spread out the work. The main object gives its work to state objects. But there is a catch. The state classes themselves must trigger the change to the next state. Example: The Traffic Light Think about a simple traffic light. It goes Red to Green to Yellow to Red. It does this forever. class RedState implements TrafficLightState { change ( context : TrafficLight ): void { console . log ( " RED light, Stop " ); context . setState ( new GreenState ()); // Very connected! } } The Problem: RedState is forced to know about GreenState . This is fine for a simple traffic light. It is a closed loop. The rules will never change. But what happens when business rules change? Imagine the city council makes a new rule. From midnight to 5:00 AM, the light must flash yellow. Now, you must open your RedState and YellowState classes. You have to add new time checks. You have to add the new flashing state. The more states you add, the messier your code gets. The Better Choice: The Central FSM In the real world, things do not always happen in a straight line. An online order does not just go from Pending to Shipped to Delivered. It can jump from Pending to Cancelled. It can go from Shipped to Returned. If you use GoF here, your PendingState needs to know about many

2026-08-26 原文 →
AI 资讯

Dictionary Pattern Matching in Some Languages Ignores Unspecified Keys, Risks Unexpected Bugs

Introduction Pattern matching, a powerful feature in many programming languages, allows developers to deconstruct complex data structures with elegance and precision. However, when it comes to dictionaries , this elegance can mask a critical issue: non-strict shape matching . Unlike sequence patterns, which demand an exact match, dictionary pattern matching in certain languages silently ignores unspecified keys. This behavior, while seemingly flexible, can lead to unexpected bugs and security vulnerabilities if developers assume strict shape enforcement. To illustrate, consider a dictionary pattern match in a language like Python or Rust. If you write a pattern to match a dictionary with keys {'a', 'b'} , and the actual dictionary contains {'a', 'b', 'c'} , the match will succeed, and the key 'c' will be ignored. This might seem harmless, but it violates the developer’s expectation of a strict shape match, akin to what sequence patterns provide. The causal chain here is straightforward: impact (developer assumes strict matching) → internal process (language ignores unspecified keys) → observable effect (unexpected behavior or bugs). The root of this issue lies in the design choice of prioritizing flexibility over strictness. Languages often default to this behavior to accommodate varying data shapes, but this comes at the cost of clarity and predictability. Compounding the problem is the lack of clear documentation or understanding of this behavior, leading developers to make incorrect assumptions based on their experience with sequence patterns. For instance, in a system where data integrity is critical, such as financial transactions or security protocols, silently ignoring keys could lead to data corruption or unauthorized access . If a developer expects a dictionary to have exactly three keys but the pattern matches a dictionary with four, the extra key might contain malicious data or disrupt downstream logic. The mechanism of risk formation here is the mismatch

2026-08-25 原文 →
AI 资讯

The Criteria pattern in NestJS: what a client may ask for is a file, not a signature

The Criteria pattern in NestJS One single way to filter, sort and paginate any list. Five parameters and a find() The example running through this article is a library catalogue. A book stores this: // src/book/book.schema.ts @ Schema ({ timestamps : true }) export class Book { @ Prop () title : string ; @ Prop ({ type : Types . ObjectId , ref : " Author " }) author : Types . ObjectId ; @ Prop () publishedAt : Date ; @ Prop () copies : number ; // copies on the shelf @ Prop () available : boolean ; @ Prop () acquisitionPrice : number ; // what it cost us: internal, never published } The author's name is not here: it lives in the authors collection, on the other side of that reference. And the screen consuming the catalogue is a table with a search box, per-column filters and pagination. The endpoint feeding it is written once and grows by accretion. It starts returning a page with a fixed order, and by the time the table has all its filters it has become this: // src/book/book.controller.ts @ Controller ( " books " ) export class BookController { constructor ( @ InjectModel ( Book . name ) private readonly model : Model < BookDocument > , ) {} @ Get () async getAll ( @ Query ( " title " ) title ?: string , @ Query ( " available " ) available ?: string , @ Query ( " minCopies " ) minCopies ?: string , @ Query ( " sortBy " ) sortBy ?: string , @ Query ( " page " ) page ?: string , ) { const filter : FilterQuery < BookDocument > = {}; if ( title ) { filter . title = { $regex : title , $options : " i " }; } if ( available ) { filter . available = available === " true " ; } if ( minCopies ) { filter . copies = { $gte : Number ( minCopies ) }; } const current = Number ( page ?? 1 ); const [ items , total ] = await Promise . all ([ this . model . find ( filter ) . sort ({ [ sortBy ?? " createdAt " ]: - 1 }) . skip (( current - 1 ) * 20 ) . limit ( 20 ), this . model . countDocuments ( filter ), ]); return { items : items , total : total , page : current }; } } There are co

2026-08-21 原文 →
AI 资讯

El patrón Criteria en NestJS: lo que un cliente puede pedir es un archivo, no una firma

Cinco parámetros y un find() El ejemplo de todo el artículo es el catálogo de una biblioteca. Un libro guarda esto: // src/book/book.schema.ts @ Schema ({ timestamps : true }) export class Book { @ Prop () title : string ; @ Prop ({ type : Types . ObjectId , ref : " Author " }) author : Types . ObjectId ; @ Prop () publishedAt : Date ; @ Prop () copies : number ; // ejemplares en la estantería @ Prop () available : boolean ; @ Prop () acquisitionPrice : number ; // lo que costó adquirirlo: interno, no se publica } El nombre del autor no está aquí: vive en la colección authors , al otro lado de esa referencia. Y la pantalla que consume el catálogo es una tabla con buscador, filtros por columna y paginación. El endpoint que la alimenta se escribe una vez y crece por acumulación. Empieza devolviendo una página con un orden fijo, y para cuando la tabla tiene todos sus filtros ha llegado a esto: // src/book/book.controller.ts @ Controller ( " books " ) export class BookController { constructor ( @ InjectModel ( Book . name ) private readonly model : Model < BookDocument > , ) {} @ Get () async getAll ( @ Query ( " title " ) title ?: string , @ Query ( " available " ) available ?: string , @ Query ( " minCopies " ) minCopies ?: string , @ Query ( " sortBy " ) sortBy ?: string , @ Query ( " page " ) page ?: string , ) { const filter : FilterQuery < BookDocument > = {}; if ( title ) { filter . title = { $regex : title , $options : " i " }; } if ( available ) { filter . available = available === " true " ; } if ( minCopies ) { filter . copies = { $gte : Number ( minCopies ) }; } const current = Number ( page ?? 1 ); const [ items , total ] = await Promise . all ([ this . model . find ( filter ) . sort ({ [ sortBy ?? " createdAt " ]: - 1 }) . skip (( current - 1 ) * 20 ) . limit ( 20 ), this . model . countDocuments ( filter ), ]); return { items : items , total : total , page : current }; } } El método tiene decisiones correctas dentro: el total sale del mismo filtro que los

2026-08-21 原文 →
开发者

LISKOV SUBSTITUTION PRINCIPLE

A parent class must be able to be substituted by its child classes without breaking the application. In practice, this helps to organize the idea of inheritance, as it prevents us from extending a parent class only to later remove an already implemented method or do a “throw new Error(‘Not implemented’)”. Making us much more careful during planning. THE BIGGEST SYMPTOM OF ERROR Unfortunately, it is a symptom that appears late, but it is exactly when we are going to make a new implementation. You realize you violated Liskov when you are going to build a class or subclass and need to purposely throw an error in the implementation of a method. Exactly because that method shouldn't be there, but it is. A BAD EXAMPLE For example, in a delivery system. In this case, the “Delivery” class should be the parent/base for the other implementations. But the ‘MotoboyDelivery’ class breaks this. Code Example: // BAD: The subclass breaks the parent class contract. class Delivery { public calculateShipping (): number { return 15.0 ; } public getTrackingCode (): string { return " TRK123456789 " ; } } class MotoboyDelivery extends Delivery { public calculateShipping (): number { return 8.0 ; } // ERROR! There is no tracking code. public getTrackingCode (): string { throw new Error ( " Motoboys do not have a tracking code. " ); } } THE SOLUTION For those who do not yet know the 'Liskov Substitution Principle', it might seem that fitting in a sequence of 'if's is the solution. But in reality, the ideal path is to rethink how this abstraction is built. A good guiding principle is to think that a child class must always be able to take the place of the parent, without breaking the application. A GOOD EXAMPLE Still in the delivery system. ‘Delivery’ now has ‘TrackableDelivery’ in the middle of the way. With this, each “leaf”/edge of the application inherits what makes the most sense and nothing is broken. Code Example: interface Delivery { calculateShipping (): number ; } interface Trackab

2026-08-20 原文 →