为什么将私有字段和方法放在班级的顶部? [英] Why put private fields and methods at the top of class?

查看:56
本文介绍了为什么将私有字段和方法放在班级的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在许多地方用多种语言看到了这个事实上的标准,但是我却从未理解过-为什么将您的私有字段和方法放在类声明的顶部?隐喻地,似乎私人事物应该位于底部(隐藏),公共事物应该位于顶部,因此,当您从上至下阅读该类时,您首先会看到公共接口,然后是内部工作原理。

I've seen this de facto standard in many places in many languages, but I've never understood it - why put your private fields and methods at the top of a class declaration? Metaphorically it seems like private things should be located at the bottom (hidden) and everything public should be at the top, so that when you read through the class top to bottom you first see the public interface then the inner workings.

这背后的原因是什么?

编辑:只是为了澄清,我并不是说声明所有成员的做法在班级顶部,但将私有成员/方法放在班级声明的顶部,而不要公开。

Just to clarify, I don't mean the practice of declaring all members at the top of the class, but of putting private members/methods at the top of a class declaration, before anything public.

推荐答案

这源于您必须声明所有内容(包括函数和变量)之后才能使用它们的日子。

It stems from the days when you had to declare everything - that includes functions as well as variables - before you could use them.

内部(私有)变量和函数位于文件顶部,而外部(公共)功能位于文件底部。这意味着公共职能可以引用内部职能。如果您有递归,则必须通过声明其概要文件来转发引用该函数。

The internal (private) variables and functions went at the top of the file and the external (public) functions went at the bottom of the file. This meant that the public functions could reference the internal functions. If you had recursion you would have to forward reference the function by declaring it's profile.

当语言允许代码跨越多个文件时,您必须放置公共函数和变量声明转换为头文件,以便可以将其包含在项目中的其他文件中,甚至可以包含在其他项目中。

When languages allowed the code to span several files you had to put public function and variable declarations into header files so that they could be included in the other files in the project - or indeed other projects.

这篇关于为什么将私有字段和方法放在班级的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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