- 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.
- Visual Basic程序設(shè)計(jì)(第3版):學(xué)習(xí)指導(dǎo)與練習(xí)
- 數(shù)據(jù)庫(kù)系統(tǒng)原理及MySQL應(yīng)用教程
- Cassandra Design Patterns(Second Edition)
- 精通Python自然語(yǔ)言處理
- Learning Network Forensics
- Java EE 7 Performance Tuning and Optimization
- AppInventor實(shí)踐教程:Android智能應(yīng)用開(kāi)發(fā)前傳
- Java面向?qū)ο蟪绦蛟O(shè)計(jì)
- MySQL入門(mén)很輕松(微課超值版)
- Java零基礎(chǔ)實(shí)戰(zhàn)
- 移動(dòng)增值應(yīng)用開(kāi)發(fā)技術(shù)導(dǎo)論
- Apache Camel Developer's Cookbook
- Python Interviews
- Hadoop大數(shù)據(jù)分析技術(shù)
- 30天學(xué)通C#項(xiàng)目案例開(kāi)發(fā)