Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Three areas of code that I think can be optimized #304

Open
guowei-gong opened this issue Oct 14, 2023 · 1 comment
Open

Three areas of code that I think can be optimized #304

guowei-gong opened this issue Oct 14, 2023 · 1 comment
Labels
enhancement New feature or request question Further information is requested

Comments

@guowei-gong
Copy link

guowei-gong commented Oct 14, 2023

我不确定这些点修改后,可以让 qmgo 变的更好,如果可以,我很乐意修改并 pr。

  1. Qmogo 中的 util.go 中的 SplitSortField 函数中,if len() 影响了代码缩进。代码应通过尽可能先处理错误情况/特殊情况并尽早返回或继续循环来减少嵌套。减少嵌套多个级别的代码的代码量。

修改前:
image

修改后:

func SplitSortField(field string) (key string, sort int32) {
	key = field
	sort = 1

	if len(field) == 0 {
		return key, sort
	}

	switch field[0] {
	case '+':
		key = strings.TrimPrefix(field, "+")
		sort = 1
	case '-':
		key = strings.TrimPrefix(field, "-")
		sort = -1
	}
	return
}
  1. Qmogo 中的 cursor.go 中的 Next 函数中,err 判断可以简化。尽量缩小变量作用范围。

修改前:
image

修改后:

func (c *Cursor) Next(result interface{}) bool {
	if c.err != nil {
		return false
	}
	if c.cursor.Next(c.ctx) {
		if err := c.cursor.Decode(result); err != nil {
			c.err = err
			return false
		}
		return true
	}
	return false
}
  1. Qmogo 中的 session.go 中的 StartTransaction 函数中,返回值做了多余的判断。不必要的 if else 判断。

修改前:
image

修改后:

func (s *Session) StartTransaction(ctx context.Context, cb func(sessCtx context.Context) (interface{}, error), opts ...*opts.TransactionOptions) (interface{}, error) {
	transactionOpts := options.Transaction()
	if len(opts) > 0 && opts[0].TransactionOptions != nil {
		transactionOpts = opts[0].TransactionOptions
	}
	return s.session.WithTransaction(ctx, wrapperCustomCb(cb), transactionOpts)
}

期待您的回复 :-)

@jiangz222
Copy link
Collaborator

  • 1和2没有什么问题
  • 3,其实改变了StartTransaction的行为,可以斟酌下
    其实可以直接提pr,在pr里讨论即可

@jiangz222 jiangz222 added enhancement New feature or request question Further information is requested labels Feb 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants