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

标签:#oop

找到 39 篇相关文章

开发者

Sealed Isn't a Restriction, It's a Promise

Leaving a class open to inheritance is a design decision, not a default you can ignore. The core idea An unsealed class is a promise: every virtual member can be overridden without breaking what the class guarantees. Most classes never meant to make that promise. They're just unsealed by default, because that's what class gives you unless you say otherwise. Common mistake: treating sealed as "I don't want to think about subclassing" rather than "this type's invariants would break if someone could." One override breaks the promise Here's the promise, a BankAccount that refuses to go negative: public class BankAccount { public decimal Balance { get ; protected set ; } public virtual void Withdraw ( decimal amount ) { if ( amount > Balance ) throw new InvalidOperationException (); Balance -= amount ; } } And here's the override that breaks it: public class RiskyAccount : BankAccount { public override void Withdraw ( decimal amount ) { Balance -= amount ; // no check } } Nothing here is exotic. It compiles cleanly, and RiskyAccount is a perfectly legal BankAccount as far as the type system is concerned. Open one with a balance of 100 and withdraw 500: BankAccount account = new RiskyAccount ( 100m ); account . Withdraw ( 500m ); Console . WriteLine ( $"Balance: { account . Balance : F2 } " ); Real dotnet run output: Balance: -400.00 The check on the left never ran. virtual was an open invitation, and RiskyAccount took it. Sealing turns a silent bug into a compile error Without sealed , the code above compiles and produces a wrong answer at runtime; nothing points you at the problem until it's already in production. With sealed , the same mistake becomes something the compiler catches before the code ever runs: public sealed class BankAccount { public decimal Balance { get ; protected set ; } public void Withdraw ( decimal amount ) { if ( amount > Balance ) throw new InvalidOperationException (); Balance -= amount ; } } public class RiskyAccount : BankAccount { } // error

2026-08-29 原文 →
AI 资讯

More Incidents of AIs Going Rogue in Cybersecurity Challenges

The AI Security Institute has a new report of AI systems engaging in “unsanctioned behavior”—what I have been calling “ genie behavior —while being tested on their cybersecurity capabilities. The incident stemmed from a single evaluation where agents were given a task of solving a cyber security challenge. We ran this challenge 122 times across several models. Our investigation found that in 10 of those runs, an AI agent took autonomous, unsanctioned action on the live internet, targeting real people and organisations. In total, we catalogued 19 such actions. Almost all of this behaviour (17 actions) came from a single model, Anthropic’s Mythos 5, with 2 actions involving OpenAI’s GPT-5.6-Sol with cyber classifiers (mechanisms to prevent misuse) disabled. In the most serious case, an agent tried to insert malicious code into an open-source project. In an attempt to get the code approved, the agent engaged in social engineering—creating fake online identities and using them to pressure the project’s maintainer to approve the code. A human maintainer caught and refused to approve the malicious code...

2026-08-21 原文 →
AI 资讯

OOP Object-Oriented Programming

Advantages of using OOP: Is faster and easier to execute. Provides a clear structure for the programs. Helps to keep code DRY "Don't Repeat Yourself" and makes code easier to maintain, modify, and debug. Makes it possible to create fully reusable applications with less code and shorter development time. Define a Class: A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces {} . All its properties and methods go inside the braces. Delegation: Delegation means that you use an object of another class as an instance variable. We can create multiple objects from a class. Each object has all the variables and functions defined in the class. An object of a class is made using the new keyword. Note: The $this keyword refers to the current class and is only available inside methods. __construct() function: Automatically runs at the beginning of the class. __destruct() function: Automatically runs at the end of the class. Encapsulation: The wrapping up of data and methods is a protection mechanism for the variables and functions inside the class. Access Modifier: Public: Variables or functions can be accessed from everywhere. Private: Variables or functions can ONLY be accessed inside the class. Protected: Variables or functions can be accessed inside the class and by child classes that extend from the parent class. Constants: It can’t be changed once it is declared. Declared inside a class with the const keyword. It is recommended to name the constants in all uppercase letters . Access outside the class by using the class name followed by the scope resolution operator :: . Access a constant inside the class by using the self keyword. Static Functions and Variables: Static functions or variables can be called directly - without creating an instance of the class first. Static functions or variables are declared with the static keyword. To access a static function or variable, use the class name , double colon :: , and the fu

2026-08-12 原文 →
AI 资讯

Unary gRPC on Reactor Netty: Event Loop Serialization, Trailers, and Cancellation

With protocol values and message framing complete, Stage 2 delivered the first end-to-end call: plaintext h2c unary RPC. This is already on main , and Stage 3 and Stage 4 subsequently completed all four RPC cardinalities on the same transport primitive. Previous: Building a Leak-Safe gRPC Frame Decoder on Reactor Netty Method Descriptor Is Where Protocol Meets Types A method requires a precise service name, method name, cardinality, and request/response marshallers: var echo = new GrpcMethod <>( "testing.EchoService" , "Echo" , GrpcMethod . Cardinality . UNARY , new ProtobufMarshaller <>( StringValue . parser ()), new ProtobufMarshaller <>( StringValue . parser ())); The generated path must be: /testing.EchoService/Echo The service registry matches by exact full path. An unknown path returns UNIMPLEMENTED ; registering the same path twice fails immediately when building the service definition. Server Validates Protocol Before Subscribing to Business Logic ReactorGrpcServer uses Reactor Netty h2c: DisposableServer bound = HttpServer . create () . host ( host ) . port ( port ) . protocol ( HttpProtocol . H2C ) . handle ( handler: : handle ) . bindNow ( Duration . ofSeconds ( 10 )); Incoming requests are validated in order: HTTP method must be POST; content-type must be application/grpc or application/grpc+... ; te must declare trailers; path must exist; currently only unary cardinality is allowed; metadata and message size must not exceed limits. Only after validation passes does it create a GrpcCallContext and subscribe to the request body, preventing invalid requests from entering the business handler. HTTP 200 Does Not Mean RPC Success The server writes a compatible content-type first; the final status comes from trailing headers: response . status ( 200 ) . header ( HttpHeaderNames . CONTENT_TYPE , "application/grpc+proto" ); response . trailerHeaders ( trailers -> { GrpcException error = terminal . get (); if ( error == null ) { writeStatus ( trailers , GrpcStatu

2026-08-09 原文 →
开发者

Apache Hadoop Installation

This guide is a collection or a summary on how to install and use a footprint of Apache Hadoop. I tried to follow an old version 2.7.1 guide that I created few years ago and adjusted this to use the latest version. Apache Hadoop 3.5.0 is used below; check the Apache releases page before future installations. These instructions target Linux (Ubuntu/Debian) for development or testing. Production clusters need Kerberos, network controls, encryption, monitoring, backups, and an upgrade plan. Do not expose HDFS or YARN ports to the internet. Native single-node installation Prerequisites sudo apt-get update sudo apt-get install -y openjdk-17-jdk openssh-client openssh-server pdsh curl tar java -version Hadoop requires Java and SSH; pdsh is recommended by the current Apache single-node documentation. Find JAVA_HOME if needed: readlink -f "$(command -v java)" | sed 's:/bin/java::' Download and install Pin the version for repeatable installs and verify Apache's SHA-512 checksum: export HADOOP_VERSION=3.5.0 cd /tmp curl -fLO "https://archive.apache.org/dist/hadoop/common/hadoop-${HADOOP_VERSION}/hadoop-${HADOOP_VERSION}.tar.gz" curl -fLO "https://archive.apache.org/dist/hadoop/common/hadoop-${HADOOP_VERSION}/hadoop-${HADOOP_VERSION}.tar.gz.sha512" sha512sum -c "hadoop-${HADOOP_VERSION}.tar.gz.sha512" sudo tar -xzf "hadoop-${HADOOP_VERSION}.tar.gz" -C /opt sudo ln -sfn "/opt/hadoop-${HADOOP_VERSION}" /opt/hadoop sudo chown -R "$USER":"$USER" "/opt/hadoop-${HADOOP_VERSION}" Add this to ~/.bashrc, adjusting JAVA_HOME if necessary: export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 export HADOOP_HOME=/opt/hadoop export HADOOP_CONF_DIR="$HADOOP_HOME/etc/hadoop" export HADOOP_HDFS_HOME="$HADOOP_HOME" export HADOOP_YARN_HOME="$HADOOP_HOME" export HADOOP_MAPRED_HOME="$HADOOP_HOME" export PATH="$PATH:$HADOOP_HOME/bin:$HADOOP_HOME/sbin" Then load and verify it: source ~/.bashrc sed -i "s|^# export JAVA_HOME=.*|export JAVA_HOME=${JAVA_HOME}|" "$HADOOP_HOME/etc/hadoop/hadoop-env.sh" had

2026-08-02 原文 →
AI 资讯

Loop Engineering: Stop Failed Successfully

After a lovely and productive conversation with your client, with still ringing ears, you check the coding agent's last log messages on a ticket that adds a discount to a product. The message was: "Done, I added the 10% discount and all tests pass. Stopping. " Well ... you know it's just not true, so you dig further and quickly realize that the discount functionality was never actually added and the tests it reported passing had never been run. The agent reached the end of the loop, looked at its own work, and called it finished. That call is the thing that shipped. This has a name. A paper published this June, From Confident Closing to Silent Failure , calls it false success: the agent asserts the task is complete while the actual state of the system says otherwise. It is common, and it holds up across capable models. On AppWorld, a benchmark for long-horizon coding agents, 75.8% of the runs that actually failed still ended with the agent claiming it was done. The researchers then put five different LLM judges on those completion claims, varying the prompts each time, and every one of them landed barely above a coin flip, because the thing each judge was reading was the closing sentence, and the closing sentence reads as confident whether the work happened or not. What told a real done apart from a false one turned out to be cheap and mechanical: a look at the actual state of the system. A lightweight deterministic state check caught four to eight times more false successes than the best of the judges. The paper has a name for the mechanism underneath, a hallucination of verification: the model narrates having checked something it never checked, and that narration is indistinguishable, sentence for sentence, from a report of a check that really ran. That gap, between what the agent said and what the system did, is what this piece is about. A loop runs five arms: generate, check, steer, retry, stop. The series opener named them; four pieces since took the check that

2026-07-28 原文 →
AI 资讯

SOLID Principles Cheat Sheet

Writing software that scales from a small monolith into a multi-team distributed system requires strict architectural discipline. The SOLID principles —coined by Robert C. Martin ("Uncle Bob")—serve as fundamental guidelines for object-oriented design and system architecture. When improperly understood, developers often fall into two extreme traps: creating monolithic "God objects" that break with every change, or over-engineering systems into hyper-fragmented, unmaintainable micro-services. In this deep-dive guide, we will break down each of the 5 SOLID principles from low-level class design up to high-level distributed systems design, complete with bad vs. refactored Java examples, system architecture diagrams, trade-off analyses, and a comprehensive cheat sheet. SOLID Principles Cheat Sheet Principle Core Concept Anti-Pattern / Code Smell Refactoring Solution Single Responsibility (SRP) A class or module should have one, and only one, reason to change (serving one business actor/domain). God Class / Micro-Fragmentation: Classes handling payment, DB, and notifications, OR over-fragmented single-function classes. Split by domain responsibility. Use orchestrator/coordinator components for workflows. Open/Closed (OCP) Software entities should be open for extension, but closed for modification . Conditional Bloat: Cascading if-else or switch statements checking object types or channels. Strategy Pattern, Dependency Injection, and Event-Driven Pub/Sub messaging (e.g., Kafka). Liskov Substitution (LSP) Subtypes must be completely substitutable for their base types without breaking client behavior. Runtime Exceptions: Subclasses throwing UnsupportedOperationException or silently breaking logic. Split fat inheritance hierarchies into granular, capability-specific interfaces. Interface Segregation (ISP) No client should be forced to depend on methods it does not use. Fat Interfaces: Monolithic interfaces forcing callers to mock or implement irrelevant methods. Role-focused

2026-07-28 原文 →
AI 资讯

🔄 The JavaScript Event Loop: From "What?" to "Oh, NOW I Get It!" (A Deep Dive)

The most misunderstood part of JavaScript — finally explained with analogies, diagrams, and zero hand-waving. If you've ever wondered why setTimeout(fn, 0) doesn't actually run in 0 milliseconds, or why Promises always run before your setTimeout callbacks, or how Node.js handles 10,000 simultaneous users on a single thread — you're about to have several "aha!" moments in a row. Buckle up. ☕ 🎤 Let's Start With an Icebreaker Pop quiz: What is JavaScript? Here's the most famous answer, often attributed to Philip Roberts' legendary JSConf talk: "JavaScript is a single-threaded, non-blocking, asynchronous, concurrent language. It has a Call Stack, an Event Loop, a Callback Queue, and some other APIs." Sounds sophisticated, right? Now ask the V8 engine the same question: "I have a Call Stack and a Memory Heap. I genuinely have no idea what those other things are." 🤯 That's the first paradox. The very features that make JavaScript powerful — the Event Loop, the queues, the async magic — are not part of the JavaScript engine itself . They live somewhere else entirely. Let's find out where. 📦 Part 1: The Basics You Need to Know JavaScript is Single-Threaded At its core, JavaScript has exactly one main thread of execution . This is the Golden Rule : One Thread = One Call Stack = One thing at a time. The Call Stack is a data structure that tracks where you are in your code. When you call a function, it gets pushed onto the stack. When it returns, it gets popped off. It follows a LIFO (Last In, First Out) principle — like a stack of plates. function greet ( name ) { console . log ( `Hello, ${ name } !` ); } function main () { greet ( " Ahmed " ); } main (); // Call Stack (reading bottom to top): // [greet] ← currently running // [main] // [global] Simple, right? But what happens when JavaScript encounters a task that takes time? 🚫 Part 2: The Problem — Blocking Imagine JavaScript has to fetch data from an API. That might take 2 seconds. Or it has to read a huge file from disk.

2026-07-26 原文 →
AI 资讯

How I replaced if statements with a Dictionary delegate in C#

Let's say you need to implement a feature that returns a different package based on the user-provided coupon code. So you start with a model: public record Package { public int Id { get ; set ; } public string Name { get ; set ; } public double Price { get ; set ; } } And you write a function that returns a different package based on the coupon code: private static Package GetPackageFromCoupon ( string coupon ) { if ( coupon == "ABC" ) { return new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }; } if ( coupon == "EBC" ) { return new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }; } if ( coupon == "DDD" ) { return new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }; } return new Package { Id = 1000 , Name = "Soda" , Price = 1.00 }; } And invoke it from your main method: internal class Program { static void Main ( string [] args ) { var package = GetPackageFromCoupon ( "ABC" ); Console . WriteLine ( package ); Console . ReadLine (); } } Quick test Provide expected parameters and inspect the results. "ABC" => Package { Id = 1 , Name = PS5 Controller , Price = 50 } "EBC" => Package { Id = 2 , Name = Iphone X , Price = 200 } "DDD" => Package { Id = 3 , Name = X7 Mouse , Price = 20 } Works as expected. Also, if you enter something that doesn't exist: "a" => Package { Id = 1000 , Name = Soda , Price = 1 } The Problem What if you need to add more coupon codes and return different variations of the Package object? Well, it's gonna get pretty messy very soon. Quick solution - Dictionary Rather than writing every possible variation in the if block, create a dictionary where the key is the coupon code and the value is the Package: private static readonly Dictionary < string , Package > _packages = new () { [ "ABC" ] = new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }, [ "EBC" ] = new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }, [ "DDD" ] = new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }, }; The next step is to

2026-07-24 原文 →
开发者

Why wordpress.org Won't Let You Install Composer Packages From a Plugin

Cross-posted from the Loopress docs Loopress is a toolset to make WordPress reproducible and reviewable via Git . Versioned snippets, Composer without SSH, and more coming... Check Loopress WordPress doesn't have a package manager. If you want a PHP library in your project, be it Guzzle for HTTP calls or a PDF generation library in a snippet, you're either vendoring the code by hand or running Composer somewhere the WordPress admin can't see. We built a feature to fix that: a Composer UI inside the WordPress admin. Search Packagist, install a package, audit it for known vulnerabilities, all without SSH access ( full walkthrough here ). Before shipping it, we asked the wordpress.org plugin review team whether it would be acceptable in the official directory. The answer was no. The rule Here's the relevant line from Guideline 8 of the wordpress.org plugin directory: "Plugins may not send executable code via third-party systems." Installing a PHP package from Packagist is, by definition, downloading executable code from a third party and writing it to disk. It doesn't matter that our plugin never calls the installed code's autoloader itself, that the user has to load it deliberately from their own snippet. The review team was clear: the indirection changes nothing. The mere presence of that capability is enough to trigger the rule, whether or not it's ever used. There's no folder you can hide it in that makes it acceptable, they weren't shy about saying that outright. If you want PHP dependencies in a plugin distributed on wordpress.org, the only accepted path is to vendor them at submission time: ship the code, with a compatible license and readable source, not fetch it dynamically. For us, that meant Composer package management could never live in the same plugin that ships on wordpress.org. Full stop, no clever workaround changes that. What we tried first, and undid Our first move was the obvious one: split into two plugins. A "Core" plugin with snippet sync, distri

2026-07-20 原文 →
AI 资讯

# 🚀 C++ Abstraction Cheat Sheet: 10-Minute Interview Revision Guide

If you have an interview in the next few hours and need to quickly revise Abstraction in C++ , this guide is for you. No long theory. No unnecessary examples. Only the concepts interviewers expect you to know. 📌 What is Abstraction? Definition Abstraction is the process of exposing only the essential behavior of an object while hiding unnecessary implementation details. Remember WHAT ↓ Hide HOW The user knows what an object can do, but not how it performs the work. ❓ Why Do We Need Abstraction? Without abstraction: Every developer needs to understand internal implementation. Client code becomes tightly coupled. Maintenance becomes difficult. With abstraction: Developers interact with a simple interface. Internal implementation can change without affecting users. Systems become easier to extend and maintain. Benefits ✅ Reduces complexity ✅ Promotes loose coupling ✅ Improves maintainability ✅ Supports extensibility ✅ Enables cleaner architecture ⚙️ How Does C++ Achieve Abstraction? C++ primarily achieves abstraction using: Abstract Class + Pure Virtual Functions + Runtime Polymorphism 🏗️ What is an Abstract Class? An abstract class is a class that contains at least one pure virtual function . It represents a: ✅ Contract ✅ Blueprint ✅ Common capability Because it is incomplete , it cannot be instantiated . 🎯 What is a Pure Virtual Function? Syntax virtual ReturnType functionName () = 0 ; Meaning It tells the compiler: Every concrete derived class must implement this function. = 0 does NOT mean "return zero." It simply marks the function as pure virtual . 🧠 Mental Model Think of it like this: Job Description ↓ Employee The job description defines responsibilities. Each employee fulfills those responsibilities differently. Or: Blueprint ↓ House You don't live inside a blueprint. You build a house from it. Similarly, you don't create objects of an abstract class—you create objects of concrete derived classes. 🏭 Practical Software Example Imagine an e-commerce application

2026-07-15 原文 →