javascript / expert
Snippet
Encapsulated Class Hierarchy with Private Field Interceptors in Service Classes
Demonstrates Object-Oriented Programming (OOP) in JavaScript using ES2022 private class fields (`#`) and abstract base class patterns for Next.js service architecture. It enforces encapsulation and strict interface inheritance for backend domain handlers.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export class BaseServiceHandler {#secretKey;constructor(secretKey) {this.#secretKey = secretKey;}get secret() {return this.#secretKey;}execute(req) {throw new Error("Abstract method execute() must be overridden");}}export class UserRegistrationHandler extends BaseServiceHandler {#allowedRoles = new Set(['admin', 'editor', 'viewer']);execute(payload) {if (!this.#allowedRoles.has(payload.role)) {return { success: false, reason: "Invalid role delegation" };}return { success: true, digest: `${payload.username}:${this.secret}` };}}
nextjs
Breakdown
1
#secretKey;
Declares a hard private instance field inaccessible outside the defining class scope.
2
constructor(secretKey) { this.#secretKey = secretKey; }
Initializes the private state during object instantiation.
3
get secret() { return this.#secretKey; }
Provides a read-only getter to safely expose private encapsulated data.
4
export class UserRegistrationHandler extends BaseServiceHandler {
Establishes sub-class inheritance extending abstract base behavior.
5
#allowedRoles = new Set(['admin', 'editor', 'viewer']);
Encapsulates instance-specific validation state within a private Set property.
6
execute(payload) {
Overrides the polymorphic base method with concrete business logic.