GO-V.ORG
As seen in

Strongly typed identifier

A strongly typed identifier is user-defined data type which serves as an identifier or key that is strongly typed. This is a solution to the "primitive obsession" code smell as mentioned by Martin Fowler. The data type should preferably be immutable if possible. It is common for implementations to handle equality testing, serialization and model binding. The strongly typed identifier commonly wraps the data type used as the primary key in the database, such as a string, an integer or universally unique identifier (UUID). Web frameworks can often be configured to model bind properties on view models that are strongly typed identifiers. Object–relational mappers can often be configured with... Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.

A strongly typed identifier is user-defined data type which serves as an identifier or key that is strongly typed. This is a solution to the "primitive obsession" code smell as mentioned by Martin Fowler. The data type should preferably be immutable if possible. It is common for implementations to handle equality testing, serialization and model binding. The strongly typed identifier commonly wraps the data type used as the primary key in the database, such as a string, an integer or universally unique identifier (UUID). Web frameworks can often be configured to model bind properties on view models that are strongly typed identifiers. Object–relational mappers can often be configured with value converters to map data between the properties on a model using strongly typed identifier data types and database columns. /// /// Represents a user identifier. /// /// The user identifier. public sealed record UserId(Guid Id) { /// /// Initializes a new instance of the record. /// /// A new UserId object. public static UserId New() => new(Guid.NewGuid()); public override string ToString() => Id.ToString(); } import std; using std::string; class UserId { private: const string id; public: explicit UserId(const string& id): id{id} {} nodiscard string getId() const noexcept { return id; } nodiscard bool operator==(const UserId& rhs) const noexcept { return id == rhs.getId(); } }; require "uuid" Represents a user identifier. record UserId, id : String do def initialize() @id = UUID.v4.to_s end def to_s(io) io import std; /** Represents a user identifier. */ immutable struct UserId { immutable UUID id; /** Initializes a new instance of the UserId struct. */ this(immutable string id) { this.id = UUID(id); } public static UserId create() { return UserId(randomUUID.toString()); } string toString() { return this.id.toString(); } } import 'package:meta/meta.dart'; /// Represents a user identifier. @immutable final class UserId { final String id; /// Initializes a new instance of the UserId struct. const UserId(this.id); @override operator ==(other) => other is UserId && other.id == id; @override int get hashCode => id.hashCode; @override String toString() => id; } open System /// /// Represents a user identifier. /// /// The user identifier. type UserId(id: Guid) = member x.id = id static member New() = Guid.NewGuid() static member Empty = Guid.Empty override x.Equals(b) = match b with | :? UserId as p -> id = p.id | _ -> false override x.GetHashCode() = hash id override x.ToString() = id.ToString() // Represents a user identifier. type UserId struct{ id string } // Creates a new user identifier. func NewUserId(id string) UserId { return UserId{id: id} } func (x UserId) String() string { return x.id } /** * Represents a user identifier. * * @param id The user identifier. */ record UserId(String id) { String toString() { id } } -- Represents a user identifier. newtype UserId = UserId String deriving (Eq, Read, Show) import java.util.UUID; /** * Represents a user identifier. * @param id The user identifier. */ public final record UserId(UUID id) { /** * Initializes a new instance of the UserId record. * @return A new UserId object. */ public static UserId newId() { return new UserId(UUID.randomUUID()); } public String toString() { return id.toString(); } } class UserId { #id; constructor(id) { if (id == undefined) { throw new TypeError("Argument is null or undefined."); } this.#id = id; Object.freeze(this); } static empty = new this.prototype.constructor("00000000-0000-0000-0000-000000000000"); static new() { return new this.prototype.constructor(crypto.randomUUID()); } equals(id) { return id instanceof this.constructor && this.#id === id.valueOf(); } toJSON() { return this.#id; } toString() { return this.#id; } valueOf() { return this.#id; } } using UUIDs "Represents a user identifier." struct UserId id::UUID end Base.string(userId::UserId) = userId.id /** * Represents a user identifier. * * @property id The user identifier. * @constructor Creates a user identifier. */ @JvmInline public value class UserId(public val id: String) { override fun toString() = id } Represents a user identifier. type UserId* = distinct string /** * Represents a user identifier. */ final class UserId implements JsonSerializable { use StronglyTypedIdentifier; } /** * Provides methods for use with strongly typed identifiers. */ trait StronglyTypedIdentifier { /** * Initializes a new instance of the UserId object. * @param string $id The user identifier. */ public function __construct(public readonly string $id) {} /** * Creates a new user identifier. */ public static function new(): self { return new self(bin2hex(random_bytes(16))); } public function jsonSerialize(): string { return $this->id; } public function __toString(): string { return $this->id; } } import uuid from dataclasses import dataclass from uuid import UUID @dataclass(frozen=True) class UserId: """Represents a user identifier.""" id: UUID @staticmethod def new() -> Self: """Create a new user identifier.""" return __class__(uuid.uuid4()) def __str__(self) -> str: return str(self.id) Python also has NewType which can be used to create new data types. from typing import NewType UserId: NewType = NewType('UserId', int) role StronglyTypedIdentifier { has Str $.id is required; multi method new(Str $id) { self.bless(:$id); } multi method gist(StronglyTypedIdentifier:U:) { self.^name } multi method gist(StronglyTypedIdentifier:D:) { self.id } method Str() { "$!id" } method empty() { self.new("00000000-0000-0000-0000-000000000000") } } class UserId does StronglyTypedIdentifier {} require 'securerandom' Represents a user identifier. UserId = Data.define(:id) do # Create a new user identifier. def self.create self.new(SecureRandom.uuid) end def self.empty self.new('00000000-0000-0000-0000-000000000000') end def to_s id end end // Represents a user identifier. [derive(Debug, PartialEq)] pub struct UserId(String); import java.util.UUID /** Represents a user identifier. * * @constructor * Create a new user identifier. * @param id * The user identifier. */ sealed case class UserId(id: UUID) object UserId: /** Initializes a new instance of the UserId class. */ def create(): UserId = UserId(UUID.randomUUID()) import Foundation /// Represents a user identifier. struct UserId: CustomStringConvertible, Equatable { private let id: UUID init(_ id: UUID) { self.id = id } var description: String { return id.uuidString.lowercased } /// Creates a new user identifier. static func new() -> Self { return Self(UUID()) } } /** Represents a user identifier. */ export type UserId = string & { readonly __brand: unique symbol }; /// Represents a user identifier. const UserId = struct { value: i32, /// Initializes a new instance of the UserId struct. pub fn init(value: i32) UserId { return UserId{ .value = value }; } };

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Strongly typed identifier". 1778951466. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1354488552

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·