Complex inheritance scenario - oop

Let's say you need to build an application that manages cheques. Each cheque contains data about the amount of money, the date, the payee and an additional payment date which may or may not be present. Additionally, each cheque must be related to a current account which belongs to a certain bank.
Now, our application should allow cheques printing under these conditions:
Each bank managed by the app has a different cheque layout (i.e. each field has a different x,y position).
The cheque layout changes slightly if the payment date is present, even with the same related bank object. But, from bank to bank these changes may not be the same (e.g. bank A may vary position for the date field, while bank B changes position for the payee field)
With these restrictions in place, it's difficult to come up with a simple inheritance schema as there is no consistent behavior to factor out accross the different types of cheques there are. One possible solution would be to avoid inheritance and create a class for every cheque - bank combination:
class ChequeNoPaymentDateForBankA
class ChequeWithPaymentDateForBankA
class ChequeNoPaymentDateForBankB
class ChequeWithPaymentDateForBankB, etc.
Each of these classes implement the print() method which takes the fields positions from a Bank object and builds up the cheque layout. So far so good, but this approach leaves me with a strange feeling as there is no room for code reuse. I wonder if I'm misinterpreting the problem and perhaps there is a better way. As this is not a new problem domain at all, I'm sure this is a reinvent-the-wheel effort. Any insights will be kindly appreciated.

Usually in these situations I move from inheritance to delegation. That is, instead of putting the common code in a superclass (which, as you say, is problematic becuase there are two dimensions), I put the common in a field (one field per dimension) and delegate to that field.
Assuming you're speaking about Java:
public interface Bank {
public void print();
}
public class BankA implements Bank {
public void print() { ... }
}
public class BankB implements Bank {
public void print() { ... }
}
public interface PaymentSchedule {
public void print();
}
public class WithPaymentDate implements PaymentSchedule {
public void print() { ... }
}
public class NoPaymentDate implements PaymentSchedule {
public void print() { ... }
}
public class Cheque {
private final Bank bank;
private final PaymentSchedule schedule;
public Cheque(Bank b, PaymentSchedule s) {
bank = b;
schedule = s;
}
public void print() {
bank.print();
schedule.print();
}
}
That's the general structure of the solution.
Depending on the exact details of your print() algorithm you may need to pass some more data into the print methods and/or to pass this data into the constructors of the classes (of the Bank or PaymentSchedule subclasses) and store it in fields.

I would start by separating the domain model (cheques, banks, etc) from the view (the way the cheques are printed). This is the basic idea behind the MVC pattern and one of its aims is to allow the same domain model to be displayed in different ways (which seems to be your case). So, I would first create the domain classes, something like:
class Cheque
{
protected $bank;
protected $money;
...
}
class Bank {...}
Note that these classes are the "M" of the MVC triad and implement the logic of your domain model, not the behavior related to the rendering process. The next step would be to implement the View classes used to render a cheque. Which approach to take heavily depends on how complex your rendering is, but I would start by having a ChequeView class that renders the common parts and that delegates to other sub-view the specific parts that can change (in this case the date):
abstract class ChequeView
{
protected $cheque;
protected $dateView;
public function __construct($cheque)
{
$this->cheque = $cheque;
$this->dateView = //Whatever process you use to decide if the payment date is shown or not
}
public function render()
{
$this->coreRender();
$this->dateView->render();
}
abstract protected function coreRender();
}
class BankACheckView extends ChequeView
{
protected function coreRender() {...}
}
class BankBCheckView extends ChequeView
{
protected function coreRender() {...}
}
abstract class DateView
{
abstract function render()
}
class ShowDateView extends DateView
{
function render() {...}
}
class NullDateView extends DateView
{
function render() {...}
}
And, if there is code to reuse across subclasses, you can of course factor them in ChequeView and make coreRender() call them.
In case your rendering turns to be too complex, this design may not scale. In that case I would go for splitting your view in meaningful subparts (e.g. HeaderView, AmountView, etc) so that rendering a cheque becomes basically rendering its different sub-parts. In this case the ChequeView may end basically working as a Composite. Finally, if you reach this case and setting up the ChequeView turns out to be a complex task you may want to use a Builder.
Edit based on the OP comments
The Builder is mostly used when the instantiation of the final object is a complex process (e.g. there are many things to sync between the sub-parts in order to get a consistent whole). There is generally one builder class and different clients, that send messages (potentially in different orders and with different arguments) to create a variety of final objects. So, while not prohibited, it is not usual to have one builder per type of object that you want to build.
If you are looking for a class that represents the creation of a particular instance you may want to check the Factory family of patterns (maybe the Abstract Factory resembles closely to what you had in mind).
HTH

