I'm working through the 100 exercises and this is my solution for setters.
The goal was to add value checks that panic whenever you would attempt to change a field on the ticket.
However, there's repeated logic into it (new has the same checks as set_title, set_description, and set_status have).
I would like to extract them to separate functions, and just do the function calls.
pub struct Ticket {
title: String,
description: String,
status: String,
}
impl Ticket {
pub fn new(title: String, description: String, status: String) -> Ticket {
if title.is_empty() {
panic!("Title cannot be empty");
}
if title.len() > 50 {
panic!("Title cannot be longer than 50 characters");
}
if description.is_empty() {
panic!("Description cannot be empty");
}
if description.len() > 500 {
panic!("Description cannot be longer than 500 characters");
}
if status != "To-Do" && status != "In Progress" && status != "Done" {
panic!("Only `To-Do`, `In Progress`, and `Done` statuses are allowed");
}
Ticket {
title,
description,
status,
}
}
pub fn title(&self) -> &String {
&self.title
}
pub fn description(&self) -> &String {
&self.description
}
pub fn status(&self) -> &String {
&self.status
}
pub fn set_title(&mut self, new_title: String) {
if new_title.is_empty() {
panic!("Title cannot be empty");
}
if new_title.len() > 50 {
panic!("Title cannot be longer than 50 characters");
}
self.title = new_title;
}
pub fn set_description(&mut self, new_description: String) {
if new_description.is_empty() {
panic!("Description cannot be empty");
}
if new_description.len() > 500 {
panic!("Description cannot be longer than 500 characters");
}
self.description = new_description;
}
pub fn set_status(&mut self, new_status: String) {
if new_status != "To-Do" && new_status != "In Progress" && new_status != "Done" {
panic!("Only `To-Do`, `In Progress`, and `Done` statuses are allowed");
}
self.status = new_status;
}
}
The way I approached this was, thinking that I should call a function like validate_status(new_status) etc., which basically takes just the reference and panics if it's invalid, without returning anything if it doesn't panic (note: panicking on invalid values is a requirement for the exercise).
However, I'm having issues with where to put the validation functions. Placing it within the impl Ticket kinda makes sense, but I don't want to use my_ticket.validate_title(title). At the same time, it doesn't make sense not to put it in the impl Ticket because that way everyone and their dog would be able to call it.
Sorry if it sounds really dumb but what's the appropriate approach?