简体   繁体   English

具体的get方法还是一般的get方法?

[英]specific get methods or general get method?

In some programming API's I see a list of methods to call, like getBoolean(String key, getDouble(String key), and getString(String key). Some other API's use a general get(String key) method, and return an Object which you are supposed to cast to an appropriate type yourself. 在一些编程API中,我看到了一个要调用的方法列表,比如getBoolean(String key,getDouble(String key)和getString(String key)。其他一些API使用一般的get(String key)方法,并返回一个Object你应该自己投射到合适的类型。

Now I am writing my own data accessing point, and I am wondering which approach to use. 现在我正在编写自己的数据访问点,我想知道使用哪种方法。 What are the advantages and disadvantages of each approach? 每种方法的优点和缺点是什么? When would you choose one over the other? 你何时会选择一个而不是另一个?

Advantage: getBoolean(), getDouble(), etc. allow you to return the respective primitive types. 优点:getBoolean(),getDouble()等允许您返回相应的基元类型。 As far as I've seen, that's the primary reason anyone writes methods like that. 据我所见,这是任何人写这样的方法的主要原因。

Provide getters for the types that are most likely to be used. 为最有可能使用的类型提供getter。 There's no real right or wrong way. 没有正确或错误的方式。

It depends on the purpose of the library. 这取决于图书馆的目的。 When the output is a predictable set of items, then toy can have specific names. 当输出是可预测的一组项目时,玩具可以具有特定的名称。 As in ResultSet . ResultSet中一样 If it is generic, then you will need generic get methods. 如果它是通用的,那么您将需要通用的get方法。 Like ObjectOutputStream ObjectOutputStream一样

In a very high level sense, you might need both: getBoolean , getDouble , getIngeter for the primitives (or their respective wrappers), a getString , for Strings and a generic get or a getObject for getting out objects. 在非常高级的意义上,您可能需要:两个原语(或其各自的包装器)的getBooleangetDoublegetIngeter ,用于StringsgetString和用于获取对象的泛型getgetObject

However, this is a very generic answer for a very generic questions. 但是,对于非常通用的问题,这是一个非常通用的答案。 What your tries to do very much decided such stuff. 你尝试做什么非常决定这样的东西。

Two questions: 1) Why don't you use general Properties instead, à là: 两个问题:1)为什么不使用常规属性,àlà:

String getName()
Address getAddress()
Date getDateOfBirth()

etc? 等等?

2) If you want to use methods like: 2)如果你想使用如下方法:

String getString(String key)
Double getDouble(String key)
Address getAddress(String key)

How on earth would I, as the user, know, which key's are associated with objects of type String, which are associated with objects of type Double, etc? 作为用户,我怎么知道哪些键与String类型的对象相关联,哪些类型与Double类型的对象相关联?

I would recommend going with a solution similar to 1). 我建议使用类似于1)的解决方案。 If I didn't misunderstand your question, that is. 如果我没有误解你的问题,那就是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM