jeudi 14 juin 2018

Design pattern to reduce code duplication

Lets assume we have 2 sets of classes, one is contains Files (i.e File1, File2 ...), second called Blocks (Block1, Block2,...). Files can contain different amount of blocks properties:

class File1
{
    public Block1 Block1Prop {get;set;}
    public Block8 Block8Prop {get;set;}
}

class File2
{
    public Block1 Block1Prop {get;set;}
    public Block9 Block9Prop {get;set;}
}

class File1
{
    public Block9 Block9Prop {get;set;}
    public Block7 Block7Prop {get;set;}
    public Block4 Block4Prop {get;set;}
    public Block3 Block3Prop {get;set;}
}

class File1
{
    public Block8 Block8Prop {get;set;}
}

. . .

and blocks are just separate classes:

class Block1
{
    public string SomeProperty {get;set}
}

class Block2
{
    public string SomeProperty {get;set}
}

. . .

So to not write same block property (in FileX) over and over again, I've separated the blocks which occur in all files to base abstract class. For the remaining blocks, I can create an interface for each one, then implement it in files (but that wold not reduce code duplication).

interface IBlock1
{
    Block1 Block1Prop {get;set;}
}

interface IBlock8
{
    Block8 Block8Prop {get;set;}
}

class File1: IBlock1, IBlock8
{
    public Block1 Block1Prop {get;set;}
    public Block8 Block8Prop {get;set;}
}

So, is there any simple way (some known design pattern) to avoid code duplication or this type of hierarchy should be written in this way?

Aucun commentaire:

Enregistrer un commentaire