should I use aggregation in this case? - oop

In the case that I have a class called Payment that it is a superclass of another class named Card, how can I join that class with another that verifies if the card is valid.
My UML diagram would be like this:
Payment<---------Card
I have thought of two ways of doing this, but I would like to know which one would be the correct one:
1) model with association to check if the credit card is valid, but not join this to paymentCard:
Card_list---1--------------1*---<>Card
so within my class Card I call something like:
class paymentCard extends Payment
{
public authorized() ---abstract method
{
if card.verified(card_number) return true; ---here I call the card class
else return false;
}
}
2) I have read that I can use aggregation, but I am a little dubious how to use it:
class paymentCard extends Payment
{
Card creditcard //aggregation
public authorized()
{
creditcard=new Card(numberCard)
if creditcard.verified() return true;
else return false;
}
}
which one of the two forms is better? For me, the first one looks like a query to a external class that can be also a database, while the second one I am not pretty sure about it
Any comment?

One day you could want to have other payment methods.
IMO, a Payment has a payment_method that can be ByCard, By..., so:
class Payment
{
protected PaymentMethodoption;
}
abstract class PaymentMethod
{
public abstract bool authorized();
}
class PaymentByCreditCard : PaymentMethod
{
public override bool authorized() { return card.verified(card_number); }
}

Well, you basically answered your own question. The key-question is: how expensive is creating a credit-card object? Probably is not just pass a number to it as you did on your second example, which means pobably you'll have them stored somewhere else.

Related

When is casting/instanceof a good use?

Every time I google instanceof and casting I will always see answers saying to avoid it and use X pattern.
I have an example where I can't see any pattern I think I could use.
We have 2 classes: Order and Payment (CashPayment and CardPayment).
CashPayment has 1 property called amount and and an implemented method pay.
CardPayment has 1 property called cardNumber and an implemented pay that calls 3rd party API.
Now say you would like to compose a view about an Order, how would someone avoid using instanceof or casting here to show the payment details?
With instanceof I can do this:
order = new Order(...);
order.checkout(aPayment);
Payment Details (Cash):
Type: (instanceof CashPayment ? "Cash") or order.payment().type();
Amount: ((CashPayment) order.payment()).amount();
Payment Details (Card):
Type: (instanceof CardPayment ? "Card") or order.payment().type();
Card Number: ((CardPayment) order.payment()).cardNumber();
Question: can we really avoid instanceof and casting? If yes, how can we achieve this the "OO-way"? If no, I assume this is one of the valid cases?
IMO, we can avoid instanceof/casting and favor use of overridden methods however if you want to know about a concrete object it can't be avoided.
Edit:
I am trying to write my Domain Models which means it is agnostic of infrastructure and application specific stuff.
Imagine we would need to save the Order thru OrderRepository and the Payment has their own tables. Wouldn't it be ugly if it was like:
class OrderRepository {
public function save(Order order) {
// Insert into order query here...
// Insert into orderItems query here...
// Insert payment into its table
queryBuilder
.table(order.payment().tableName())
.insert([
order.payment().columnName() => order.payment().value()
]);
}
}
If you absolutely want to segregate the operation from the object itself (e.g. to maintain separation of concerns), but the operation is strongly coupled to subclass details then you only have two choices.
You either need to rethink the model and find an homogeneous abstraction, which could be any approach that allows you to treat the various types the same way.
e.g.
Payment Details:
Type: {{payment.type}}
{{for attr in payment.attributes}}
{{attr.name}}: {{attr.value}}
{{/}}
or you need to perform some kind of type matching, whether you are using the visitor pattern, pattern matching, instanceof, etc.
e.g. with the Visitor Pattern
interface IPaymentVisitor {
public void visit(CashPayment payment);
public void visit(CardPayment payment);
}
class PaymentRenderer implements IPaymentVisitor ...
class CashPayment extends Payment {
...
public void visit(IPaymentVisitor visitor) {
visitor.visit(this);
}
}
var renderer = new PaymentRenderer(outputStream);
payment.accept(renderer);
The obvious object-oriented solution is to add a display() method to the Payment.
In general instanceof/casting is frowned upon, because it usually indicates a less then optimal design. The only time where it is allowed is when the type-system is not powerful enough to express something. I encountered a few situations in Java where there is no better solution (mostly because there are no read-only collections in Java, therefore the generic parameter is invariant), none in Scala or Haskell yet.
You could go with composition over inheritance.
Perhaps something along the lines of:
public class Payment
{
private CardPaymentDetail _cardPaymentDetail;
public PaymentType Type { get; private set; }
public decimal Amount { get; }
private Payment(decimal amount)
{
// > 0 guard
Amount = amount;
}
private Payment(decimal amount, CardPaymentDetail cardPayment)
: this(amout)
{
// null guard
CardPayment = cardPayment;
}
public CardPaymentDetail CardPayment
{
get
{
if (Type != PaymentType.Card)
{
throw new InvalidOperationException("This is not a card payment.");
}
return _cardPaymentDetail;
}
}
}
IMHO persistence may also be easier. Along the same lines I have also used what equates to an Unknown payment type as the default and then have a method to specify the type: AsCard(CardPaymentDetail cardPayment) { }.

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);
}
}

