何时使用枚举、类或标签? [英] When to use enum, class or tags?

查看:32
本文介绍了何时使用枚举、类或标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个特定页面类型的页面(例如普通页面、帐户页面等).该页面由一个 Page 对象表示.

Imagine you have a page that is of a specific page type (for example normal page, account page etc). The page is represented by a Page object.

我的问题是,您将如何为页面分配页面类型?

My question is, how would you assign a page type to a page?

我看到这些选项:

  1. 使用在 Page 对象中设置的 PageType 枚举.
  2. 通过使用 PageType 类,并在 Page 对象中分配它的实例.
  3. 使用页面标签,这些标签是与 Page 对象关联的简单字符串.

选项 1 是纯代码方法,因此添加新页面类型意味着更改(核心)代码.选项 2 更灵活,但必须维护这些页面类型会产生额外的开销.选项 3 非常灵活,因为无需维护,并且可以扩展到页面类型以外的其他机制.但是你可以很容易地破坏东西,因为没有限制.

Option 1 is code-only approach, so adding new page types means changing (core) code. Option 2 is more flexible, but there is additional overhead in having to maintain these page types. Option 3 is very flexible, because there's no maintenance and it's extendable to other mechanisms than page type. But you can easily break things because there are no constraints.

选择一个而不是另一个的其他客观原因是什么?

What would be other objective reasons to choose one over the other?

推荐答案

缺乏关于系统设计和页面要求、支持的不同页面类型的数量以及页面本身之间的差异的细节,因此很难做出这样的决定.在这种情况下,我建议保持简单并使用枚举.

There is a lack of details regarding a system design and pages requirements, number of different page types to support and difference between pages itself, so hard to make such decision. In such case I would recommend to keep it simple and use Enum.

  • 如果页面有自己特定的业务逻辑,你可以坚持使用每个页面类型的类,但只有在真正有页面特定的逻辑时才小心谨慎.
  • 考虑 UserControl/CustomControl 功能(假设您使用 ASP.NET),这样您就可以通过一组负责页面功能的控件拆分页面,这样您将保持单一职责原则并构建耦合度较低的系统.
  • 一些逻辑应该从 Page 实体本身提取到外部助手/工厂/存储库中,然后注入到 Page 类中.
  • If pages has own specific business logic you can stick with class per Page type, but do it carefully only when really page-specific logic there.
  • Think about UserControl/CustomControl feature (assuming you are usign ASP.NET) so you can split page by a set of controls which is responsible on the part of Page functionality, so in this way you'll keep Single Responsibility Principle and build less coupled system.
  • Some logic should be extracted from Page entities itself into external helpers/factories/repositories and then injected in Page class.

关于目标,您应该定义潜在的页面数量以及应该提供的灵活性级别.还要记住诸如系统的可扩展性和维护之类的事情.

Regarding objectives, you should define how many pages could be in place potentially and which level of flexibility should be provided. Also keep in mind such things like extensibility and maintenance of a system.

这篇关于何时使用枚举、类或标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