官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 田阳县| 项城市| 黄浦区| 三亚市| 儋州市| 望谟县| 滨州市| 连江县| 巴彦淖尔市| 丰台区| 铅山县| 桃园市| 唐海县| 庆云县| 泾源县| 遂昌县| 连城县| 招远市| 涟源市| 安化县| 丹东市| 林西县| 万荣县| 布尔津县| 莫力| 鄯善县| 广州市| 石河子市| 阜新| 万宁市| 秦皇岛市| 陇川县| 上饶县| 中卫市| 秦皇岛市| 清水河县| 花垣县| 合阳县| 博客| 永靖县| 西青区|