base

package
v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package base provides the core interfaces and implementations for value objects.

This package serves as the foundation for the valueobject framework, defining the essential interfaces that all value objects should implement and providing base implementations for common value object types.

Key interfaces defined in this package:

  • ValueObject: The base interface for all value objects, defining methods for string representation and emptiness checking.
  • Equatable: For value objects that can be compared for equality.
  • Comparable: For value objects that can be compared for ordering.
  • Validatable: For value objects that can be validated.
  • JSONMarshallable: For value objects that can be marshalled to JSON.
  • JSONUnmarshallable: For value objects that can be unmarshalled from JSON.

Base implementations provided:

  • StringValueObject: A base implementation for string-based value objects.
  • StructValueObject: A base implementation for struct-based value objects.

The package also provides utility functions for common value object operations and validation helpers to ensure value objects maintain their invariants.

Example usage:

// Define a custom string-based value object
type Email struct {
    base.StringValueObject
}

// Create a constructor with validation
func NewEmail(value string) (*Email, error) {
    // Create the value object
    email := &Email{}

    // Initialize with validation
    if err := email.Init(value); err != nil {
        return nil, err
    }

    // Additional validation
    if !strings.Contains(value, "@") {
        return nil, errors.New("invalid email format")
    }

    return email, nil
}

The base package is designed to be extended by more specific value object types in other subpackages, providing a consistent foundation for all value objects in the application.

Package base provides common interfaces and utilities for value objects.

Package base provides common interfaces and utilities for value objects.

Package base provides common interfaces and utilities for value objects.

Package base provides common interfaces and utilities for value objects.

