Today was a step forward in my Go journey. Instead of writing everything inside main(), I refactored my Conference Booking App by separating logic into functions, validating user input properly, and organizing my code structure.
Here's what I learned:
Encapsulating Logic with Functions
I broke my program into smaller, focused functions:
-
greetUser()- Displays conference details -
getUserInput()- Collects user input -
validateUserInput()- Validates the input -
bookTicket()- Handles ticket booking logic -
getFNames()- Extracts first names from bookings
Example:
func bookTicket(userTickets uint, fName string, lName string, email string) {
remainingTickets = remainingTickets - userTickets
bookings = append(bookings, fName+" "+lName)
}
What I Realized:
- Functions make
main()cleaner - Code becomes reusable
- Logic is easier to test and understand
- Each function has a single responsibility
Validating User Input
I created a validation function that returns multiple boolean values:
func validateUserInput(fName string, lName string, email string, userTickets uint) (bool, bool, bool)
Inside it:
isValidName := len(fName) >= 2 && len(lName) >= 2
isValidEmail := strings.Contains(email, "@")
isValidTicketNumber := userTickets > 0 && userTickets <= remainingTickets
What I Learned:
- Functions can return multiple values in Go
- Boolean expressions control decision-making
- Validation prevents bad input
Using Global Variables Carefully
I defined shared data outside main():
var conferenceName = "Go Conference"
const conferenceTickets = 50
var remainingTickets uint = 50
var bookings = []string{}
This allowed multiple functions to access shared state.
Clean Main Function
Now my main() function is much cleaner:
fName, lName, email, userTickets := getUserInput()
isValidName, isValidEmail, isValidTicketNumber := validateUserInput(...)
Instead of being crowded with logic, main() now:
- Gets input
- Validates input
- Books tickets if valid
- Displays first names
- Stops when tickets are sold out
This separation made the flow much easier to read.
Extracting First Names
I also created:
func getFNames() []string
Which:
- Loops through the
bookingsslice - Uses
strings.Fields()to split names - Returns only first names
In summary, I learned how to encapsulate logic into separate functions to make my Go program cleaner and more organized. I created dedicated functions for greeting users, collecting input, validating data, booking tickets, and extracting first names. I also learned how to return multiple boolean values from a function to validate user input properly. Structuring my code this way made main() easier to read and improved the overall flow of the program. This lesson helped me understand the importance of modular and maintainable code in real-world development.
Top comments (0)