I'm making a change to an API that serves data. Some of the searches require data about an author and take a IAuthor
object. The API has an IAuthor
interface and a single concrete class that implements IAuthor
called Author
.
I need to add a boolean property, IsNovelist
that will change the semantics of some but not all searches.
I've heard about the open/closed principle and it would seem that changing the IAuthor
and/or Author
classes would violate this. How then to make this simple change?
UPDATE:
Perhaps I was concentrating on the wrong class. I don't want to add behaviour to Author
class (it's just a way of passing parameters to the API). So a Decorated
author wouldn't need a boolean flag because it would be isNovelist == true
by implication.
I need to change the behaviour of the GetBooks
method given an author who is flagged as being a novelist. So something more like this but my thinking is probably wonky because now I'm changing (not extending) the Books
class:
//Before
class Books
{
public Books[] GetBooks(IAuthor author){
// Call data access GetBooks...
}
}
//After
class Books
{
public Books[] GetBooks(IAuthor author){
// To maintain pre-existing behaviour
// call data access GetBooks with SQL param @isNovelist = false...
// (or don't pass anything because the SQL param defaults to false)
}
public Books[] GetBooksForNovelist(IAuthor author){
// To get new behaviour
// call data access GetBooks with SQL param @isNovelist = true
}
}
Solution 2 :
Solution 1 :
Here is how you do using the decorator pattern