最佳实践,1 种方法和 2 种方法具有相同的功能
我有以下场景。 有些人使用方法 1,有些人使用方法 2。 两种方法具有相同的功能,根据新闻表中的新闻 ID 锁定或解锁新闻。 你有什么建议,哪一个更好,为什么?
注意:为了简单起见,我使用 void 返回类型而不是 bool,因此请忽略这一点
方法 1:
public void LockNews(long newId)
{
......
}
public void UnlockNews(long newId)
{
...
}
方法 2:
public void LockUnlockNews(long newId,bool Islock)
{
......
}
I have following scenario.
Some people use approach 1 and some use approach 2.
Both approaches have same functionality lock or unlock news against news id in news table.
what you suggest,which one is better and why?
Note:I use void return type instead of bool for simplicity so please ignore this
Approach 1:
public void LockNews(long newId)
{
......
}
public void UnlockNews(long newId)
{
...
}
Approach 2:
public void LockUnlockNews(long newId,bool Islock)
{
......
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
方法 1,对我来说,因为恕我直言,方法应该代表单个操作。为了编写可测试的代码或任何形式的自动化测试,它将保持清晰的分离并且更有意义。
方法 2 倾向于“执行所有操作”,恕我直言,应该避免这种操作。
Approach 1, for me, because IMHO a method should represent a single operation. In the interest of writing testable code or any form of automated testing, it would maintain a clear separation and make a lot more sense.
Approach 2 is leaning towards a "does everything" operation, which IMHO should be avoided.
我更喜欢方法 1。它可以清楚地说明发生了什么。如果您使用方法 2 并调用
并不能立即明确这是锁定还是解锁。
只是火上浇油:如果你将 bool 更改为 enum 或 const,那么我的论点就无效了。
就像
I prefer Approach 1. It makes it clear what is going on. If you use approach 2 and call
It is not immediately clear whether this is a lock or an unlock.
Just to throw some fuel on the fire: If you changed the bool to an enum or a const, then my argument is null and void.
is just as clear as
第一种方法。
您的方法是一个命令,并且应该尽可能明确。我什至会问你为什么除了新闻本身之外还有人知道如何锁定/解锁?对我来说新闻应该对此负责:
更有意义,不是吗? :) 你可以清楚地看到你的对象是什么以及它们有什么行为。这就是 OOP 中所谓的封装。
First approach.
Your method is a Command and should be as explicit as possible. I would even ask you why someone but News itself know how to lock/unlock? For me News should be responsible for it:
Makes more sense, doesn't it? :) You clearly see what your objects are and what behaviors they have. This is what is called encapsulation in OOP.
我通常将这两种方法结合起来,如下所示:
公共方法提供清晰的界面并且更易于测试:
私有方法执行实际业务并提高模块化从一个位置管理事物:
I combine both approaches generally like below:
Public methods provide clear interface and are more testable:
Private method does actual business and increases modularity managing things from one location: