为什么缺乏方法的凝聚力(LCOM)包括Getters和Setter

时间:2011-05-16 03:58:59

标签: c# .net ndepend lcom

我正在查看此处显示的LCOM指标,

http://www.ndepend.com/Metrics.aspx

所以我们说了几句话,

1) A class is utterly cohesive if all its methods use all its instance fields
2) Both static and instance methods are counted, it includes also constructors, properties getters/setters, events add/remove methods

如果我看一下这样的课程,

public class Assessment
{
    public int StartMetres { get; set; }
    public int EndMetres { get; set; }
    public decimal? NumericResponse { get; set; }
    public string FreeResponse { get; set; }
    public string Responsetype { get; set; }
    public string ItemResponseDescription { get; set; }
    public string StartText { get; set; }
    public decimal? SummaryWeight { get; set; }
}

得分为0.94,因为每个getter和setter都不会访问“所有其他实例字段”。

这样计算,

accessAverage - methodCount / 1 - methodCount

(2 - 17) / (1 - 17) = 0.94 (rounded)

我不理解这个指标,为什么它应该包括getter和setter? getter和setter将始终只访问一个单个实例字段。

1 个答案:

答案 0 :(得分:26)

这表明,如果你盲目地将它发挥到极致,每个软件指标都是有缺陷的。

当你看到一个“无关紧要”的课时,你就知道了。例如:

class HedgeHog_And_AfricanCountry
{

   private HedgeHog _hedgeHog;
   private Nation _africanNation;

   public ulong NumberOfQuills { get { return _hedgeHog.NumberOfQuills; } }
   public int CountOfAntsEatenToday { get { return _hedgeHog.AntsEatenToday.Count(); } }

   public decimal GrossDomesticProduct { get { return _africanNation.GDP; } }
   public ulong Population { get { return _africanNation.Population; } }
}

这显然是一个不连贯的类,因为它包含两个不需要彼此相关的数据。

但是虽然我们很明显这个课程是不完整的,但你怎么能得到一个软件程序来确定不连贯?怎么会说上面的课是不连贯的,但这不是?

class Customer
{
    public string FullName { get; set; }
    public Address PostalAddress { get; set; }
} 

他们提出的指标肯定会检测到不连贯,但也会出现误报。

如果您认为此指标很重要怎么办?您可以创建一个仅包含字段的“CustomerData”类,以及一个将数据字段公开为属性的“Customer”类。

// This has no methods or getters, so gets a good cohesion value.
class CustomerData
{
    public string FullName;
    public Address PostalAddress;
}

// All of the getters and methods are on the same object
class Customer
{
   private CustomerData _customerData;
   public string FullName { get { return _customerData.FullName; } }
   // etc
}

但是,如果我正在玩这个游戏,我也可以将它应用于不连贯的例子:

class Hedgehog_And_AfricanCountry_Data
{
   public Hedgehog _hedgehog;
   public AfricanNation _africanNation;
}

class Hedgehog_And_AfricanCountry
{
   private Hedgehog_And_AfricanCountry_Data _hedgehogAndAfricanCountryData;
   // etc;
}

真的,我认为最好了解什么是凝聚力,为什么它是一个有价值的目标,但也要明白软件工具无法正确衡量它。