Java API 中的枚举
我正在为地址簿创建一个java API 在我的 API 中使用 Enum 是一个好习惯吗?
我使用它的方式如下:
public enum AddressType {
WORK,HOME
}
public class AddressBook implements Function{
Map<String, Details> byName = new TreeMap<String,Details>();
public void addNewContact(String name, String address, AddressType
addressType) {
byName.put(name, new Details(name,new Address(address,addressType)));
// addressType is my enum AddressType
}
请告知是否有更好的方法来做到这一点?
您还可以指导我如何确定应将哪些方法声明为受保护和私有的方法吗? 我希望这个 API 可供公众访问,所以我的理解是我创建的所有方法、类、枚举都应该是公开的。 但这不是忽视了Java的封装性吗?
请帮忙。
谢谢 }
I am creating a java API for an addressbook
Is it a good practice to use Enums in my API ?
I am using it as follows:
public enum AddressType {
WORK,HOME
}
public class AddressBook implements Function{
Map<String, Details> byName = new TreeMap<String,Details>();
public void addNewContact(String name, String address, AddressType
addressType) {
byName.put(name, new Details(name,new Address(address,addressType)));
// addressType is my enum AddressType
}
Please advise if there is a better way to do this?
Also could you guide on how I could determine which methods I should declare as protected and private?
I want this API to be accessible for public so my understanding was that all the methods, classes, enums I create should be public.
But would that not be overlooking encapsulation property of Java??
Please help.
Thank you
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,枚举是一个好主意。对于任何可以表示为少量不变字符串的数据,它是一种非常有用的数据类型。 (如果需要的话,您可以将元数据和行为附加到它们上,这是特别好的)
也就是说,我对您将其用于工作和家庭等联系人类型的想法的一个犹豫是,它使用户无法拥有他们的信息自己的自定义联系人类型。例如,如果我有两份兼职工作,并且想根据人们从事的工作对他们进行分类,该怎么办?
如果你能接受这个限制,我会建议你去尝试。
如果您想要额外的灵活性,我建议将联系人类型存储为字符串或采用数据库解决方案。对于这样的事情,将数据存储在 SQLite 数据库中可能是有意义的,因为这样可以让您轻松构建关系模型。
Enums as a general rule are a good idea. For any data that can be represented as a small number of unchanging strings, it's a very useful datatype to have around. (It's especially nice that you can attach metadata and behaviors to them if desired)
That said, the one hesitation I have about your idea of using it for contact types such as WORK and HOME is that it makes it impossible for the user to have their own custom contact type. For example, what if I have two part time jobs and want to categorize people based on which job they are at?
If you're okay with that limitation, I'd say go for it.
If you want the additional flexibility, I'd suggest either storing the contact type as a string or going for a database solution. For something like this, it may make sense to store your data in a SQLite database as that allows you to easily build a relational model.