OOP:有多少程序逻辑应该作为方法封装在相关对象/类中?

发布于 2024-08-27 08:26:58 字数 368 浏览 6 评论 0原文

我有一个简单的程序,可以有管理员用户或普通用户。 该程序还有两个类:UserAccount 和AdminAccount。 管理员需要做的事情(用例)包括 Add_Account、Remove_Account 等。

我的问题是,我应该尝试将这些用例封装到对象中吗?

只有使用 AdminAccount 登录的管理员才能添加和删除其他帐户。我可以有一个无类子过程,将新的 UserAccount 对象添加到系统中,并在管理员按下“添加帐户”按钮时调用。或者,我可以将该过程作为 AdminAccount 对象中的方法放置,并让按钮事件执行一些代码,例如“Admin.AddUser(name,password)”。

我更倾向于第一种选择,但我不确定这个面向对象的业务应该走多远。

I have a simple program which can have an admin user or just a normal user.
The program also has two classes: for UserAccount and AdminAccount.
The things an admin will need to do (use cases) include Add_Account, Remove_Account, and so on.

My question is, should I try to encapsulate these use-cases into the objects?

Only someone who is an Admin, logged in with an AdminAccount, should be able to add and remove other accounts. I could have a class-less Sub-procedure that adds new UserAccount objects to the system and is called when an admin presses the 'Add Account' button. Alternatively, I could place that procedure as a method inside the AdminAccount object, and have the button event execute some code like 'Admin.AddUser(name, password).'

I'm more inclined to go with the first option, but I'm not sure how far this OO business is supposed to go.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新一帅帅 2024-09-03 08:26:58

对象中应该有多少逻辑?

所有这一切。

面向对象 101 会说你应该有一个 Account 类。用户和管理员是可能授予彼此不同权力的角色,但从系统中添加和删除帐户的行为不应改变。

您的对象所表达的用途也应该超越用户看到的界面。您的用例应该可以针对文本或图形用户界面执行。这是一个很好的测试,可以看看您将用户界面与逻辑分离的程度如何,以便首先看看您是否可以在没有 GUI 的情况下解决问题。

如果您首先考虑 GUI,那么您就错了。

How much logic should be in objects?

All of it.

Object-oriented 101 would say that you should have an Account class. User and Admin are roles that might bestow different powers on one over the other, but the behavior of adding and removing accounts from the system shouldn't change.

It should also be true that your objects express use that's over and above the interface a user gets to see. Your use cases should be executable for either text or graphical user interfaces. It's a good test to see how well you've separated the user interface from the logic to first see if you can drive the problem without a GUI.

If you're thinking GUI first you're doing it wrong.

岁月如刀 2024-09-03 08:26:58

创建帐户当然是一项业务活动,因此它应该是您的业务类之一(例如帐户)的一部分,而不是在按钮的方法中包含逻辑。

The creation of accounts is certainly a business activity, so it should be part of one of your business classes (e.g. Account) rather than having the logic in the button's method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文