How could ExpandoObjects be used to replace the listed incrementally composed classes?

83 views Asked by At

I don't think a design pattern can be used in this sense. The case scenario is having a base object that has these properties and corresponding getters/setters always defined: (id,name,content). In addition to that there will be objects that have optional properties and corresponding getters/setters (comments, author, deleted). I would like those object to provide the API with the exact properties/methods that I need nothing more and nothing less.

One approach is to have everything in one class which has a bloat of state

class Article {
    int id;
    int name;
    String content;
    List<Comment> comments;
    Author author;
    bool deleted;

    //getters and setters omitted 
}

The other one is to have multiple classes but that causes bloat of class Names

class Article {
    int id;
    int name;
    String content;
    //getters and setters omitted 
}


class DeletedArticle : Article {
    bool deleted = true;
    //getters and setters omitted 
}


class ArticleWithAuthor : Article {
    Author author;
    //getters and setters omitted 
}


 class ArticleWithComments : Article {
    List<Comment> comments;
    //getters and setters omitted 
}


 class DeletedArticleWithAuthor : Article {
    bool deleted = true;
    Author author;
    //getters and setters omitted 
 }

 class DeletedArticleWithComments : Article {
    bool deleted = true;
    List<Comment> comments;
    //getters and setters omitted 
 }

 class DeletedArticleWithAuthorAndComments : Article {
    bool deleted = true;
    Author author;
    List<Comment> comments;
    //getters and setters omitted 
 }

 //AND SO ON... 

Since all the possible configurations of a Class that always has (id,name,content) and three optional variables is 2^3 I wonder if there is a way to do it with design patterns (hopefully without Reflection). Keep in mind that I know I could use a more relaxed type-wise language or just use JSON/XML but that is not the point :P. Also I am not familiar with partial classes (from C#) if that is relevant at all.

As it was pointed to me ExpandoObjects could be the way. Could you please provide some example code to represent ArticleWithComments and DeletedArticleWithAuthorAndComments for example so these wont be needed to be defined as separate classes?

Thanks

0

There are 0 answers