java– 使接口编程而不是语义是什么意思?

java– 使接口编程而不是语义是什么意思?,第1张

概述目前我正在阅读“CodeComplete,2ndEdition”一书.在第6.2章中,作者讨论了类和接口,并给出了以下建议:MakeinterfacesprogrammaticratherthansemanticwhenpossibleEachinterfaceconsistsofaprogrammaticpartandasemanticpart.Theprogrammaticpartcon

目前我正在阅读“Code Complete,2nd Edition”一书.在第6.2章中,作者讨论了类和接口,并给出了以下建议:

Make interfaces programmatic rather than semantic when possible
Each interface consists of a programmatic part and a semantic part.
The programmatic part consists of the data types and other attributes
of the interface that can be enforced by the compiler. The semantic
part of the interface consists of the assumptions about how the
interface will be used, which cannot be enforced by the compiler. The
semantic interface includes consIDerations such as “RoutineA must be
called before RoutineB” or “RoutineA will crash if dataMember1 isn’t
initialized before it’s passed to RoutineA.” The semantic interface
should be documented in comments, but try to keep interfaces minimally
dependent on documentation. Any aspect of an interface that can’t be
enforced by the compiler is an aspect that’s likely to be misused.
Look for ways to convert semantic interface elements to programmatic
interface elements by using Asserts or other techniques.

我理解作者通过语义和程序化的意思,但我不明白的是你如何将语义接口函数转换为程序化函数.他提到使用断言或其他技术来实现这一目标.

让我们以作者为例:

必须在RoutineB之前调用RoutineA.我假设这些例程是接口(公共函数)的一部分,因为这就是这个丑陋的接口.

因此,如果在调用RoutineB之前确实必须调用RoutineA,那么如何使用断言或其他技术重新组织此接口?

我对此有一些想法,但我不确定它们是否正确.

假设RoutineA和RoutineB都是公共函数,这意味着它们都应该彼此独立可用,但唯一的限制是你首先必须调用RoutineA才能独立调用RoutineB.

如果确实如此,那么如何使用断言或其他技术解决这个问题呢?

如果我的假设有错误,请随时纠正我.

另外,我故意在当前标签下发布这个标签,因为像面向对象编程/设计/界面这样的标签只有非常少的命中,这意味着我的问题可能不会被看到很多.

解决方法:

两个可能的答案:

>放置断言(a_called);在例行程序中
>从类的接口中删除RoutineB,并使RoutineA返回一个具有RoutineB成员的新对象.

在后一种情况下,您可能希望使外部类成为指向内部类的智能指针的瘦包装器,然后RoutineA只会复制指针.

class Impl;class SecondClass;class FirstClass{    std::shared_ptr<Impl> pimpl;public:    FirstClass();    SecondClass RoutineA(...);    ...}class SecondClass{    std::shared_ptr<Impl> pimpl;    frIEnd class FirstClass;    SecondClass(const std::shared_ptr<Impl>& impl) : pimpl(impl);public:    voID RoutineB(....);}SecondClass FirstClass::RoutineA(...){    // Do stuff    return SecondClass(pimpl);}

您也可以使用unique_ptr执行此 *** 作,但该代码有点长.

总结

以上是内存溢出为你收集整理的java – 使接口编程而不是语义是什么意思?全部内容,希望文章能够帮你解决java – 使接口编程而不是语义是什么意思?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1108146.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存