Utility Functions Library
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendix
Introduction
This document is a practical reference for Sparrow's utility functions library, focusing on the following capabilities:
- ID Generation Tools: UUID generation and Snowflake ID generator
- Type Conversion Tools: String, integer, time, naming style conversion and pluralization
- Sorting Tools: Generic entity sorting, stable sorting, sorting by JSON tag fields, random shuffling
- Time Processing Tools: Time parsing and naming style conversion
- Type Name Tools: Generic type name and short type name extraction
- Extensions and Best Practices: How to correctly use these tools in projects, avoid common pitfalls, and provide extension and custom development guides
Project Structure
Utility functions are mainly located in the pkg/utils directory, combined with the SortField structure in usecase for sorting control; some repository layers call sorting tools; there is also a codes directory providing Snowflake ID and code generator as supplementary solutions for ID generation.
Core Components
ID Generation Tools
- UUID Generation: Provides globally unique string ID
- Snowflake ID Generation: High-throughput distributed ID based on timestamp, machine ID, sequence number
- Code Generation: Prefix + date + random code style encoding
Type Conversion Tools
- String/Integer/Boolean/Float/Pointer/Struct and other general conversions
- Time Parsing: RFC3339, common local formats, Unix second timestamps
- Naming Style Conversion: Underscore, Pascal, camelCase, kebab, plural
Sorting Tools
- Generic Entity Sorting: Supports default descending by creation time, ascending/descending by field
- Reflection Field Access: Supports direct field name and JSON tag mapping
- Random Shuffling: Fisher-Yates shuffle
Time Processing Tools
- ParseTime: Unified parsing of multiple time inputs
- Naming Style Conversion: Align with database/frontend naming conventions
Type Name Tools
- GetTypeName/GetShortTypeName: Get full name and short name of generic types
Architecture Overview
The position and interaction of utility functions in the system is as follows:
Detailed Component Analysis
ID Generation Tools
UUID Generation
- Function: Generate globally unique string ID
- Parameters: None
- Returns: String ID
- Usage Example Path: Generation Example
- Performance Characteristics: Depends on third-party library, low generation overhead, suitable for most scenarios
- Applicable Scenarios: General primary key, temporary identifier, log trace ID
Snowflake ID Generator
- Function: High-throughput distributed ID, containing timestamp, machine ID, sequence number
- Parameters: Machine ID (0-1023), optional start timestamp
- Returns: 64-bit integer ID
- Usage Example Path: Construction and Generation
- Performance Characteristics: Single machine high throughput, avoid cross-machine clock drift; sequence number limit 4095 within same millisecond
- Applicable Scenarios: High concurrent writes, strong consistency ordering requirements
Code Generator
- Function: Prefix + date + random code style encoding
- Parameters: Business prefix
- Returns: String code
- Usage Example Path: Code Generation
- Performance Characteristics: Simple and easy to use, human-readable
- Applicable Scenarios: Order numbers, task numbers and other business codes
Type Conversion Tools
ToString
- Function: Convert any type to string
- Parameters: Any interface
- Returns: String
- Usage Example Path: String Conversion
ToInt
- Function: Convert any type to int
- Parameters: Any interface
- Returns: int
- Usage Example Path: Integer Conversion
ParseTime
- Function: Parse multiple time inputs to time.Time
- Parameters: String, RFC3339, local format, Unix second timestamp
- Returns: time.Time
- Usage Example Path: Time Parsing
Naming Style Conversion
- Camel/Pascal/Snake/Kebab: Convert between underscore, Pascal, camelCase, kebab
- Parameters: String
- Returns: Converted string
- Usage Example Path: Naming Conversion
Pluralization
- Function: Simple rule English plural conversion
- Parameters: String
- Returns: Plural form
- Usage Example Path: Pluralization
Sorting Tools
SortEntities
- Function: Stable sort entity slices
- Parameters:
- entities: Any generic slice
- sortFields: Sort field list (usecase.SortField)
- defaultSortByCreatedAt: Whether to default descending by creation time
- Returns: None (in-place modification)
- Usage Example Path: Sorting Test
- Algorithm Implementation Points:
- Default sorting: If entity implements creation time interface, sort by time descending
- Field sorting: Prioritize comparing each field, supports string/int/float/bool/time
- Field location: Prioritize by field name, then by JSON tag matching
- Performance Characteristics: Stable sort O(n log n), default path avoids reflection, field sorting path uses reflection
- Usage Recommendations:
- Implement creation time interface for entities to get more efficient default sorting
- Ensure fields exist and are comparable when sorting by field
compareEntities
- Function: Compare two entities' specified fields through reflection
- Usage Example Path: Field Comparison
getFieldByJSONTag
- Function: Find field by JSON tag
- Usage Example Path: JSON Tag Lookup
compareValues
- Function: Compare based on field type
- Usage Example Path: Value Comparison
ShuffleStrings
- Function: Fisher-Yates shuffle
- Parameters: String slice
- Returns: None (in-place modification)
- Usage Example Path: Shuffle
Time Processing Tools
ParseTime
- Supported Inputs: RFC3339, local format, Unix second timestamp
- Returns: time.Time; returns zero value on parse failure
- Usage Example Path: Time Parsing
Naming Style Conversion
- Align with database/frontend naming conventions, convenient for serialization/deserialization
- Usage Example Path: Naming Conversion
Type Name Tools
GetTypeName
- Function: Get full name of generic type
- Parameters: None (generic)
- Returns: String
- Usage Example Path: Type Name Retrieval
GetShortTypeName
- Function: Get short type name (remove package path)
- Parameters: None (generic)
- Returns: String
- Usage Example Path: Short Type Name Retrieval
Dependency Analysis
- SortEntities depends on usecase.SortField definition
- Repository layer (such as RedisRepository) implements sorting by calling utils.SortEntities
- Naming conversion tools are used by multiple repository layers for field naming normalization
- ID generation tools are used in multiple places by repository layer for generating entity IDs
Performance Considerations
SortEntities
- Default path avoids reflection, prioritizes type assertion to get creation time, complexity O(n log n)
- Field sorting path uses reflection, pay attention to field count and entity scale
ShuffleStrings
- Fisher-Yates shuffle, time complexity O(n), space complexity O(1)
ParseTime
- Multi-format attempt parsing, pay attention to input format consistency to reduce failed retries
Naming Conversion
- String concatenation and splitting, pay attention to caching intermediate results in high-frequency scenarios
Troubleshooting Guide
Sorting Invalid or Abnormal
- Confirm entity implements creation time interface (if relying on default sorting)
- Confirm sort field name matches entity field or JSON tag
- Reference test cases to verify behavior: Sorting Test
Naming Conversion Result Not As Expected
- Check if input string contains mixed case and numbers
- Reference conversion function implementation: Naming Conversion
Time Parsing Failure
- Confirm input format conforms to RFC3339 or local format
- Reference parsing logic: Time Parsing
Type Name Tool Abnormal
- Confirm passing concrete type not interface type
- Reference test cases: Type Name Test
Conclusion
Sparrow's utility functions library provides a practical toolset covering ID generation, type conversion, sorting, time processing and type name extraction. Through generics and stable sorting strategies, combined with naming conventions and time parsing capabilities, it can meet most engineering scenario needs. It is recommended to follow the principle of "default path first, field sorting cautiously, naming style unified" in projects, and choose appropriate ID generation schemes in high-concurrency scenarios.
Appendix
Usage Examples and Best Practices
ID Generation
- General scenarios use UUID: UUID Generation
- High-throughput scenarios use Snowflake ID: Snowflake ID Construction and Generation
- Business codes use code generator: Code Generation
Type Conversion
- Unified string/integer conversion: ToString/ToInt
- Time parsing: ParseTime
- Naming style conversion: Camel/Pascal/Snake/Kebab
Sorting
- Default descending by creation time: Default Sorting
- Sort by field: Field Sorting
- Random shuffle: Shuffle
Type Name
- Get full type name and short name: Type Name Tools
Extension Development Guide
Add New Sort Field
- Define SortField in usecase layer and pass to utils.SortEntities
- Reference: SortField Definition
Custom Entity Sorting
- Implement creation time interface for entities to enable default sorting path
- Reference: Default Sorting Logic
Custom ID Generation
- Can extend machine ID/start time strategy based on Snowflake ID generator
- Reference: Snowflake ID Generator
Naming Style Extension
- Can add new naming conversion functions in conv.go, following existing style
- Reference: Naming Conversion Implementation