Design a Furniture class with classes like WoodChair, WoodTable etc

This is an OOD based interview question:
There is a Furniture class and has derived classes like WoodChair, WoodTable, SteelChair, SteelTable. Interviewer wanted to add more number of classes like ironchair,irontable etc; How should we do that. The design is not yet published and we are free to modify the entire sutff given.
I thought that since we're basically building types of furniture we should use a builder pattern here with Furniture class with properties like type (chair/table) and make(iron/wood) etc. Then we'd have an interface Builder with functions like: buildLegs(..), buildSurface(..) and sub-classes like ChairBuilder, TableBuilder and a Director class to instantiate all of them. We could add as many new types of Furniture of any make and construct a builder class for them without affecting existing design.
After reading Builder Vs Decorator pattern I was sure that I'm not supposed to use Decorator pattern here. But is Builder also ok? Is it an overkill?
Also, I'm not sure how to deal with the make of the furniture. Would adding a feature of type enum for the make be enough? [steel, iron, wood] The make doesn't really add any new behavior to the furniture items.
It looks like something needs to be refactored in the existing classes, which may also help avoiding creating a new class for every one of the need that arise in the future. This depends entirely on the context though: an inventory application needs a radically different model of a chair than a software that needs to display a chair in 3d. How do you know? Ask the interviewer, then you will know where they want you to go.
Boring case: a Chair has some common behavior/data that can be refactored out in a different class, same thing for Table. Now how do you choose to represent the material? Again, it depends on the domain, ask the interviewer. It is also a matter of the language you are using: does your language of choice support multiple inheritance? Do you need (or want) to use multiple inheritance at all? It may make sense to favor composition over inheritance. Why would you go one way or the other? Do you even need a class to represent this piece of information?
How should we do that.
Ask the interviewer, they will guide you to the solution. There is no single correct answer to a problem so broadly formulated, they want you to ask questions and see how you think. That said, as broad as the question is, the way it is formulated may be a hint that you should refactor something in order to avoid having to create a class for every new combination of furniture and material.
Possible solutions:
No need for Table/Chair/Bed to inherit from Furniture: a class Furniture with a property for the piece of furniture and a property for the material.
Classes for Table, Chair, Bed, whatever with a property for the material. The complexity of how the material is represented depends on how this information have to be modeled: it could be a string, or a Class (Wood, Iron, Steel) implementing an IMaterial interface.
Probably, i was use Abstract Factory: WoodFurntiture, SteelFurniture, IronFurniture.
Each Factory know How to make chair, table.
Inside you can use (if you need) other DP, but for a now, i do not see any needs for it
Code:
namespace Furniture
{
class Program
{
static void Main(string[] args)
{
IFurnitureFactory factory = new WoodFurnitureFactory();
IFurniture chair = factory.GetChair();
}
}
public interface IFurniture { }
public class WoodChair : IFurniture { }
public class WoodTable : IFurniture { }
public class SteelChair : IFurniture { }
public class SteelTable : IFurniture { }
public class IronChair : IFurniture { }
public class IronTable : IFurniture { }
public interface IFurnitureFactory
{
IFurniture GetChair();
IFurniture GetTable();
}
public class WoodFurnitureFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new WoodChair();
}
public IFurniture GetTable()
{
return new WoodTable();
}
}
public class IronFurnitureFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new IronChair();
}
public IFurniture GetTable()
{
return new IronTable();
}
}
public class SteeFurniturelFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new SteelChair();
}
public IFurniture GetTable()
{
return new SteelTable();
}
}
}

Complex inheritance scenario

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