-
-
Save silverark/2fd88d03fddbe373fce87da80afdc3ce to your computer and use it in GitHub Desktop.
Bad Code Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is an example of some badly written code. What would you refactor? | |
type User struct { | |
Uuid string | |
FirstName string `db:"first_name"` | |
LastName string `db:"last_name"` | |
Email string | |
Password string | |
Address *Address | |
} | |
type Address struct { | |
Uuid string | |
UserUuid uint `db:"user_uuid"` | |
Address1 string | |
Address2 string | |
City string | |
Postcode string | |
} | |
func OrderBYAndGetAll(orderBy string) ([]User, error) { | |
db, _ := sqlx.Connect("postgres", "user=prod password=prodPass741 dbname=acme sslmode=disable") | |
getUsersQuery := "SELECT * FROM users" | |
// Add the order by if it has been passed though | |
if orderBy != "" { | |
getUsersQuery += " ORDER BY " + orderBy + " ASC" | |
} | |
users := []User{} | |
db.Select(&users, getUsersQuery) | |
// Find the address for each user | |
for _, user := range users { | |
db.Select(&user.Address, "select * from addresses where user_uuid = "+user.Uuid) | |
} | |
return users, nil | |
} | |
func GetAllUsers() ([]User, error) { | |
// db, _ := sqlx.Connect("postgres", "user=dev password=password dbname=acme sslmode=disable") | |
// getUsersQuery := "SELECT * FROM users" | |
// users := []User{} | |
// db.Select(&users, getUsersQuery) | |
db, _ := sqlx.Connect("postgres", "user=prod password=prodPass741 dbname=acme sslmode=disable") | |
getUsersQuery := "SELECT * FROM users" | |
users := []User{} | |
db.Select(&users, getUsersQuery) | |
// Find the address for each user | |
for _, user := range users { | |
err := db.Select(&user.Address, "select * from addresses where user_uuid = "+user.Uuid) | |
} | |
return users, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment