简体   繁体   English

我应该争取一个成员职责单一的成员功能还是最小化成员变量的数量?

[英]Should I strive for either member functions with a single responsibility or minimising the number of member variables?

I have a class called SolarPosition that has many member functions. 我有一个名为SolarPosition的类,它具有许多成员函数。 I currently have a member function called CalculateSolarAzimuthAndAltitude which is a prime candidate for refactoring. 我目前有一个名为CalculateSolarAzimuthAndAltitude的成员函数,它是重构的主要候选者。

I found that the only way to refactor it to CalculateSolarAzimuth and CalculateSolarAltitude was to add an additional ten member variables, as some preliminary calculations are used by both functions. 我发现将其重构为CalculateSolarAzimuthCalculateSolarAltitude的唯一方法是添加额外的十个成员变量,因为这两个函数都使用了一些初步计算。

Should I be happy with a member function with two responsibilities, or are multiple transient member variables a reasonable sacrifice in order to split it up? 我应该对担负两个职责的成员函数感到满意,还是为了将其拆分而将多个临时成员变量作为合理的牺牲?

My suggestion is to split up responsibilities into to two member functions. 我的建议是将职责分为两个成员职能。 If that introduce ten addition transient variables, you can define a struct to group them together and define member from that struct in the SolarPosition class. 如果这样引入了十个附加瞬态变量,则可以定义一个结构以将它们分组在一起,并在SolarPosition类中定义该结构的成员。 that will improve readability as well. 也会提高可读性。

If you still want to keep SolarPosition class much cleaner by hiding internal data variables from the class declaration, refer pimpl-idiom. 如果您仍然想通过隐藏类声明中的内部数据变量来使SolarPosition类更整洁,请参考pimpl-idiom。 for more information visit: Is the pImpl idiom really used in practice? 欲了解更多信息,请访问: pImpl习惯用法是否真的在实践中使用?

If you have that many additional variables to add, I suspect that you have an additional class hiding in your SolarPosition class. 如果要添加的变量太多,我怀疑您的SolarPosition类中隐藏了一个附加类。 Think about extracting that class and go on from there. 考虑提取该类并从那里继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM