直接访问成员变量还是作为参数传递? [英] Access member variables directly or pass as parameter?

查看:327
本文介绍了直接访问成员变量还是作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,即使尊重OOD的单一责任原则,有时班级仍会增加.有时,直接在方法中访问成员变量感觉就像是具有全局状态,并且在当前作用域中存在很多东西.仅通过查看当前使用的方法,就无法确定当前范围内可访问的单个变量的来源.

I noticed that even when paying respect to the single responsibility principle of OOD, sometimes classes still grow large. Sometimes accessing member variables directly in methods feels like having global state, and a lot of stuff exists in the current scope. Just by looking at the method currently working in, it is not possible anymore to determine where invidiual variables accessible in the current scope come from.

最近与朋友一起工作时,我意识到自己编写的代码比他多得多,因为我仍然将成员变量作为参数传递给每个方法.

When working together with a friend lately, I realized I write much more verbose code than him, because I pass member variables still as parameters into every single method.

这是不好的做法吗?

例如:

class AddNumbers {
public:
    int a, b;
    // ...
    int addNumbers {
        // I could have called this without arguments like this:
        // return internalAlgorithmAddNumbers();
        // because the data needed to compute the result is in members.
        return internalAlgorithmAddNumbers(a,b);
    }

private:
    int internalAlgorithmAddNumbers(int sum1, int sum2) { return sum1+sum2; }
};

推荐答案

如果类具有成员变量,请使用它们.如果要显式传递参数,请使其成为自由函数.传递成员变量不仅使代码更加冗长,而且还违反了人们的期望并使代码难以理解.

If a class has member variables, use them. If you want to pass parameters explicitly, make it a free function. Passing member variables around not only makes the code more verbose, it also violates people's expectations and makes the code hard to understand.

一个类的全部目的是创建一个具有隐式传递的共享状态的函数集.如果这不是您想要做的,请不要使用类.

The entire purpose of a class is to create a set of functions with an implicitly passed shared state. If this isn't what you want to do, don't use a class.

这篇关于直接访问成员变量还是作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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