Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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")
}
share|improve this question
    
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". –  Dave C May 10 at 14:00
    
Maybe you are right. –  user3147268 May 10 at 14:05

1 Answer 1

up vote 1 down vote accepted

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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