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

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

问题描述

我第一次做一个大项目.我有很多类,其中一些有公共变量,一些有带有 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 know the theory what public and private means, but what is used in the real world and why?

推荐答案

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

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.

尽可能禁止 getter/setter 并将属性设为 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)作为,例如简单点类:

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天全站免登陆