普遍接受的私人变量声明公约

时间:2012-05-29 15:13:25

标签: c# oop

我目前正在重构一些丑陋的代码,并将一个庞大且过于复杂的类A拆分为带有子类B和C的超类A.

我的问题是,如果我在过度复杂的类中有私有变量,只是在拆分后与子类B相关,那么是否有一个普遍接受的约定来声明这些?

我的选择是:

protected variable in superclass A
pro: all variables located in central location
con: some variables in superclass unused by all subclasses

private variable in subclass B
pro: only shared variables present in superclass A (more "proper"?)
con: more complicated code management

谢谢你的时间!

3 个答案:

答案 0 :(得分:4)

  
    

我的问题是,如果我在过度复杂的类中有私有变量仅在分裂后与子类B 相关,那么是否有一个普遍接受的约定来声明这些?

  

如果它们仅与B类相关,则将它们放入B类。要做任何其他事情,会降低代码的可读性,并在将来引起混淆。

如果您想证明您对某人的回答是正确的,您可以指向Separation of Concerns (SoC),这可以解决您的分手课程。

答案 1 :(得分:2)

@Ramhound是对的:变量应该在需要它的类中

A - variables that are shared by both C and B
B - variables that belongs to B only
C - Variables that belongs to C only

答案 2 :(得分:1)

绝对把它们放在子类B中,你应该将这些方法放在他们都继承的类中的唯一原因是两者都将使用该方法,或者在不久的将来可能会添加另一个类并且将会使用方法,属性,字段或案例变量