2
\$\begingroup\$

My current project uses a database represented as object. Furthermore I want to implement methods like CreateUser(), DeleteUser() etc, but my current code requires the injection of the db-object as parameter in each function.

Making the db-object global would solve the problem, but I learnt that global variables are mostly seen as a bad practice. Are there any other solutions?

package main

import (
    "fmt"
    "time"

    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
)

type User struct {
    ID        int
    Name      string `sql:"size:50"`
    Username  string `sql:"size:50"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

func CreateUser(db gorm.DB, name, username string) {
    user := User{
        Name:     name,
        Username: username,
    }

    db.Create(&user)
}

func main() {
    db, err := gorm.Open("sqlite3", "data.sqlite3")

    if err != nil {
        fmt.Println(err)
    }

    db.DB()
    fmt.Println("Programm is running...")

    CreateUser(db, "John Doe", "johndoe")
}
\$\endgroup\$
2
  • \$\begingroup\$ Isn't this more appropriate for Stack Overflow? Seems like it doesn't fit according to the help center; i.e. it sounds more like a "generally applicable question about … [b]est practices in general". \$\endgroup\$
    – Dave C
    Commented May 10, 2015 at 14:00
  • \$\begingroup\$ Maybe you are right. \$\endgroup\$ Commented May 10, 2015 at 14:05

1 Answer 1

2
\$\begingroup\$

Usually, when you have a lot of functions operating on the same data, it's worth considering making those functions methods on this data:

type UserDB struct {
    *gorm.DB
}

func (udb *UserDB) Create(name, username string) error {
    user := User{
        Name:     name,
        Username: username,
    }

    return udb.Create(&user).Error
}

// etc.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.