Skip to content

Commit

Permalink
Merge pull request #55 from richzw/master
Browse files Browse the repository at this point in the history
Add tips 067
  • Loading branch information
smallnest authored Apr 21, 2024
2 parents 41d9a4b + e85263c commit 88944c0
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ Go tips from [Phuong Le](https://twitter.com/func25).
| 64 | | |
| 65 | Returning Pointers Made Easy with Generics | miniLCT |
| 66 | | |
| 67 | | |
| 67 | How to deal with long function signatures | richzw |
| 68 | Use the deadcode tool to find and remove unused functions | richzw |
| 69 | Manage multiple goroutines with errgroup | richzw |
| 70 | | |
Expand Down
30 changes: 30 additions & 0 deletions src/067.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Tip #67 如何处理长函数签名

> 原始链接:[ Golang Tip #67: How to deal with long function signatures](https://twitter.com/func25/status/1775910818116411508)
>
当你在 Go 中处理具有许多参数、长名称、接收器、多个返回结果的函数签名时,可能会遇到类似这样的情况:

![](./images/067/001.png)

```go
func SendEmail(subj string, receip string, body string, attachmentPaths []string, cc []string, bcc []string, replyTo string) error
```

在不破坏代码流程(从上到下)的情况下,有几种解决方法:

1. 长参数可能表明函数的功能超出了应有的范围,考虑将其拆分为较小的函数。
2. 如果任何参数是可选的,请考虑使用可选的结构体或变长函数。这一技术在我之前分享的tips中介绍过([Tips#22](https://twitter.com/func25/status/1758435261183353308))。
3. 如果参数是必需的,仍然可以将它们分组到一个结构体中并进行验证,必要时抛出错误。
4. 使用仍然清晰且描述准确的较短名称。
5. 具有相同类型的参数可以在类型前声明一次。

> “但我仍然想保留 4 或 5 个参数;我不想每次都创建一个新的结构体。”

**语义换行**

更清晰的解决方案是根据它们的语义关系将一组参数放在自己的一行上:

![](./images/067/002.png)

尽管由于多行而稍显冗长,但它使我们需要阅读的所有内容都在视线范围内。
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- [Tip #47 表驱动测试,测试集和并行运行测试](./047.md)
- [Tip #71 用泛型让 sync.Pool 类型安全](./071.md)
- [Tip #65 使用泛型返回指针](./065.md)
- [Tip #67 如何处理长函数签名](./067.md)
- [Tip #68 使用deadcode工具来找到和删除无用的函数](./068.md)
- [Tip #69 通过errgrup管理多个goroutine](./069.md)
- [Tip #73 用stringer工具给枚举类型实现String()方法](./073.md)
Expand Down
Binary file added src/images/067/001.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/067/002.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 88944c0

Please sign in to comment.