Skip to content

Constraint 0030

Title

Java programming language rules and standards

Description

This set of constraints defines the state-of-the-art rules and architectural standards for Java development within the project, specifically tailored for robust Object-Oriented design, uncompromised static typing, deterministic memory/thread boundaries, and high-performance numerical/signal processing workflows (DeepLearning4j, ZeroMQ).

1. Robustness, Input Defenses & Parameter Sanitization

  • [CS-0030.1] Mandatory Precondition Defenses & Parameter Sanitization: Every constructor, public method, package-private method, and protected method shall start with explicit parameter validation and sanitization.
  • [CS-0030.1.1] Null Rejection: Object parameters shall be validated using java.util.Objects.requireNonNull with a descriptive error message immediately upon entry.
  • [CS-0030.1.2] Range and Boundary Bounds: Numerical limits, sample rates, array lengths, and buffer indices shall be explicitly validated against valid domain ranges. Invalid parameters shall immediately trigger an IllegalArgumentException or IndexOutOfBoundsException before any state mutation occurs.
  • [CS-0030.1.3] String & URI Sanitization: String parameters shall be checked for null or whitespace-only inputs (str.trim().isEmpty()) and sanitized before execution to prevent invalid URLs, SQL parameter injections, or empty identifiers.

2. Object-Oriented Design & Bounded Resource Execution

  • [CS-0030.4] Bounded Object Instantiation & Pools: Continuous execution paths (e.g. real-time audio sample demodulation loops, frame streams) shall enforce a bounded object allocation model. Unbounded instantiation in high-frequency loops is forbidden. Reusable ring buffers, object pools, or off-heap memory blocks shall be utilized to maintain zero GC retention and prevent heap exhaustion.
  • [CS-0030.5] Bounded Threading Execution Models: The manual instantiation of unmanaged threads (new Thread().start()) or unbounded thread pools (Executors.newCachedThreadPool()) is strictly prohibited. All concurrent tasks shall execute within globally bounded, explicitly sized thread pools configured with dedicated work queues and explicit rejection handlers (RejectedExecutionHandler).
  • [CS-0030.6] Object-Oriented Behavioral Patterns: Core domain logic shall leverage expressive Object-Oriented patterns to encapsulate complexity:
  • [CS-0030.6.1] State Pattern: Protocol handshakes and finite state machines must be modeled using the State pattern (with separate state classes implementing a common interface) rather than complex, error-prone nested if/switch blocks.
  • [CS-0030.6.2] Strategy Pattern: Interchangeable algorithms (e.g. signal modulation codecs, error-correction schemes) shall be cleanly encapsulated via the Strategy pattern.
  • [CS-0030.6.3] Factory Pattern: Complex object instantiation shall be governed by Static Factory Methods or dedicated Factory classes that enforce complete pre-construction validation.
  • [CS-0030.7] Strong Immutability & Encapsulation: Classes shall enforce uncompromised encapsulation. All fields must be private and, whenever possible, declared final. Class invariants must be completely established by the end of the constructor execution.

3. Exhaustive Exception Processing & Lifecycle Management

  • [CS-0030.8] Exhaustive Exception Protection: All execution paths must be fully protected against runtime failures. Absolutely no instruction that can throw checked or unchecked/runtime exceptions (e.g. NullPointerException, IndexOutOfBoundsException, OutOfMemoryError, ClassCastException, XmlPullParserException) shall be left unhandled or allowed to crash an application thread or Activity.
  • [CS-0030.8.1] Boundary & Instruction Interception: Every method, asynchronous entry point, background worker, network loop, or XML stream step must wrap potentially faulty instructions in targeted or top-level try-catch blocks to intercept, log, and gracefully process all potential failures.
  • [CS-0030.8.2] Domain Exception Translation & Graceful Recovery: Low-level operational or runtime exceptions (e.g. IOException, ZMQException, SQLite CursorWindow OOMs) shall be caught and translated into clean domain responses or logged warnings without terminating execution.
  • [CS-0030.9] Mandatory try-with-resources: Any resource implementing java.lang.AutoCloseable or java.io.Closeable must be strictly managed using a try-with-resources statement to ensure guaranteed, deterministic resource disposal.
  • [CS-0030.9.1] DeepLearning4j Off-Heap Scopes: Native arrays (INDArray) and ND4J MemoryWorkspace contexts allocate off-heap memory directly. Their lifecycles must be strictly bounded using try-with-resources blocks to ensure prompt, deterministic off-heap deallocation.
  • [CS-0030.9.2] Transport Sockets & Streams: ZeroMQ contexts/sockets, file streams, and network buffers must be initialized within try-with-resources declarations. Manual calls to .close() inside finally blocks are forbidden as they risk masking primary exceptions.

