You're right, using .map() for validation within the TryFrom implementation isn't ideal. It mixes concerns (mapping and validation) and can make the code harder to read. Here's a refactored version with a more structured approach:
Refactored Code:
#[derive(FromRow)]
struct DbAlbum {
id: Vec<u8>,
name: String,
artist_id: Vec<u8>,
year: Option<i64>,
}
#[derive(Debug)] // Add Debug for better error messages
enum AlbumConversionError {
InvalidUuid,
YearLessOrEqualToZero(i64),
}
impl TryFrom<DbAlbum> for Album {
type Error = AlbumConversionError;
fn try_from(db_album: DbAlbum) -> Result<Self, Self::Error> {
let id = Uuid::from_slice(&db_album.id).map_err(|_| AlbumConversionError::InvalidUuid)?;
let artist_id = Uuid::from_slice(&db_album.artist_id).map_err(|_| AlbumConversionError::InvalidUuid)?;
let year = match db_album.year {
Some(year) => {
if year <= 0 {
return Err(AlbumConversionError::YearLessOrEqualToZero(year));
}
Some(year as u32)
}
None => None,
};
Ok(Self::new(id, db_album.name, artist_id, year))
}
}
Explanation of Improvements:
-
Separate Validation and Mapping:
- We handle UUID conversion and year validation separately, making the code more readable and maintainable.
-
match for Year Validation:
- Using
match on db_album.year allows for clear handling of both Some and None cases.
- The validation logic for the year is now explicit and easy to understand.
-
Error Handling:
map_err is used to convert UUID conversion errors into AlbumConversionError::InvalidUuid.
- The
match statement directly returns the appropriate AlbumConversionError for invalid years.
-
Debug for Error Type:
- Adding
#[derive(Debug)] to AlbumConversionError enables better error messages when debugging.
Additional Considerations:
- Custom Error Type: You might want to expand
AlbumConversionError to include more specific error variants if needed.
- Error Propagation: If
Self::new() can also return errors, consider using the ? operator to propagate them up.
This refactored code is more structured, easier to understand, and separates concerns effectively.