- Hands-On Dependency Injection in Go
- Corey Scott
- 306字
- 2021-06-10 19:17:50
Export only what you must
When you are careful and stingy about your exported API, many good things happen. Chiefly, it becomes easier for others to understand; when a method has fewer parameters, it is naturally easier to understand. Look at the following code:
NewPet("Fido", true)
What does true mean? It's hard to tell without opening the function or the documentation. However, what if we do the following:
NewDog("Fido")
In this case, the purpose is clear, mistakes are unlikely and, as a bonus, encapsulation is improved.
Similarly, interfaces and structs with fewer methods and packages with objects are all easier to understand, and are more likely to have a more definite purpose. Let's look at another example:
type WideFormatter interface {
ToCSV(pets []Pet) ([]byte, error)
ToGOB(pets []Pet) ([]byte, error)
ToJSON(pets []Pet) ([]byte, error)
}
Compare the preceding code to the following:
type ThinFormatter interface {
Format(pets []Pet) ([]byte, error)
}
type CSVFormatter struct {}
func (f CSVFormatter) Format(pets []Pet) ([]byte, error) {
// convert slice of pets to CSV
}
Yes, in both of these cases, the result was more code. More straightforward code, but more code nonetheless. Providing a better UX for users will frequently incur a little bit more cost, but the productivity gains for the users are multiplicative. Considering the fact that, in many cases, one of the users of the code that you write is future you, you could say that a bit of extra work now saves you lots of work in the future.
Continuing along the line of looking out for future me, the second advantage this approach offers is it makes it easier to change your mind. Once a function or type is exported, it can be used; once used, it has to be maintained and takes much more effort to change. This approach makes such changes easier.
- Fundamentals of Linux
- CentOS 7 Server Deployment Cookbook
- Reactive Programming With Java 9
- Instant RubyMotion App Development
- Apex Design Patterns
- Android開發:從0到1 (清華開發者書庫)
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- PHP編程基礎與實例教程
- LabVIEW虛擬儀器入門與測控應用100例
- Laravel Application Development Blueprints
- Java并發編程:核心方法與框架
- 人人都能開發RPA機器人:UiPath從入門到實戰
- 程序員的成長課
- Ionic3與CodePush初探:支持跨平臺與熱更新的App開發技術
- 用Go語言自制編譯器