Package base provides common interfaces and utilities for value objects.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyValue is returned when a required value is empty.
	ErrEmptyValue = errors.New("value cannot be empty")

	// ErrInvalidFormat is returned when a value has an invalid format.
	ErrInvalidFormat = errors.New("invalid format")

	// ErrOutOfRange is returned when a value is out of the allowed range.
	ErrOutOfRange = errors.New("value out of allowed range")
)
View Source
var (
	// EmailRegex is a regular expression for validating email addresses.
	EmailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

	// URLRegex is a regular expression for validating URLs.
	URLRegex = regexp.MustCompile(`^(https?|ftp)://[^\s/$.?#].[^\s]*$`)

	// PhoneRegex is a regular expression for validating phone numbers.
	PhoneRegex = regexp.MustCompile(`^\+?[0-9]{1,3}[-\s]?[0-9]{1,14}$`)

	// UsernameRegex is a regular expression for validating usernames.
	UsernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,20}$`)

	// CurrencyCodeRegex is a regular expression for validating ISO currency codes.
	CurrencyCodeRegex = regexp.MustCompile(`^[A-Z]{3}$`)
)

Common validation regular expressions

Functions

func CompareFloats

func CompareFloats(a, b float64) int

CompareFloats compares two float64 values with a small epsilon to handle floating point precision. Returns: -1 if a < b

0 if a == b
1 if a > b

func CompareStrings

func CompareStrings(a, b string) int

CompareStrings compares two strings case-insensitively. Returns: -1 if a < b

0 if a == b
1 if a > b

func FloatsEqual

func FloatsEqual(a, b float64) bool

FloatsEqual checks if two float64 values are equal, with a small epsilon to handle floating point precision.

func IsEmptyString

func IsEmptyString(s string) bool

IsEmptyString checks if a string is empty after trimming whitespace.

func IsZeroFloat

func IsZeroFloat(f float64) bool

IsZeroFloat checks if a float64 is zero, with a small epsilon to handle floating point precision.

func RoundFloat

func RoundFloat(f float64, places int) float64

RoundFloat rounds a float64 to the specified number of decimal places.

func StringsEqualFold

func StringsEqualFold(a, b string) bool

StringsEqualFold checks if two strings are equal, ignoring case.

func TrimAndNormalize

func TrimAndNormalize(s string) string

TrimAndNormalize trims whitespace and normalizes a string. This is useful for value objects that need to normalize their string representation.

func ValidateCurrencyCode

func ValidateCurrencyCode(code string) error

ValidateCurrencyCode validates an ISO currency code.

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates an email address.

func ValidatePhone

func ValidatePhone(phone string) error

ValidatePhone validates a phone number.

func ValidateURL

func ValidateURL(url string) error

ValidateURL validates a URL.

func ValidateUsername

func ValidateUsername(username string) error

ValidateUsername validates a username.

func WithValidation

func WithValidation[T any](vo T, err error) (T, error)

WithValidation is a helper function that validates a value object after creation. It's useful for constructor functions that need to validate the created object. Example usage:

func NewMyValueObject(value string) (MyValueObject, error) {
    vo := MyValueObject{value: value}
    return WithValidation(vo, vo.Validate())
}

Types

type BaseStructValueObject

type BaseStructValueObject struct{}

BaseStructValueObject is a base implementation of StructValueObject. It provides common functionality for struct-based value objects. Embed this struct in your value object to inherit its functionality.

func (BaseStructValueObject) IsEmpty

func (vo BaseStructValueObject) IsEmpty() bool

IsEmpty checks if the value object is empty (zero value). This is a default implementation that always returns false. Override this method in your value object to provide a proper implementation.

func (BaseStructValueObject) MarshalJSON

func (vo BaseStructValueObject) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. This is a default implementation that uses the ToMap method. Override this method in your value object to provide a more efficient implementation.

func (BaseStructValueObject) String

func (vo BaseStructValueObject) String() string

String returns the string representation of the value object. This is a default implementation that returns a generic string. Override this method in your value object to provide a proper implementation.

func (BaseStructValueObject) ToMap

func (vo BaseStructValueObject) ToMap() map[string]interface{}

ToMap converts the value object to a map[string]interface{}. This is a default implementation that returns an empty map. Override this method in your value object to provide a proper implementation.

type Comparable

type Comparable[T any] interface {
	// CompareTo compares this value object with another and returns:
	// -1 if this < other
	//  0 if this == other
	//  1 if this > other
	CompareTo(other T) int
}

Comparable is an interface for value objects that can be compared for ordering.

type Equatable

type Equatable[T any] interface {
	// Equals checks if two value objects are equal.
	Equals(other T) bool
}

Equatable is an interface for value objects that can be compared for equality.

type JSONMarshallable

type JSONMarshallable interface {
	// MarshalJSON implements the json.Marshaler interface.
	MarshalJSON() ([]byte, error)
}

JSONMarshallable is an interface for value objects that can be marshalled to JSON.

type JSONUnmarshallable

type JSONUnmarshallable interface {
	// UnmarshalJSON implements the json.Unmarshaler interface.
	UnmarshalJSON(data []byte) error
}

JSONUnmarshallable is an interface for value objects that can be unmarshalled from JSON.

type StringValueObject

type StringValueObject struct {
	// contains filtered or unexported fields
}

StringValueObject is a base type for string-based value objects. It implements the ValueObject and Equatable interfaces.

func NewStringValueObject

func NewStringValueObject(value string) StringValueObject

NewStringValueObject creates a new StringValueObject with the given value.

func (StringValueObject) Equals

func (vo StringValueObject) Equals(other StringValueObject) bool

Equals checks if two StringValueObjects are equal. This is a case-sensitive comparison. For case-insensitive comparison, use EqualsIgnoreCase.

func (StringValueObject) EqualsIgnoreCase

func (vo StringValueObject) EqualsIgnoreCase(other StringValueObject) bool

EqualsIgnoreCase checks if two StringValueObjects are equal, ignoring case.

func (StringValueObject) IsEmpty

func (vo StringValueObject) IsEmpty() bool

IsEmpty checks if the value object is empty (zero value).

func (StringValueObject) String

func (vo StringValueObject) String() string

String returns the string representation of the value object.

func (StringValueObject) Value

func (vo StringValueObject) Value() string

Value returns the underlying string value.

func (StringValueObject) WithValue

func (vo StringValueObject) WithValue(value string) StringValueObject

WithValue returns a new StringValueObject with the given value.

type StructValueObject

type StructValueObject interface {
	ValueObject
	// ToMap converts the value object to a map[string]interface{}.
	ToMap() map[string]interface{}
	// MarshalJSON implements the json.Marshaler interface.
	MarshalJSON() ([]byte, error)
}

StructValueObject is a base interface for struct-based value objects. It extends the ValueObject interface with methods specific to struct-based value objects.

type Validatable

type Validatable interface {
	// Validate checks if the value object is valid.
	// Returns nil if valid, otherwise returns an error.
	Validate() error
}

Validatable is an interface for value objects that can be validated.

type ValueObject

type ValueObject interface {
	// String returns the string representation of the value object.
	String() string

	// IsEmpty checks if the value object is empty (zero value).
	IsEmpty() bool
}

ValueObject is the base interface for all value objects. It defines the common methods that all value objects should implement.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL