1

根据 Martin Fowler 的说法,“有些东西可以公开,但这并不意味着你已经发布了它。” 这是否意味着这样的事情:

public interface IRollsRoyceEngine
{
    void Start();
    void Stop();
    String GenerateEngineReport();
}

public class RollsRoyceEngine : IRollsRoyceEngine
{
    public bool EngineHasStarted { get; internal set; }

    public bool EngineIsServiceable { get; internal set; }

    #region Implementation of IRollsRoyceEngine

    public void Start()
    {
        if (EngineCanBeStarted())
            EngineHasStarted = true;
        else
            throw new InvalidOperationException("Engine can not be started at this time!");
    }

    public void Stop()
    {
        if (EngineCanBeStopped())
            EngineHasStarted = false;
        else
            throw new InvalidOperationException("Engine can not be started at this time!");
    }

    public string GenerateEngineReport()
    {
        CheckEngineStatus();
        return EngineIsServiceable ? "Engine is fine for now" : "Hmm...there may be some problem with the engine";
    }

    #endregion

    #region Non published methods

    public bool EngineCanBeStarted()
    {
        return EngineIsServiceable ? true : false;
    }

    public bool EngineCanBeStopped()
    {
        return EngineIsServiceable ? true : false;
    }

    public void CheckEngineStatus()
    {
        EngineIsServiceable = true;
        //_EngineStatus = false;
    }

    #endregion

}

可以说这个发布的接口是IRollsRoyceEngine而不是RollsRoyceEngine中的任何东西吗?

如果是这样,公共方法和已发布方法之间的真正区别是什么?

4

2 回答 2

5

我认为他的意思是合同为王——仅仅因为你的类中的一个方法是公共的,并不能使客户假设他们可以调用它,或者他们知道它的作用,或者它会在下一个版本。API 不是由源定义的,它们是由合同定义的,通常以文档的形式。

客户有责任不调用未记录(未发布)的函数,而不是实现者有责任隐藏不应调用的方法。

有些人可能不同意这一点——通常是那些不信任文档的人,他们宁愿通过查看源代码来了解它的实际作用,而不是作者声称的作用。他们可能很有道理,尤其是在处理文档不足的代码时。但我认为这与 Fowler 所说的相反,即功能应该被正式定义,而不是通过检查特定实现来推断。

于 2008-12-14T04:02:03.477 回答
2

In my opinion mentioned white paper talks about target audience of the API rather than the distinction between interface and its implementation.

You can find analogy in Framework Design Guidelines which says that once your API shipped you have a contract with consumers. For example, if you shipped in v1 of your framework IService interface you cannot change it in v2 because it will introduce breaking changes to end developers. Instead you must create new interface IService2 inhereted from IService and ship it with v2.

So basically public API becomes published once you "sign a contract" with end developers.

Returning back to your code - it will be published when you ship it to development community for example.

Hope this explanation will help.

于 2008-12-14T16:39:20.920 回答