聊一聊 Go 中面向包的設計

我是一隻可愛的土撥鼠,專注於分享 Go 職場、招聘和求職,解 Gopher 之憂!歡迎關注我。

歡迎大家加入 Go 招聘交流羣,來這裏找志同道合的小夥伴!跟土撥鼠們一起交流學習。

目錄

前言

文章翻譯自:https://github.com/ardanlabs/gotraining/tree/master/topics/go/design/packaging,屬於由於gotraining系列的design/packaging篇,本人翻譯水平,覺得翻譯不當之處煩請指出。謝謝。

面向包的設計允許開發人員確定一個包在 Go 項目中的位置,並且該包必須遵守設計準則。它定義了什麼是 Go 項目以及 Go 項目是如何構建起來的。最後,它增強了團隊成員之間的溝通交流,促進了整潔的包設計和項目架構。

鏈接

可以參考閱讀下面文章

包設計理念

面向包設計

歷史

在 2000 年 Mihai Budiu 對 Brian Kernighan 的採訪中,Brian 被問到以下問題:

“Can you tell us about the worse features of C, from your point of view”?

“從你的角度來看,你能告訴我們 c 語言最糟糕的特性是什麼嗎?”?

以下是 Brian 的回答:

I think that the real problem with C is that it doesn’t give you enough mechanisms for structuring really big programs, for creating "firewalls" within programs so you can keep the various pieces apart. It’s not that you can’t do all of these things, that you can’t simulate object-oriented programming or other methodology you want in C. You can simulate it, but the compiler, the language itself isn’t giving you any help.”

我認爲 c 語言的真正問題在於它沒有提供足夠的機制來構造真正的大型程序,在程序中創建 “防火牆”,這樣就可以將各個部分分開。並不是說你不能做所有這些事情,也不是說你不能在 c 語言中模擬面向對象程序設計或者其他你想要的方法。你可以模擬它,但是編譯器,語言本身不會給你任何幫助。

語言機制

包的設計哲學

項目結構

Kit                     Application

├── CONTRIBUTORS        ├── cmd/
├── LICENSE             ├── internal/
├── README.md           │   └── platform/
├── cfg/                └── vendor/
├── examples/
├── log/
├── pool/
├── tcp/
├── timezone/
├── udp/
└── web/

驗證

面向包設計的一個重要方面是去驗證包設計的能力。這是可能的,因爲根據包在項目中的位置與包相關聯的準則。有七個驗證步驟可幫助你識別設計問題。

驗證包的位置

驗證依賴項

驗證正在實施的策略

驗證接受 / 返回數據的方式

驗證如何處理錯誤

驗證測試

驗證 recover 和 panic

參考資料

[1] 

Design Philosophy On Packaging: https://www.ardanlabs.com/blog/2017/02/design-philosophy-on-packaging.html

[2] 

Package Oriented Design: https://www.ardanlabs.com/blog/2017/02/package-oriented-design.html

[3] 

Understanding and using the vendor folder: https://blog.gopheracademy.com/advent-2015/vendor-folder/

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/zPHooITRTLNJDcbH2uPsUw