Related

Different interpretation of internal state based on what client wants

A Model object which has some private internal state. A component of this state is exposed to the clients. But one of the clients wants a different component of the internal state to be exposed. How should this be dealt with?An example
public GarageModel {
private Vehicle car;
private Vehicle truck;
public Vehicle getMostInterestingVehicle() {
//exposes car as the most interesting vehicle but
//one of the client wants this to return a truck
return car;
}
}
It is hard to say given your sample, you could apply a strategy pattern on your GarageModel class for each different client and override that single method to cater to each of their needs. This only works if you can provide different garage models to your clients though.
Polymorphism is always the answer as a teacher of mine used to say
An example would be
public TruckGarageModel: GarageModel {
public override Vehicle getMostInterestingVehicle(){
return truck;
}
}
public CarGarageModel: GarageModel {
public override Vehicle getMostInterestingVehicle(){
return car;
}
}
Then you would pass the appropriate decorated version of your GarageModel to each different client
You could provide method with parameters which will define criteria by which your client sees most interesting vehicle.
public Vehicle getMostInterestingVehicleByCriteria(VehicleCriteria vehicleCriteria){
// logic which selects correct vehicle in simple way it will be just
if(vehicleCriteria.getMostInterestingVehicleType().equals(VehicleType.TRUCK){
//do your logic
}
// In case of multiple objects you should refactor it with simple inheritance/polymorphism or maybe use some structural pattern
}
public class VehicleCriteria{
VehicleType mostInterestingVehicle; // enum with desired vehicle type
public VehicleCriteria(VehicleType mostInterestingVehicle){
this.mostInterestingVehicle = mostInterestingVehicle;
}
}
If the client knows what type it wants, then let the client say so with a generic argument (C# assumed):
public T getMostInterestingVehicle<T>() where T : Vehicle { }
You can then use a dictionary of 'things' (factories maybe?) that will get a vehicle, keyed by the type they return. This could be a static collection created on construction or resolved by IoC:
private Dictionary<T, Vehicle> _things;
You can then use this to do the work:
public T getMostInterestingVehicle<T>() where T : Vehicle
{
FactoryThing thing;
if (_things.TryGetValue(T, out thing))
{
return thing.GetVehicle();
}
}
Apologies if it's not C# you're working with and if the syntax/usage is incorrect, but I think you'll get my point...
You might have to consider quite a few things before making a decision about the implementation, some questions are these-
Do you expect newer implementations of Vehicle to be added later?: If yes, you might have to provide a factory that could register newer types without you making changes in the factory again and again. This provides an example. That way you avoid many if-else as well.
Do you want to decide what Vehicle to return at runtime?: Then Strategy Pattern helps as pointed in other answers.
Hope this helps a little bit.

How can I achieve this via oops concepts

I am facing a design problem. This must only be solved by applying oops concepts. I am describing the problem below.
Problem: Suppose You have a class called X . It has two Paid (Chargeable) methods like m, n. Their may be many consumers classes of these methods. Someone pays for m, someone pays for n and someone pays for both m, n.
Now I have to design my X class in such a way that consumers can only see that method for which they make payment. How can we do this via OOPS concepts? I can make appropriate changes in my X class to achieve this design. Sample class is written below.
class X { // service class
public m(){ // do some stuff
}
public n(){ // do some stuff
}
}
Create 3 interfaces: one containing the m method, one containing n and a third containing both (the third interface can extend the two others). Then make your class X implement those interfaces.
You will then be able to expose the appropriate interface to your consumers, depending on their needs, while still using the same X class.
interface M { // exposed to customers paying for m
void m();
}
interface N { // exposed to customers paying for n
void n();
}
interface Mn extends M, N {} // exposed to customers paying for both
class X implements Mn {
#Override
public m(){ // do some stuff
}
#Override
public n(){ // do some stuff
}
}
I think you are not taking advantage of the class state. Class can store information in its instance fields about the user, and change its behavior accordingly.
One possible option would be:
class Payment {
int paymentType = 0; // fill with constructor for i.e.
public pay(int sum){
// some common behavior
switch(this.paymentType){
case 1:
// pay 1 logic
break;
case 2:
// pay 2 logic
break;
}
// some other common behavior
}
}
In another design you might use the Strategy pattern to have family of decoupled algorithms.
In the above code I assumed we are talking about some logically related code. If the code has nothing in common, you might even split it into other classes.
Update: I wouldn't advice on using it, but you can implement the Template Method pattern. The problem is you are going to overuse inheritance.
abstract class Payment {
public Pay(int sum){
// some common code
this.doPay(sum);
}
abstract protected doPay(int sum);
}
class PaymentOne : Payment {
protected doPay(int sum){
// pay 1 logic
}
}
class PaymentTwo : Payment {
protected doPay(int sum){
// pay 2 logic
}
}
You'd better use polymorphism concept
As example, based on assumption that m and n has different types:
class X{ // service class
public Pay(NType n){ // do some stuff
}
public Pay(MType m){ // do some stuff
}
public Pay(NType n, MType m){ // do some stuff
Pay(n);
Pay(m);
}
}

"Tell, Don't Ask" over multiple domain objects

Question
How do I adhere to the "Tell, Don't Ask" principle when performing a function involving multiple objects.
Example - Generating a Report
I have the following objects (illustrative purposes only):
Car, Horse, Rabbit
There is no relationship between these objects, but I do want to generate a Report based on these objects:
createHtmlReport(Car car, Horse horse, Rabbit rabbit){
Report report = new Report()
report.setSomeField(car.getSerialNumber())
report.setAnotherField(horse.getNumberOfLegs())
// ...etc
}
The problem with this method is that it has to "Pull" data from each object, which violates the "Tell, Don't Ask" rule. I would rather keep the insides of each object hidden, and have them generate a report for me:
car.createHtmlReport()
horse.createHtmlReport()
rabbit.createHtmlReport()
... but then I get 3 partial reports. Furthermore, I don't think a Rabbit should have to know how to generate every single report I need (HTML, JMS, XML, JSON ....).
Finally, whilst generating the report I may want to switch on multiple items:
if (car.getWheels() == 4 || horse.getLegs() == 4)
// do something
The report should maintain the ability to create its self.
In this case, each IReportable object should Implement void UpdateReport(Report aReport).
When Report.CreateReport(List<Reportable> aList) is invoked, it iterates through the List and each object in its own implementation of UpdateReport invokes:
aReport.AddCar(serialNumber)
aReport.AddHorse(horseName)
At the end of CreateReport, the report object should produce its own result.
The goal of "Tell don't ask" rule is to help you identify situations where the responsibility that should lie with the given object ends up being implemented outside of it (bad thing).
What responsibilities can we see in your case? What I see is:
1) knowing how to format the report (in xml, ascii, html, etc)
2) knowing what goes on which report
First one obviously does not belong with the domain object (Car, Horse etc.). Where should the 2) go? One could suggest the domain object but if there are multiple different reports in your system you end up burdening your objects with knowledge about differnt report details which would look and smell bad. Not to mention that it would violate the Single Responsibility Principle: being a Rabbit is one thing but knowing which parts of Rabbit information should go on report X vs. report Y is quite another.
Thus I would design classes which encapsulate data contents that go on a specific type of report (and possibly perform necessary calculations). I would not worry about them reading the data members of Rabbit, Horse or Car. The responsibility this class implements is 'gathering the data for a specific type of a report' which you've consciously decided should lie outside of the domain object.
That's exactly what the Visitor Pattern is for.
I don't know exactly this pattern's name (Visitor, Builder, ...):
public interface HorseView {
void showNumberOfLegs(int number);
}
public interface CarView {
void showNumberOfWheels(int number);
void showSerialNumber(String serialNumber);
}
public class Horse {
void show(HorseView view) {
view.showNumberOfLegs(this.numberOfLegs);
}
}
public class Car {
void show(CarView view) {
view.showNumberOfWheels(this.numberOfWheels);
view.showSerialNumber(this.serialNumber);
}
}
public class HtmlReport implements HorseView, CarView {
public void showNumberOfLegs(int number) {
...
}
public void showNumberOfWheels(int number) {
...
}
public void showSerialNumber(String serialNumber) {
...
}
}
public XmlModel implements HorseView, CarView {
...
}
public JsonModel implements HorseView, CarView {
...
}
This way you can have multiple representations of the same domain object, not violating "Tell don't ask" principle.

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.

