IoC 预期接口的命名约定
Naming convention for IoC intended interfaces
当您使用 IoC 框架时,您最终会专门为 IoC 创建接口。我很想为那些人使用命名约定。
比如图片上没有IoC,你可能有如下业务领域驱动结构:
interface IBodyPart
{
string ScientificName { get; set; }
string StreetName { get; set; }
}
class Head : IBodyPart
{
public string ScientificName { get; set; }
public string StreetName { get; set; }
}
class BodyPartPoker
{
bool isSituationAcademic;
BodyPartPoker(bool isSituationAcademic)
{
this.isSituationAcademic = isSituationAcademic;
}
void Poke(IBodyPart bodyPart)
{
if (this.isSituationAcademic)
Debug.Print($"Proceeding to poke {bodyPart.ScientificName}");
else
Debug.Print($"Poking that {bodyPart.StreetName} LOL");
}
}
现在假设您想使用 IoC 注入 BodyPartPoker
个实例。您还想使用某种单元测试模拟框架来测试该逻辑。
在这种情况下,即使您没有针对它的业务领域案例,您也会引入 IBodyPartPoker
接口:
interface IBodyPartPoker
{
bool IsSituationAcademic { get; set; }
void Poke(IBodyPart bodyPart);
}
class BodyPartPoker : IBodyPartPoker
{
我的问题是:像 IBodyPartPoker
这样的接口有一个命名约定是否有意义,所以我们明确确定它的目的是不与业务领域相关?
说....
interface IIocBodyPartPoker
在 C# 中,约定通常是利用语言的惯用命名约定,并使用前面的 I
命名接口,如 IBodyPartPoker
。这使得 BodyPartPoker
可以自由作为 class.
的名称
在 Java 中,惯例是在不使用匈牙利符号的情况下命名一个接口,因此该接口通常被命名为 BodyPartPoker
,这通常会导致人们将其单个名称命名为 class像 BodyPartPokerImp
.
您应该认为这是一种代码味道,正是因为接口存在的唯一原因似乎是启用单元测试。你可以说它违反了 Reused Abstractions Principle.
给接口起另一个名字,比如 IIocBodyPartPoker
,并不能解决根本问题。
如果存在专门用于支持单元测试的接口,您很可能会发现测试与实现细节过于耦合,并且每次您尝试重构生产代码时,测试都会中断。同样,命名约定不会解决此类问题。
当您使用 IoC 框架时,您最终会专门为 IoC 创建接口。我很想为那些人使用命名约定。
比如图片上没有IoC,你可能有如下业务领域驱动结构:
interface IBodyPart
{
string ScientificName { get; set; }
string StreetName { get; set; }
}
class Head : IBodyPart
{
public string ScientificName { get; set; }
public string StreetName { get; set; }
}
class BodyPartPoker
{
bool isSituationAcademic;
BodyPartPoker(bool isSituationAcademic)
{
this.isSituationAcademic = isSituationAcademic;
}
void Poke(IBodyPart bodyPart)
{
if (this.isSituationAcademic)
Debug.Print($"Proceeding to poke {bodyPart.ScientificName}");
else
Debug.Print($"Poking that {bodyPart.StreetName} LOL");
}
}
现在假设您想使用 IoC 注入 BodyPartPoker
个实例。您还想使用某种单元测试模拟框架来测试该逻辑。
在这种情况下,即使您没有针对它的业务领域案例,您也会引入 IBodyPartPoker
接口:
interface IBodyPartPoker
{
bool IsSituationAcademic { get; set; }
void Poke(IBodyPart bodyPart);
}
class BodyPartPoker : IBodyPartPoker
{
我的问题是:像 IBodyPartPoker
这样的接口有一个命名约定是否有意义,所以我们明确确定它的目的是不与业务领域相关?
说....
interface IIocBodyPartPoker
在 C# 中,约定通常是利用语言的惯用命名约定,并使用前面的 I
命名接口,如 IBodyPartPoker
。这使得 BodyPartPoker
可以自由作为 class.
在 Java 中,惯例是在不使用匈牙利符号的情况下命名一个接口,因此该接口通常被命名为 BodyPartPoker
,这通常会导致人们将其单个名称命名为 class像 BodyPartPokerImp
.
您应该认为这是一种代码味道,正是因为接口存在的唯一原因似乎是启用单元测试。你可以说它违反了 Reused Abstractions Principle.
给接口起另一个名字,比如 IIocBodyPartPoker
,并不能解决根本问题。
如果存在专门用于支持单元测试的接口,您很可能会发现测试与实现细节过于耦合,并且每次您尝试重构生产代码时,测试都会中断。同样,命名约定不会解决此类问题。