作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在查看此处显示的 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 将始终只访问一个实例字段。
最佳答案
这表明,如果您盲目地将其发挥到极致,那么每个软件指标都是有缺陷的。
当你看到一个类时,你就知道它是一个“缺乏凝聚力”的类。例如:
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;
}
真的,我认为最好理解什么是内聚力,以及为什么它是一个有值(value)的目标,但也要明白软件工具无法正确衡量它。
关于c# - 为什么方法缺乏凝聚力(LCOM)包括getters和setters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013032/
我是一名优秀的程序员,十分优秀!