Where to put methods used by multiple classes?

To show an example what is this question about:
I have currently a dilemma in PHP project I'm working on. I have in mind a method that will be used by multiple classes (UIs in this case - MVC model), but I'm not sure how to represent such methods in OO design. The first thing that came into my mind was to create a class with static functions that I'd call whenever I need them. However I'm not sure if it's the right thing to do.
To be more precise, I want to work, for example, with time. So I'll need several methods that handle time. I was thinking about creating a Time class where I'd be functions that check whether the time is in correct format etc.
Some might say that I shouldn't use class for this at all, since in PHP I can still use procedural code. But I'm more interested in answer that would enlighten me how to approach such situations in OOP / OOD.
So the actual questions are: How to represent such methods? Is static function approach good enough or should I reconsider anything else?
I would recommend creating a normal class the contains this behavior, and then let that class implement an interface extracted from the class' members.
Whenever you need to call those methods, you inject the interface (not the concrete class) into the consumer. This lets you vary the two independently of each other.
This may sound like more work, but is simply the Strategy design pattern applied.
This will also make it much easier to unit test the code, because the code is more loosely coupled.
Here's an example in C#.
Interface:
public interface ITimeMachine
{
IStopwatch CreateStopwatch();
DateTimeOffset GetNow();
}
Production implementation:
public class RealTimeMachine : ITimeMachine
{
#region ITimeMachine Members
public IStopwatch CreateStopwatch()
{
return new StopwatchAdapter();
}
public DateTimeOffset GetNow()
{
return DateTimeOffset.Now;
}
#endregion
}
and here's a consumer of the interface:
public abstract class PerformanceRecordingSession : IDisposable
{
private readonly IStopwatch watch;
protected PerformanceRecordingSession(ITimeMachine timeMachine)
{
if (timeMachine == null)
{
throw new ArgumentNullException("timeMachine");
}
this.watch = timeMachine.CreateStopwatch();
this.watch.Start();
}
public abstract void Record(long elapsedTicks);
public virtual void StopRecording()
{
this.watch.Stop();
this.Record(this.watch.ElapsedTicks);
}
}
Although you say you want a structure for arbitrary, unrelated functions, you have given an example of a Time class, which has many related functions. So from an OO point of view you would create a Time class and have a static function getCurrentTime(), for example, which returns an instance of this class. Or you could define that the constuctors default behaviour is to return the current time, whichever you like more. Or both.
class DateTime {
public static function getNow() {
return new self();
}
public function __construct() {
$this->setDateTime('now');
}
public function setDateTime($value) {
#...
}
}
But apart from that, there is already a builtin DateTime class in PHP.
Use a class as a namespace. So yes, have a static class.
class Time {
public static function getCurrentTime() {
return time() + 42;
}
}
I don't do PHP, but from an OO point of view, placing these sorts of utility methods as static methods is fine. If they are completely reusable in nature, consider placing them in a utils class.