我应该使用公共还是私有变量? [英] Should I use public or private variables?

查看:126
本文介绍了我应该使用公共还是私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次做一个大项目。我有很多类,其中一些有公共变量,一些有私有变量与setter和getter方法,并有相同的两种类型。

I am doing a large project for the first time. I have lots of classes and some of them have public variables, some have private variables with setter and getter methods and same have both types.

我决定重写这个代码主要使用一种类型。但是我不知道应该使用哪个变量(仅用于同一对象中的方法的变量始终是私有的,而不是这个问题的主题)。

I decided to rewrite this code to use primarily only one type. But I don't know which I should use (variables which are used only for methods in the same object are always private and are not subject of this question).

I知道公共和私人意味着什么,但在现实世界中使用什么,为什么?

I know the theory what public and private means, but what is used in the real world and why?

推荐答案

私有数据成员通常被认为是好的,因为它们提供封装。

private data members are generally considered good because they provide encapsulation.

为他们提供getter和setter打破了封装,但它仍然优于 public 数据成员,因为只有一次

Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.

您会在调试过程中注意到这一点。如果它是私有的,您知道,您只能修改类中的变量。如果是公开的,您必须搜索整个代码库以便修改

You'll notice this during debugging. If it's private, you know you can only modify the variable inside the class. If it's public, you'll have to search the whole code-base for where it might be modified.

尽可能地禁止getters / setters和make属性 private 。这遵循信息隐藏的原则 - 你不应该关心类有什么属性。它应该是自包含的。当然,在实践中这是不可行的,如果是,那么跟随这个的设计将比没有的设计更加混乱和难以维护。

As much as possible, ban getters/setters and make properties private. This follows the principle of information hiding - you shouldn't care about what properties a class has. It should be self-contained. Of course, in practice this isn't feasible, and if it is, a design that follows this will be more cluttered and harder to maintain than one that doesn't.

这当然是一个经验法则 - 例如,我只是使用 struct (等同于 class with public access)for,say,a simple point class:

This is of course a rule of thumb - for example, I'd just use a struct (equivalent with a class with public access) for, say, a simple point class:

struct Point2D
{
   double x;
   double y;
};

这篇关于我应该使用公共还是私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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