So, I decided to keep it pretty light-weight tonight. Just wanted to vent a little on coding practices:
If you name your return types, what's the point in returning with those names?
- BAD
func GetAllTodos() (todos Todos, err eror){
db, err := sql.Open("mysql", database.ConnectionString())
if err != nil{
return todos, err //WHY?!!?!??!?!!?
}
defer db.Close()
///more goodies...
}
- GOOD
func GetAllTodos() (todos Todos, err eror){
db, err := sql.Open("mysql", database.ConnectionString())
if err != nil{
return
}
defer db.Close()
///more goodies...
}
If you plan on returning one thing...return the type and don't name it!
- BAD
//REALLY? WHY are we naming it then?
func (t *Todo) Get() (err error){
db, err := sql.Open("mysql", database.ConnectionString())
if err != nil{
return err
}
//more goodies...
}
- GOOD
func (t *Todo) Get() error{
db, err := sql.Open("mysql", database.ConnectionString())
if err != nil{
return err
}
//more goodies...
}
Straight from Programming Fundamentals: Name your variables appropriately!
- BAD
func ReallyComplicatedFunction() (returnTypes ReturnTypes, err error){
//imagine this function being really complicated...
//lots of loops...
//channels, go routines, and pieces being put together...
//then...
//you...
//see...
shazaam := false
for rows.Next(){
shazaam = true
//process some rows
}
if shazaam == false{
//more stuff to do...
}
//more goodies...
}
First of all, WTF is shazaam and what does it do? At first glance, I have no clue.
- GOOD
func ReallyComplicatedFunction() (returnTypes ReturnTypes, err error){
//imagine this function being really complicated...
//lots of loops...
//channels, go routines, and pieces being put together...
//then...
//you...
//see...
queryHasRows := false
for rows.Next(){
queryHasRows = true
//process some rows
}
if !queryHasRows{
//more stuff to do...
}
//more goodies...
}
I should be able to look at any variable and have some idea of what it is doing or what it is about to do! I can clearly see now that I am going to be checking to make sure that I have rows. Easy peasy.
It's not your fault...