- Hands-On Dependency Injection in Go
- Corey Scott
- 391字
- 2021-06-10 19:17:45
A quick word about idiomatic Go
Personally, I try to avoid using the term idiomatic Go but a Go book is arguably not complete without addressing it in some form. I avoid it because I have seen it too often used as a stick to beat people. Essentially, this is not idiomatic, therefore it's wrong and, by extension, I am idiomatic and therefore better than you. I believe that programming is a craft and, while a craft should have some form of consistency in its application, it should, as with all crafts, be flexible. After all, innovation is often found by bending or breaking the rules.
So what does idiomatic Go mean to me?
I'll define it as loosely as I can:
- Format your code with gofmt: Truly one less thing for us programmers to argue about. It's the official style, supported with official tools. Let's find something more substantive to argue about.
- Read, apply, and regularly revisit the ideas in Effective Go (https://golang.org/doc/effective_go.html) and Code Review Comments (https://github.com/golang/go/wiki/CodeReviewComments): There is a huge amount of wisdom in these pages, so much so that it's perhaps impossible to glean it all from just one reading.
- Aggressively apply the Unix philosophy: It state that we should design code that does a single thing, but to does it well and works well together well with other code.
While these three things are the minimum for me, there are a couple of other ideas that resonate:
- Accepting interfaces and returning structs: While accepting interfaces leads to nicely decoupled code, the returning structs might strike you as a contradiction. I know they did with me at first. While outputting an interface might feel like it's more loosely coupled, it's not. Output can only be one thing—whatever you code it to be. Returning an interface is fine if that's what you need, but forcing yourself to do so just ends up with you writing more code.
- Reasonable defaults: Since switching to Go, I've found many cases where I want to offer my user the ability to configure the module but such configuration is frequently not used. In other languages, this could lead to multiple constructors or seldom used parameters, but by applying this pattern we end up with a much cleaner API and less code to maintain.
推薦閱讀
- Visual C++程序設(shè)計(jì)教程
- Git Version Control Cookbook
- Rust實(shí)戰(zhàn)
- 算法訓(xùn)練營(yíng):入門篇(全彩版)
- Android 7編程入門經(jīng)典:使用Android Studio 2(第4版)
- Python 3破冰人工智能:從入門到實(shí)戰(zhàn)
- Microsoft System Center Orchestrator 2012 R2 Essentials
- Hands-On Enterprise Automation with Python.
- Java Web程序設(shè)計(jì)任務(wù)教程
- C語言程序設(shè)計(jì)
- SQL Server數(shù)據(jù)庫(kù)管理與開發(fā)兵書
- Python入門很輕松(微課超值版)
- HTML5游戲開發(fā)實(shí)戰(zhàn)
- 少年小魚的魔法之旅:神奇的Python
- Kali Linux Wireless Penetration Testing Essentials