4. Core Java Typing & Application Architecture

  • [CS-0030.10] Strong and Explicit Typing Mandate: Local variable type inference (var) is strictly forbidden. Every variable, field, parameter, and return type shall be explicitly declared with its concrete or interface type to ensure absolute static typing clarity and straightforward reviewability.
  • [CS-0030.11] Semantic POJOs & Equality Contracts: Data carriers shall be implemented as standard Java classes. Every data carrier class shall implement robust, explicit equals and hashCode methods using Objects.equals/Objects.hash. Array fields must be compared using Arrays.equals or Arrays.deepEquals. DeepLearning4j tensors shall segregate precision-tolerant equality comparisons from standard identity checks.
  • [CS-0030.12] Sealed Hierarchies for Exhaustive Modeling: Bounded domain models and signal frame structures shall utilize sealed interfaces or classes to ensure exhaustive pattern matching at compile-time.
  • [CS-0030.13] Constructor Dependency Injection: Spring Boot/enterprise component wiring shall strictly use explicit constructor injection. Field injection via @Autowired is prohibited. Components shall aim for absolute immutability with final fields initialized via a single validated constructor.
  • [CS-0030.14] GraalVM Native Image Reachability: Application code must maintain structural compatibility with GraalVM Native Image ahead-of-time compilation. Unmanaged runtime reflection without configured reachability metadata is prohibited.

5. Clean Code Traceability, Logging & Verification Standards

  • [CS-0030.15] Traceability Reference Mandate: Every class, interface, method, and logically distinct block must include comment annotations referencing the explicit requirement, feature request, task, or bug fix it addresses, in perfect compliance with CS-0010 and CS-0020.
  • [CS-0030.16] Comprehensive & Consistent Log Instrumentation: Every class and non-trivial method shall incorporate explicit logger instrumentation (using java.util.logging.Logger or SLF4J). Log levels must be adapted consistently:
  • FINE / DEBUG: Detailed execution trace, method entry parameters, loop steps, and non-fatal handled exceptions.
  • INFO: Key lifecycle events, job start/completion summaries, background worker results, and successful database transactions.
  • WARNING: Recoverable network failures, duplicate item skips, HTTP non-200 responses, and non-fatal data parsing errors.
  • SEVERE / ERROR: Unrecoverable errors, fatal component exceptions, and IO failures.
  • [CS-0030.17] Standardized Verification Stack: Unit and integration testing shall utilize JUnit 5, AssertJ fluent assertions, and Mockito. External transport components shall be verified using Testcontainers. Tests shall systematically assert semantic equality implementations, edge-case invalid audio payloads, null safety contracts, and execute stress verification suites for concurrent pipelines.

Rationale

High-performance domain applications, such as real-time Data-over-Sound exchanges, depend fundamentally on rock-solid input validation, absolute memory/resource safety, and deterministic execution bounds. By enforcing aggressive defensive programming (preconditions, null safety, copy-on-boundary), mandatory try-with-resources lifecycles, global thread/object bounds, expressive Object-Oriented patterns, and uncompromised strong typing, CS-0030 ensures bulletproof stability, eliminates runtime resource exhaustion, and guarantees architectural clarity.

Verification

Compliance with CS-0030 rules shall be validated continuously using automated CI/CD gatekeepers, static analysis, and peer reviews:

  • Static Code Analysis: Integration of Checkstyle, PMD, and SonarQube rules configured to detect unmanaged resource allocations, absent precondition checks, local var usage, missing traceability annotations, and unhandled boundary paths.
  • Resource Exhaustion & Leak Verification: Automated continuous execution under memory/thread profilers asserting absolutely flat memory and thread profiles across long-running DL4J/ZMQ signal workflows.
  • Peer Review Gateways: Rigorous peer validation enforcing defensive parameter boundaries, correct mapping of OO patterns (State, Strategy, Factory), comprehensive exception protection on every asynchronous/external thread path, and correct implementation of semantic POJOs.