How to design a class hierarchy - oop

I'm designing a class hierarchy for a Java Project. It involves creating a class hierarchy to represent several bank accounts.
Now, all bank accounts have a few attributes in common. These can be moved to an abstract class. However, there is one attribute which is common to several of the bank accounts but not all of them. How should I implement this attribute in the class hierarchy?
I probably shouldn't implement the attribute over and over in all the relevant classes but I can't think of another way to do it..

Let me try and help you out as much as possible.
You can have an interface IBankAccount, which defines the common behavior of the Bank Accounts. There will be just method definitions. E.g. A bank account should allow credit(), debit(), getBalance() etc. methods. It can have some additional methods not so common to all Bank Accounts.
Next you can have a BaseBankAccount class that would be abstract and implement these commmon methods. This is so because credit(), debit() and getBalance() will have a common behavior across bank accounts.
Then you can define a BankDecorator interface that will define BankAccount behaviors. Special Decorators will implement this interface to add extra features to the bank accounts. E.g. CurrentBankAccountDecorator will add the Current account functionality etc.
Hope this helps.

You could use the programming concept of mixins.
See also: D. Ancona, G. Lagorio, and E. Zucca. Jam - designing a Java extension with
mixins. ACM Trans. Program. Lang. Syst., 25(5):641-712, 2003.

Related

OOP Encapsulation Concept

In an interview I have been asked this. Is this is an example of Encapsulation?
class abc
{
}
I tried seeking for the answer from multiple books but couldn't find it.
We would start talking about encapsulation when the following would happen:
The class will have members and methods and therefore becomes a collection of data and methods.
In this class we start hiding the data within, and make it available only through public methods
This technique is known as encapsulation because it seals the data (and internal methods) safely inside the "capsule" of the class, where it can be accessed only by trusted users (i.e., by the methods of the class).
Until no methods and members, I don't think we are talking about encapsulation.
If the class is empty, there is no information to be encapsulated, so no encapsulation here.
No its not,
Encapsulation refers to the act of binding together data members and functions which manipulate them into a single entity.
Mostly they are bound into a class.
But the example here has to data members and functions to encapsulate, so it's not an Encapsulation

why is it recommended to define service contract as an interface

why is it recommended to define service contract as an interface.
Any specific advantages over having them as classes?
The primary goal is separate definition of your service from implementation
The user of your service should not know anything about how you implemented your service, but he should know what operations he can do and how.
That's why its using an interface instead of class, because interface doesn't contain an implementation.
You can share your interface one time and then never worry for years even if you changing implementation of its methods every day. End users will not need to recompile the code that's using your service
Of course [there are several advantages] !
The main one is probably the ability to implement multiple classes which support said Interface and to use these classes interchangeably [with regards to the particular interface]. One of the direct uses of this is with Mock classes used for testing; This is also used with IoC (Inversion of Control) pattern, and more generally wherever we care about the "What" rather than the "Who", i.e. What matters is that whichever class is in place it behaves as per the contract (the API) regardless of "who" (which class) it is.
Another salient advantage of Interfaces is the ability to modularize behavior. For example your application may implement a concept which works, say, like a List (can be iterated over, supplies a number of items, etc.) and like a widget validator (some application specific thing). By having two interfaces "describing" this particular object, you can use instances of that class wherevever you'd use a List (and just that) and similarly you can use it as a widget validator (and just that) whereever these validator are needed. This is akin to multiple inheritance but more flexible.
In a nutshell (and some other answers started with this), the Interface defines the contract and the Class(es) implement(s) it.
Technically, a single class could do both of these things, i.e. you do not __need __ to have Interfaces, but it is very preferable to define APIs for most any behavior which may be implemented by several classes (whether multiple implementations of almost the same thing as with "mock classes", or very different classes but supplying one particular generic service/feature as say two very distinct Lists.)
Because an interface IS a contract and a class is the means to fulfill a contract. There can be many different ways to fulfill a contract based on the context, so It makes more sense to have the contracts as interfaces. which can have different implementations

Architecting common and unique behaviour in code

I am designing a utility to backup applications.
The backup functionality will contain both common tasks to do (common code) and some unique steps. Am I on the right track by using an interface for the unique behaviour and an abstract base class for the common behaviour in common by all the children? Is there any downside to this approach? Anything better?
Thanks
If the base class actually implements some behaviour then I think it's called a non-abstract base class.
Anyway I think that's called Template method pattern: you may want to look that up in a dictionary of patterns (which should explain when it's appropriate, and reference any similar alternative patterns).
I wouldn't use abstract base classes to share common functionality, but only to express is-a relationships. If D derives from B, wherever B is expected, a D can come up. This is the criteria for using public inheritance.
You can use private inheritance though, but you are limited to derive from only one class in some languages.
Which brings us to the point to should be the first - you should think about responsibilites and encapsulate functionality wherever it belongs to, exposing interfaces (or pure abstract classes in C++) to clients, and implementing functionalities in concrete classes that derive from those interfaces.

Abstract classes vs interfaces to represent a family

Abstract classes are described as being useful for a family of objects (e.g. could be used for animals which are mammals). However, what difference is there between using an interface or abstract class for representing a family of related objects?
My process is to use an abstract class when I want to define common functionality but with the option for future extensions and an interface for custom functionality (implementations).
For example, I wrote an abstract class to encapsulate some database functionality which will be used heavily in a small web app at work. I wrote an abstract class with virtual methods which can be overrided with custom functionality in the future (e.g. logging, or some reporting of the database events which may be required).
Is this the right way to go? Is there any significance in choosing one construct (abstract or interface) to represent a family?
An abstract class should be used when there is common state and behavior between all types. An interface should be used when all types will have a common interface but will not share state or behavior.
Here is an example.
German Shepherd, Golden Retriever, Beagle
These three objects are all dogs, and as such they share certain common state (carnivorous, 4 legs, etc.) and they also share certain overridable behavior (bark, pant, etc.). In this instance it would make the most sense to create an abstract Dog class to hold this common state and behavior and create subtypes of Dog for each type of dog.
Pencil, Pen, Chalk
These objects have no common state and they cannot share behavior. Yet you may notice that they do have something in common - they are cabaple of writing. These objects are best build separately and without a base class and then tied together with a Writable interface that exposes each type's Write method.
I would suggest using interfaces so that you can implement new functionality in your database utility at some future point.
As always, the primary design principle when it comes to development is
Design towards an interface, not an implementation
With abstract classes, you can provide implementation that is needed and shared by all the classes in your hierarchy. Therefore, you're reusing code. You may allow the derived classes to override the default behavior or not but at least you're providing a baseline functionality like breathing for a new born animal. However, with interfaces, you can't provide any implementation. You simply define a contract that all classes that inherits that interface should honor and provide implementation for. This may lead to repetitive and duplicate code among the hierarchy of classes.
Interfaces are not very good for extensibility and you need to worry about versioning. You decide to make change to an existing interface but you will soon realize that there are a lot of classes in existence you may need to modify. Think about adding Breath method to IMammal interface that's already being used by many mammals. You will need to go and provide Breath implementation for each one. With an abstract class, you can simply add Breath method and provide some baseline implementation without having to worry about existing derived classes. So abstract classes are more flexible in term of the development of your hierarchy and the api.

Inheritance and interfaces

This is somewhat of a follow-up question to this question.
Suppose I have an inheritance tree as follows:
Car -> Ford -> Mustang -> MustangGT
Is there a benefit to defining interfaces for each of these classes? Example:
ICar -> IFord -> IMustang -> IMustangGT
I can see that maybe other classes (like Chevy) would want to implement Icar or IFord and maybe even IMustang, but probably not IMustangGT because it is so specific. Are the interfaces superfluous in this case?
Also, I would think that any class that would want to implement IFord would definitely want to use its one inheritance by inheriting from Ford so as not to duplicate code. If that is a given, what is the benefit of also implementing IFord?
In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.
And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!
Adam
I also agree with adamalex's response that interfaces should be shared by classes that should respond to certain methods.
If classes have similar functionality, yet are not directly related to each other in an ancestral relationship, then an interface would be a good way to add that function to the classes without duplicating functionality between the two. (Or have multiple implementations with only subtle differences.)
While we're using a car analogy, a concrete example. Let's say we have the following classes:
Car -> Ford -> Escape -> EscapeHybrid
Car -> Toyota -> Corolla -> CorollaHybrid
Cars have wheels and can Drive() and Steer(). So those methods should exist in the Car class. (Probably the Car class will be an abstract class.)
Going down the line, we get the distinction between Ford and Toyota (probably implemented as difference in the type of emblem on the car, again probably an abstract class.)
Then, finally we have a Escape and Corolla class which are classes that are completely implemented as a car.
Now, how could we make a Hybrid vehicle?
We could have a subclass of Escape that is EscapeHybrid which adds a FordsHybridDrive() method, and a subclass of Corolla that is CorollaHybrid with ToyotasHybridDrive() method. The methods are basically doing the same thing, but yet we have different methods. Yuck. Seems like we can do better than that.
Let's say that a hybrid has a HybridDrive() method. Since we don't want to end up having two different types of hybrids (in a perfect world), so we can make an IHybrid interface which has a HybridDrive() method.
So, if we want to make an EscapeHybrid or CorollaHybrid class, all we have to do is to implement the IHybrid interface.
For a real world example, let's take a look at Java. A class which can do a comparison of an object with another object implements the Comparable interface. As the name implies, the interface should be for a class that is comparable, hence the name "Comparable".
Just as a matter of interest, a car example is used in the Interfaces lesson of the Java Tutorial.
You shouldn't implement any of those interfaces at all.
Class inheritance describes what an object is (eg: it's identity). This is fine, however most of the time what an object is, is far less important than what an object does. This is where interfaces come in.
An interface should describe what an object does), or what it acts like. By this I mean it's behavior, and the set of operations which make sense given that behaviour.
As such, good interface names should usually be of the form IDriveable, IHasWheels, and so on. Sometimes the best way to describe this behaviour is to reference a well-known other object, so you can say "acts like one of these" (eg: IList) but IMHO that form of naming is in the minority.
Given that logic, the scenarios where interface inheritance makes sense are completely and entirely different from the scenarios where object inheritance makes sense - often these scenarios don't relate to eachother at all.
Hope that helps you think through the interfaces you should actually need :-)
I'd say only make an interface for things you need to refer to. You may have some other classes or functions that need to know about a car, but how often will there be something that needs to know about a ford?
Don't build stuff you don't need. If it turns out you need the interfaces, it's a small effort to go back and build them.
Also, on the pedantic side, I hope you're not actually building something that looks like this hierarchy. This is not what inheritance should be used for.
Create it only once that level of functionality becomes necessary.
Re-factoring Code is always on on-going process.
There are tools available that will allow you to extract to interface if necessary.
E.G. http://geekswithblogs.net/JaySmith/archive/2008/02/27/refactor-visual-studio-extract-interface.aspx
Make an ICar and all the rest (Make=Ford, Model=Mustang, and stuff) as members of a class that implements the interface.
You might wanna have your Ford class and for example GM class and both implement ICar in order to use polymorphism if you don't wanna go down the route of checking Make == Whatever, that's up to your style.
Anyway - In my opinion those are attributes of a car not the other way around - you just need one interface because methods are common: Brake, SpeedUp, etc.
Can a Ford do stuff that other cars cannot? I don't think so.
I woudl create the first two levels, ICar and IFord and leave the second level alone until I need an interface at that second level.
Think carefully about how your objects need to interact with each other within your problem domain, and consider if you need to have more than one implementation of a particular abstract concept. Use Interfaces to provide a contract around a concept that other objects interact with.
In your example, I would suggest that Ford is probably a Manufacturer and Mustang is a ModelName Value used by the Manufacturer Ford, therefore you might have something more like:
IVehichle -> CarImpl, MotorbikeImpl - has-a Manufacturer has-many ModelNames
In this answer about the difference between interface and class, I explained that:
interface exposes what a concept is (in term of "what is" valid, at compilation time), and is used for values (MyInterface x = ...)
class exposes what a concept does (actually executed at runtime), and is used for values or for objects (MyClass x or aMyClass.method() )
So if you need to store into a 'Ford' variable (notion of 'value') different sub-classes of Ford, create an IFord. Otherwise, do not bother until you actually need it.
That is one criteria: if it is not met, IFord is probably useless.
If it is met, then the other criteria exposed in the previous answers apply: If a Ford has a richer API than a Car, an IFord is useful for polymorphisms purpose. If not, ICar is enough.
In my view interfaces are a tool to enforce a requirement that a class implement a certain signature, or (as I like to think of it) a certain "Behavior" To me I think if the Capital I at the beginning of my onterface names as a personal pronoun, and I try to name my interfaces so they can be read that way... ICanFly, IKnowHowToPersistMyself IAmDisplayable, etc... So in your example, I would not create an interface to Mirror the complete public signature of any specific class. I would analyze the public signature (the behavior) and then separate the members into smaller logical groups (the smaller the better) like (using your example) IMove, IUseFuel, ICarryPassengers, ISteerable, IAccelerate, IDepreciate, etc... And then apply those interfaces to whatever other classes in my system need them
In general, the best way to think about this (and many questions in OO) is to think about the notion of a contract.
A contract is defined as an agreement between two (or more) parties, that states specific obligations each party must meet; in a program, this is what services a class will provide, and what you have to provide the class in order to get the services. An interface states a contract that any class implementing the interface must satisfy.
With that in mind, though, your question somewhat depends on what language you're using and what you want to do.
After many years of doing OO (like, oh my god, 30 years) I would usually write an interface for every contract, especially in Java, because it makes tests so much easier: if I have an interface for the class, I can build mock objects easily, almost trivially.
Interfaces are intended to be a generic public API, and users will be restricted to using this public API. Unless you intend users to be using the type-specific methods of IMustangGT, you may want to limit the interface hierarchy to ICar and IExpensiveCar.
Only inherit from Interfaces and abstract classes.
If you have a couple of classes wich are almost the same, and you need to implement the majority of methods, use and Interface in combination with buying the other object.
If the Mustang classes are so different then not only create an interface ICar, but also IMustang.
So class Ford and Mustang can inherit from ICar, and Mustang and MustangGT from ICar and IMustang.
If you implement class Ford and a method is the same as Mustang, buy from Mustang:
class Ford{
public function Foo(){
...
Mustang mustang = new Mustang();
return mustang.Foo();
}