Skip to content

refactor: Add newtype for Topic #29

Description

@tomverelst

Problem

Topics are represented as plain String throughout the codebase. This allows invalid values (empty strings, invalid characters) to propagate.

Suggestion

Create a newtype with validation:

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Topic(String);

impl Topic {
    pub fn new(s: impl Into<String>) -> Result<Self, ValidationError> {
        let s = s.into();
        if s.is_empty() {
            return Err(ValidationError::EmptyTopic);
        }
        // Kafka topic name rules: alphanumeric, '.', '_', '-'
        if !s.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '_' || c == '-') {
            return Err(ValidationError::InvalidTopicCharacters);
        }
        Ok(Topic(s))
    }
    
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

Impact

  • Catches invalid topic names at parse time
  • Makes APIs self-documenting
  • Prevents bugs from invalid string manipulation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions