How do you code special cases for objects?
For example, let's say I'm coding an rpg - there are N = 5 classes. There are N^2 relationships in a matrix that would determine if character A could attack (or use ability M on) character B (ignoring other factors for now).
How would I code this up in OOP without putting special cases all over the place?
Another way to put it is, I have something maybe
ClassA CharacterA;
ClassB CharacterB;
if ( CharacterA can do things to CharacterB )
I'm not sure what goes inside that if statement, rather it be
if ( CharacterA.CanDo( CharacterB ) )
or a metaclass
if ( Board.CanDo( CharacterA, CharacterB ) )
when the CanDo function should depend on ClassA and ClassB, or attributes/modifiers with ClassA/ClassB?
i would start with a canSee(Monster monster) or canBeSeenBy(Monster monster) method and see what happens. you may end up with a Visibilility class or end up using the http://en.wikipedia.org/wiki/Visitor_pattern. an extreme example is uncle bobs triple dispatch:
// visitor with triple dispatch. from a post to comp.object by robert martin http://www.oma.com
/*
In this case, we are actually using a triple dispatch, because we have two
types to resolve. The first dispatch is the virtual Collides function which
resolves the type of the object upon which Collides is called. The second
dispatch is the virtual Accept function which resolves the type of the
object passed into Collides. Now that we know the type of both objects, we
can call the appropriate global function to calculate the collision. This
is done by the third and final dispatch to the Visit function.
*/
interface AbstractShape
{
boolean Collides(final AbstractShape shape);
void Accept(ShapeVisitor visitor);
}
interface ShapeVisitor
{
abstract public void Visit(Rectangle rectangle);
abstract public void Visit(Triangle triangle);
}
class Rectangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
RectangleVisitor visitor=new RectangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Rectangle
}
class Triangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
TriangleVisitor visitor=new TriangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Triangle
}
class collision
{ // first dispatch
static boolean Collides(final Triangle t,final Triangle t2) { return true; }
static boolean Collides(final Rectangle r,final Triangle t) { return true; }
static boolean Collides(final Rectangle r,final Rectangle r2) { return true; }
}
// visitors.
class TriangleVisitor implements ShapeVisitor
{
TriangleVisitor(final Triangle triangle)
{ this.triangle=triangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,triangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(triangle,this.triangle); }
boolean result() {return result; }
private boolean result=false;
private final Triangle triangle;
}
class RectangleVisitor implements ShapeVisitor
{
RectangleVisitor(final Rectangle rectangle)
{ this.rectangle=rectangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,this.rectangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(rectangle,triangle); }
boolean result() {return result; }
private boolean result=false;
private final Rectangle rectangle;
}
public class MartinsVisitor
{
public static void main (String[] args)
{
Rectangle rectangle=new Rectangle();
ShapeVisitor visitor=new RectangleVisitor(rectangle);
AbstractShape shape=new Triangle();
shape.Accept(visitor);
}
}
Steve Yegge has an awesome blog post about the Properties pattern that you could use handle this. In fact, he wrote an RPG using it!
http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html
You might say player1 is a type1 and type1s can attack type2s and player2 is a type2, so unless there is some "override" on the specific player1, player1 can attack player2.
This enables very robust and extensible behavior.
What is the definition of "see"? If they occupy the same square? If so, this will be answered in how you implement collision detection (or whatever in this case) rather then OOP relationships between characters. Without knowing more information, I would approach the problem in this manner (in C++/pseudo code for illustration):
class Character {
private:
matrixSquare placement;
public:
Character() {};
~Character {};
matrixSquare getLocation() { return placement;};
};
class GameBoard {
private:
//your 5 x 5 matrix here
public:
GameBoard() {};
~GameBoard() {};
boolean isOccupied(matrixSquare)
{
if (occupied)
{
//do something
return true;
}
else
{
return false;
}
}
};
The trick here is to define the relationship between your character pieces and your implementation of the playing field. After that is established you could then clarify how you determine if two characters are in the same square, adjoining squares, etc... Hope that helps.
I would say use design patterns, generally I think Observer, Mediator and Visitor patterns are quite good for managing complex inter-object relationships.
I would (assuming C++) give each class a std::string identifier, returned by a getter method on the class's instance, and use a std::map< std::pair<std::string, std::string>, ... > to encode the special cases of relationship between classes, all nice and ordered in one place. I'd also access that map exclusively through a getter function so that changing the strategy for encoding some or all of the special cases is made easy as pie. E.g.: if only a few pairs of classes out of the 25 have the "invisibility" property, the map in that case might contain only the few exceptions that do have that property (for a boolean property like this a std::set might actually be a preferable implementation, in C+_).
Some OO languages have multi-dispatch (Common Lisp and Dylan are the two that come to mind at the moment), but for all the (vast majority) of languages that lack it, this is a good approach (in some cases you'll find that a centralized map / dict is restrictive and refactor to a Dynamic Visitor design pattern or the like, but thanks to the "getter function" such refactorings will be pretty transparent to all the rest of your code).
In response to your edit of your question, you'll want to look into polymorphism. I personally would have the cando() function be a part of the Board, then, depending on the two classes passed in, the Board would call the appropriate function and return the result (of battle, of seeing, so on and so forth).
If you're doing this in java an enum/interface to go along with your Game Board would be a very clean way of approaching this problem.
I suggest you look at double dispatch pattern.
http://c2.com/cgi/wiki?DoubleDispatchExample
The above example explains how a group of printers can print a group of shapes.
http://en.wikipedia.org/wiki/Double_dispatch
The wikipedia example specifically mentions solving adaptive collision problems with this pattern.
Related
Here's a bare minimum pseodo-code of what I use:
class A{
//other variables
B b;
void delayedPartnerInit(B b){
this.b=b;
}
}
class B{
//some other variables
A a;
void delayedPartnerInit(A a){
this.a=a;
}
}
I could make it into a single class but certain members(not shown here) of A are needed to exist before data about B. In other words, objects of A and B are instanced at different times but need reference of each other's variables once both set of variables are available.
The question is there a better way to do this? Am I missing some basic concept of programming?
Though I am currently working on C#, I have had this thought many times before when working with other languages too.
Update: I am using this in Unity game engine where B is Unity C# script. Since Unity doesn't allow us create scripts without adding it to something I need 2 classes. I get certain data(A's data) earliar which needs processing.
Didn't mention this earlier because I asked it as a generic question.
Note before closing as duplicate: I checked similar questions but found only specific questions that caused issues to authors who tried to do what I am doing. My question is whether it is a bad practice.
Tightly coupled classes are generally bad practice:
Changes in one class lead to changes in another.
You cannot test one of classes without creating (or mocking) another one. Which in your case creates circular dependency.
Both classes depend on each other's implementations, not abstractions.
Harder for other persons (or yourself half a year later) to understand and reason about first class logic without inspecting second class as well.
Since Unity doesn't allow us create scripts without adding it to something I need 2 classes. I get certain data(A's data) earliar which needs processing
MVC pattern for Unity provides useful trick for decoupling monobehaviours:
interface ISomeObjectView {
event Action OnUpdate;
event Action Destroyed;
event Action TriggerEntered;
void SetTransform(Vector3 position, Quaternion rotation);
void AddForce(Vector3 force);
// Other methods or events you need to expose:
// MouseOver, OnFixedUpdate, Move() or SetScale(), ...
}
MonoBehaviour itself does not contain any logic, it simply invokes events and uses incoming values:
public void SetTransform(Vector3 position, Quaternion rotation)
{
// Params validation
transform.rotation = rotation;
transform.position = position;
}
private void Update()
=> OnUpdate?.Invoke();
MonoBehaviour logic must be moved to your data class or new controller class. Now your data class simply links itself to provided interface events and methods without circular dependencies. Monobehaviour does not require any references to other classes, it simply provides methods to manipulate itself and events to catch input.
This trick helps in several ways:
MonoBehaviour doesn't depend on anything and doesn't require any references to other classes.
Your data/logic classes doesn't require ant special knowledge about monobehaviours, only provided interface.
You can have several implementations for interface, switching different views depending on situation.
Easy to test, easy to mock.
You can move all the "Unity stuff" inside MonoBehaviour and write all related classes on pure C#. If you want to.
Please note that using event Action is not conventional way to deal with events! I think it's very convenient, but I'd suggest to use conventional EventHandler (UnityEvents is another option that might suit your needs).
Update: an example of simple MVC.
Consider the following Player controller:
[Serializable]
public class PlayerInfo {
// Values configurable via inspector
[SerializeField] private float speed = 1.5f;
[SerializeField] private float jumpHeight = 5;
[SerializeField] private float damage = 15;
[SerializeField] private Player playerPrefab;
public float Speed => speed;
public float JumpHeight => jumpHeight ;
public float Damage => damage;
private Player playerInstance;
public void InitializePlayer() {
playerInstance = Instantiate(playerPrefab);
playerInstance.Info = this;
}
public void TeleportTo(Vector3 newPosition) {
playerInstance.transform.position = newPosition;
}
}
public class Player : MonoBehaviour {
public PlayerInfo Info { get; set; }
private Rigidbody rb;
private void Awake() {
rb = GetComponent<Rigidbody>();
}
private void Update() {
if (Input.GetButtonDown("Jump")
rb.AddForce(Vector3.up * info.JumpHeight);
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
rb.AddForce(movement * info.Speed);
}
private void OnTriggerEnter(Collider other) {
var enemy = other.GetComponent<Enemy>();
if (enemy != null)
enemy.TakeHit(info.Damage);
}
}
There you go. PlayerInfo is created before Player. PlayerInfo references Player and Player references PlayerInfo. Player is used to move gameobject and attack enemies, PlayerInfo contains required info. What can we do here?
First, Rewrite MonoBehaviour without any logic:
public class PlayerView : MonoBehaviour {
private Rigidbody rb;
// Events for future subscription.
public event Action OnUpdate;
public event TriggerEntered<Collider>;
// Simple initialization of required components.
private void Awake() {
rb = GetComponent<Rigidbody>();
}
// Unity methods doing nothing but invoking events.
private void Update() {
OnUpdate?.Invoke();
}
private void OnTriggerEnter(Collider other) {
TriggerEntered?.Invoke(other);
}
// We still need a method to move our player, right?
public void Move(Vector3 direction) {
rb.AddForce(direction);
}
public void SetPosition(Vector3 position) {
transform.position = position;
}
}
Now you need class containing data about player:
[Serializable]
public class PlayerModel {
[SerializeField] private float speed = 1.5f;
[SerializeField] private float jumpHeight = 5;
[SerializeField] private float damage = 15;
public float Speed => speed;
public float JumpHeight => jumpHeight ;
public float Damage => damage;
}
Now we need a way to tie those two together:
public class PlayerController {
private readonly PlayerModel model;
private readonly PlayerView view;
public PlayerController(PlayerModel model, PlayerView view) {
// Validate values here.
this.model = model;
this.view = view;
// Linking logic to events.
view.OnUpdate += Move;
view.TriggerEntered += Attack;
}
// Actual logic moved here.
private void Move() {
Vector3 movement = Vector3.zero;
if (Input.GetButtonDown("Jump")
movement += Vector3.up * model.JumpHeight;
movement += new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * model.Speed;
view.Move(movement);
}
private void Attack(Collider other) {
var enemy = other.GetComponent<Enemy>();
if (enemy != null)
enemy.TakeHit(model.Damage);
}
// Method from PlayerInfo to set player position without actual movements.
public void MoveTo(Vector3 position) {
view.SetPosition(position);
}
}
Now you have 3 classes instead of 2, but model and view classes are very simple and do not require any dependencies. All the work is done by Controller class, which receives other two pieces and ties them together.
It becomes even better when interfaces are introduced in addition to classes: IPlayerModel, IPlayerView, IPlayerController.
You might think that it would be easier to create single class instead of three linked classes, but in the long run you will thank yourself for using this pattern: view and model are extremely simple, easy to read, easy to check for errors, easy to expand with new functionality. Single class, on the other hand, will quickly grow to hundreds of lines and become a nightmare to test and expand.
I strongly recommend this article with more complicated examples of MVC.
This is a follow-up question to the answer given by #Peter Meyer given in this question (What does it mean to "program to an interface"?).
First, let me begin by saying I am loath to make this a new question. But (I love stackoverflow but I must be a little critical here) 1) I could not privately message Peter Meyer (read: https://meta.stackexchange.com/questions/93896/a-proposal-for-private-messaging-within-the-stack-exchange-network), 2) I could not post a 'follow-up' question (read: https://meta.stackexchange.com/questions/10243/asking-a-follow-up-question) and 3), the question was locked to avoid "explosion pills" and, alas, I do not have enough reputation to ask there.
So, I must post a new question.
In that thread, Peter Meyer showed a brilliant and funny example of when to use interfaces and why programming to interfaces is important.
My question is this: wouldn't using a wrapper class be another approach to solving his problem?
Couldn't you write:
interface IPest {
void BeAnnoying();
}
class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead();
void LandOnThings();
void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}
class Telemarketer inherits Person implements IPest {
void CallDuringDinner();
void ContinueTalkingWhenYouSayNo();
void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}
class DiningRoom {
DiningRoom(Person[] diningPeople, IPest[] pests) { ... }
void ServeDinner() {
when diningPeople are eating,
foreach pest in pests
pest.BeAnnoying();
}
}
in this way:
class IPest {
HouseFly houseFly;
public IPest(HouseFly houseFly) {
this.houseFly = houseFly;
}
Telemarketer telemarketer;
public IPest(Telemarketer telemarketer) {
this.telemarketer = telemarketer;
}
void BeAnnoying() {
if(houseFly != null)
houseFly.BeAnnoying();
else
telemarketer.BeAnnoying();
}
}
class HouseFly inherits Insect {
void FlyAroundYourHead();
void LandOnThings();
void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}
class Telemarketer inherits Person {
void CallDuringDinner();
void ContinueTalkingWhenYouSayNo();
void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}
class DiningRoom {
DiningRoom(Person[] diningPeople, IPest[] pests) { ... }
void ServeDinner() {
when diningPeople are eating,
foreach pest in pests
pest.BeAnnoying();
}
}
?
Although I tagged this as language-agnostic, I'm really "Java-ifying" this question because that is what I'm most familiar with, so please forgive me. But as I see it, there is disadvantage to using the interface approach. For instance, if you want to override the "toString()" method for the different types, to return a different value based on whether it's being represented as an "IPest" or a "HouseFly," with the interface you cannot do that. You can't give a different toString value for "HouseFly" by itself than you would for a HouseFly implementing the IPest interface with the interface (because HouseFly will always implement the interface by the class definition). A wrapper class would give you broader functionality than the interface would.
To illustrate: Let's say you wanted to display all of the "IPests" in a list, but you wanted the list to have a distinguishing mark on each one to display whether the pest was a Fly or a Telemarketer. Then with the wrapper class, this would be easy:
class IPest {
HouseFly houseFly;
public IPest(HouseFly houseFly) {
this.houseFly = houseFly;
}
Telemarketer telemarketer;
public IPest(Telemarketer telemarketer) {
this.telemarketer = telemarketer;
}
void BeAnnoying() {
if(houseFly != null)
houseFly.BeAnnoying();
else
telemarketer.BeAnnoying();
}
public String toString() {
return (houseFly == null? "(T) " + telemarketer.toString() : "(F) " + houseFly.toString()) +
}
}
Then, in another place, if you had a list to represent the HouseFly by itself (not as an IPest but as a HouseFly) then you could give a different value for toString().
This isn't limited to toString(), but any other method that those classes may have that you might want to override to provide different functionality when the object is being represented as a IPest vs when it is being represented as a HouseFly or Telemarketer.
I hope my question makes sense.
My theory is that: if you are programming an API or anything that anyone will use, you should avoid concrete classes and try to use interfaces. But if you are writing client code directly and have zero expectation (or possibility) of code reuse then "programming to interface" seems like a not-so-big-deal.
I'm looking forward to any feedback. Am I way off-base here? Am I terrible at writing code? Hopefully Peter Meyer will give his input...
To me, this is making the code a lot uglier for no obvious benefit. (That reads kind of harshly, which is not how I intend it...+1 for the actual question).
The big downside is your IPest class. As you continue to add possible pests, this class grows enormous and bloated with unused variables and code. If you have 30 different kinds of pests, then your IPest class has grown 15 times as large than your example with 2 kinds, with lots of extra code to support all of these classes.
Worse, the great majority of this code isn't actually relevant to the instantiated object. If the IPest is supposed to represent a HouseFly, then there are several instance variables (one for each other type of IPest) that are all empty, and a ton of unused code. Worse, what happens if IPest has more than one of its values not null? What is it? (BrundleFly the Telemarketer!)
Compare this with the pure interface, which grows no larger as more classes implement it (because it doesn't care.)
Finally, I don't think it's generally useful (or a good idea) to have a single conceptual idea (such as a single fly) represented by two (or more) objects such a HouseFly object and a IPest object...and more objects as you want to add more functionality. For each of your wrappers, you add another object, which is another object to potentially keep track of and update.
This isn't to say there couldn't be some very specialized case where something like this wouldn't be a good idea...but I'm not seeing it here, for the reasons I describe above.
I'm trying to think of how to solve this problem correctly using object-oriented methods. The language isn't important—I would actually like to write code, but it's more the general principles I care about.
I want to implement a field: a collection of 'numbers' on which the operations +, -, *, and / operate. Further, I would like to be able to implement higher operations like ^ and cycle-finding which (1) do not need to be defined for a given field but which (2) can be overridden if desired, say for efficiency reasons.
Here's the catch. It's not good enough to declare
FieldElement power (FieldElement base, FieldElement exponent)
because I want type safety: it should not be possible to add, say, a member of a finite field to an integer.
Perhaps what I'm really looking for is a meta-object, or super-interface, or something that ties together different classes (one for integers, one for 7-adics, one for the finite field F_4, etc.). Or maybe there's something better.
N.B. Code is welcome (even encouraged) in answers, if it would be enlightening, but declarations are probably enough: presumably everyone here could write out the obvious methods for at least a few fields.
I'll mention other conditions which matter to me but are (apparently) unrelated to the main OO issue: I don't want field elements to carry their type information around, and further I want them to be lightweight (since I may need to deal with large arrays of field elements). These desiderata may not be achievable—though frankly I'm more likely to abandon OO here than efficiency. But an answer would be appreciated regardless, since I'm interested in learning about these issues even apart from the particular problem at hand.
This is called the binary method problem. Quick googling will reveal some (lots of) information. In particular, the article "On binary methods" by Luca Cardelli et al gives the subject a thorough treatment.
You may want to learn some Haskell to see how a practical programming language deals with this problem.
EDIT Loluca → Luca. Damn the tiny phone screen and its tinier keyboard ;)
I have tried to express these concepts in C# before, but I have encountered language barriers: language is not rich enough, or specific enough. For example, if I define an Element of a Field like this:
public abstract class FieldElement
{
public abstract FieldElement Add(FieldElement another);
public abstract FieldElement SumInvert();
public abstract FieldElement MultiplicationInvert();
public abstract FieldElement MultiplyBy(FieldElement another);
public abstract FieldElement One; //Multiplication neutral element
public abstract FieldElement Zero; //Addition neutral element
public FieldElement Subtract(FieldElement another)
{
return this.Add(another.SumInvert());
}
public FieldElement Divide(FieldElement another)
{
return this.MultiplyBy(another.MultiplicationInvert());
}
public virtual FieldElement Power(uint b)
{
if (b == 0)
return this.One;
else
{
FieldElement result = this;
for (int i = 0; i < b - 1; i++)
result = result.MultiplyBy(result);
return result;
}
}
}
Then I define Real Numbers like this:
public class RealNumber : FieldElement
{
public double Value { get; set; }
public RealNumber(double value)
{
this.Value = value;
}
public override FieldElement Power(uint b)
{
return new RealNumber(Math.Pow(Value, b));
}
public override FieldElement Add(FieldElement another)
{
if (another.GetType() != typeof(RealNumber)) //Ugly typecast to enforce type-safety
throw new ArgumentException("RealNumber expected in Add method");
return new RealNumber(Value + (another as RealNumber).Value);
}
}
I can then define generically operations on Field Elements (by using generics):
public class FieldOperations<T> where T: FieldElement
{
public T Add(T a, T b)
{
return a.Add(b) as T;
}
public T Multiply(T a, T b)
{
return a.MultiplyBy(b) as T;
}
public T Subtract(T a, T b)
{
return a.Subtract(b) as T;
}
public T Divide(T a, T b)
{
return a.Divide(b) as T;
}
public T Power(T a, uint b)
{
return a.Power(b) as T;
}
}
And I will use it like this in code:
public class TestFieldOperations
{
public static void TestAddRealNumbers()
{
FieldOperations<RealNumber> operations = new FieldOperations<RealNumber>();
RealNumber a = new RealNumber(0.5);
RealNumber b = new RealNumber(0.7);
RealNumber c = operations.Add(a, b);
RealNumber d = operations.Power(c, 3);
}
}
Similarly, I could have FieldOperations on Vectors, FieldOperations on InvMatrix...
Being able to abstract the concept of Field operations in a type-safe and object-oriented way can be very powerful: being able to deal with numbers, vectors and (invertible) matrices arithmetic at the same level of abstraction.
Referring to the below link:
http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html?page=2
The composition approach to code reuse provides stronger encapsulation
than inheritance, because a change to a back-end class needn't break
any code that relies only on the front-end class. For example,
changing the return type of Fruit's peel() method from the previous
example doesn't force a change in Apple's interface and therefore
needn't break Example2's code.
Surely if you change the return type of peel() (see code below) this means getPeelCount() wouldn't be able to return an int any more? Wouldn't you have to change the interface, or get a compiler error otherwise?
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
With a composition, changing the class Fruit doesn't necessary require you to change Apple, for example, let's change peel to return a double instead :
class Fruit {
// Return String number of pieces of peel that
// resulted from the peeling activity.
public double peel() {
System.out.println("Peeling is appealing.");
return 1.0;
}
}
Now, the class Apple will warn about a lost of precision, but your Example2 class will be just fine, because a composition is more "loose" and a change in a composed element does not break the composing class API. In our case example, just change Apple like so :
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return (int) fruit.peel();
}
}
Whereas if Apple inherited from Fruit (class Apple extends Fruit), you would not only get an error about an incompatible return type method, but you'd also get a compilation error in Example2.
** Edit **
Lets start this over and give a "real world" example of composition vs inheritance. Note that a composition is not limited to this example and there are more use case where you can use the pattern.
Example 1 : inheritance
An application draw shapes into a canvas. The application does not need to know which shapes it has to draw and the implementation lies in the concrete class inheriting the abstract class or interface. However, the application knows what and how many different concrete shapes it can create, thus adding or removing concrete shapes requires some refactoring in the application.
interface Shape {
public void draw(Graphics g);
}
class Box implement Shape {
...
public void draw(Graphics g) { ... }
}
class Ellipse implements Shape {
...
public void draw(Graphics g) { ... }
}
class ShapeCanvas extends JPanel {
private List<Shape> shapes;
...
protected void paintComponent(Graphics g) {
for (Shape s : shapes) { s.draw(g); }
}
}
Example 2 : Composition
An application is using a native library to process some data. The actual library implementation may or may not be known, and may or may not change in the future. A public interface is thus created and the actual implementation is determined at run-time. For example :
interface DataProcessorAdapter {
...
public Result process(Data data);
}
class DataProcessor {
private DataProcessorAdapter adapter;
public DataProcessor() {
try {
adapter = DataProcessorManager.createAdapter();
} catch (Exception e) {
throw new RuntimeException("Could not load processor adapter");
}
}
public Object process(Object data) {
return adapter.process(data);
}
}
static class DataProcessorManager {
static public DataProcessorAdapter createAdapter() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String adapterClassName = /* load class name from resource bundle */;
Class<?> adapterClass = Class.forName(adapterClassName);
DataProcessorAdapter adapter = (DataProcessorAdapter) adapterClass.newInstance();
//...
return adapter;
}
}
So, as you can see, the composition may offer some advantage over inheritance in the sense that it allows more flexibility in the code. It allows the application to have a solid API while the underlaying implementation may still change during it's life cycle. Composition can significantly reduce the cost of maintenance if properly used.
For example, when implementing test cases with JUnit for Exemple 2, you may want to use a dummy processor and would setup the DataProcessorManager to return such adapter, while using a "real" adapter (perhaps OS dependent) in production without changing the application source code. Using inheritance, you would most likely hack something up, or perhaps write a lot more initialization test code.
As you can see, compisition and inheritance differ in many aspects and are not preferred over another; each depend on the problem at hand. You could even mix inheritance and composition, for example :
static interface IShape {
public void draw(Graphics g);
}
static class Shape implements IShape {
private IShape shape;
public Shape(Class<? extends IShape> shape) throws InstantiationException, IllegalAccessException {
this.shape = (IShape) shape.newInstance();
}
public void draw(Graphics g) {
System.out.print("Drawing shape : ");
shape.draw(g);
}
}
static class Box implements IShape {
#Override
public void draw(Graphics g) {
System.out.println("Box");
}
}
static class Ellipse implements IShape {
#Override
public void draw(Graphics g) {
System.out.println("Ellipse");
}
}
static public void main(String...args) throws InstantiationException, IllegalAccessException {
IShape box = new Shape(Box.class);
IShape ellipse = new Shape(Ellipse.class);
box.draw(null);
ellipse.draw(null);
}
Granted, this last example is not clean (meaning, avoid it), but it shows how composition can be used.
Bottom line is that both examples, DataProcessor and Shape are "solid" classes, and their API should not change. However, the adapter classes may change and if they do, these changes should only affect their composing container, thus limit the maintenance to only these classes and not the entire application, as opposed to Example 1 where any change require more changes throughout the application. It all depends how flexible your application needs to be.
If you would change Fruit.peel()'s return type, you would have to modify Apple.peel() as well. But you don't have to change Apple's interface.
Remember: The interface are only the method names and their signatures, NOT the implementation.
Say you'd change Fruit.peel() to return a boolean instead of a int. Then, you could still let Apple.peel() return an int. So: The interface of Apple stays the same but Fruit's changed.
If you would have use inheritance, that would not be possible: Since Fruit.peel() now returns a boolean, Apple.peel() has to return an boolean, too. So: All code that uses Apple.peel() has to be changed, too. In the composition example, ONLY Apple.peel()'s code has to be changed.
The key word in the sentence is "interface".
You'll almost always need to change the Apple class in some way to accomodate the new return type of Fruit.peel, but you don't need to change its public interface if you use composition rather than inheritance.
If Apple is a Fruit (ie, inheritance) then any change to the public interface of Fruit necessitates a change to the public interface of Apple too. If Apple has a Fruit (ie, composition) then you get to decide how to accomodate any changes to the Fruit class; you're not forced to change your public interface if you don't want to.
Return type of Fruit.peel() is being changed from int to Peel. This doesn't meant that the return type of Apple.peel() is being forced to change to Peel as well. In case of inheritance, it is forced and any client using Apple has to be changed. In case of composition, Apple.peel() still returns an integer, by calling the Peel.getPeelCount() getter and hence the client need not be changed and hence Apple's interface is not changed ( or being forced to be changed)
Well, in the composition case, Apple.peel()'s implementation needs to be updated, but its method signature can stay the same. And that means the client code (which uses Apple) does not have to be modified, retested, and redeployed.
This is in contrast to inheritance, where a change in Fruit.peel()'s method signature would require changes all way into the client code.
I am new to OOP. Though I understand what polymorphism is, but I can't get the real use of it. I can have functions with different name. Why should I try to implement polymorphism in my application.
Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.
Have a look at this code:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual float GetArea() = 0;
};
class Rectangle : public Shape
{
public:
Rectangle(float a) { this->a = a; }
float GetArea() { return a * a; }
private:
float a;
};
class Circle : public Shape
{
public:
Circle(float r) { this->r = r; }
float GetArea() { return 3.14f * r * r; }
private:
float r;
};
int main()
{
Shape *a = new Circle(1.0f);
Shape *b = new Rectangle(1.0f);
cout << a->GetArea() << endl;
cout << b->GetArea() << endl;
}
An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.
Have fun learning!
Have you ever added two integers with +, and then later added an integer to a floating-point number with +?
Have you ever logged x.toString() to help you debug something?
I think you probably already appreciate polymorphism, just without knowing the name.
In a strictly typed language, polymorphism is important in order to have a list/collection/array of objects of different types. This is because lists/arrays are themselves typed to contain only objects of the correct type.
Imagine for example we have the following:
// the following is pseudocode M'kay:
class apple;
class banana;
class kitchenKnife;
apple foo;
banana bar;
kitchenKnife bat;
apple *shoppingList = [foo, bar, bat]; // this is illegal because bar and bat is
// not of type apple.
To solve this:
class groceries;
class apple inherits groceries;
class banana inherits groceries;
class kitchenKnife inherits groceries;
apple foo;
banana bar;
kitchenKnife bat;
groceries *shoppingList = [foo, bar, bat]; // this is OK
Also it makes processing the list of items more straightforward. Say for example all groceries implements the method price(), processing this is easy:
int total = 0;
foreach (item in shoppingList) {
total += item.price();
}
These two features are the core of what polymorphism does.
Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method.
Take look at the following example.
Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.
class CarBase
{
public virtual void ProduceCar()
{
Console.WriteLine("don't know how to produce");
}
}
class CarToyota : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Toyota Car ");
}
}
class CarBmw : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Bmw Car");
}
}
class CarUnknown : CarBase { }
class CarBuilder
{
public List<CarBase> CarsToProduceList { get; set; }
public void ProduceCars()
{
if (null != CarsToProduceList)
{
foreach (CarBase car in CarsToProduceList)
{
car.ProduceCar();// doesn't know how to produce
}
}
}
}
class Program
{
static void Main(string[] args)
{
CarBuilder carbuilder = new CarBuilder();
carbuilder.CarsToProduceList = new List<CarBase>() { new CarBmw(), new CarToyota(), new CarUnknown() };
carbuilder.ProduceCars();
}
}
Polymorphism is the foundation of Object Oriented Programming. It means that one object can be have as another project. So how does on object can become other, its possible through following
Inheritance
Overriding/Implementing parent Class behavior
Runtime Object binding
One of the main advantage of it is switch implementations. Lets say you are coding an application which needs to talk to a database. And you happen to define a class which does this database operation for you and its expected to do certain operations such as Add, Delete, Modify. You know that database can be implemented in many ways, it could be talking to file system or a RDBM server such as MySQL etc. So you as programmer, would define an interface that you could use, such as...
public interface DBOperation {
public void addEmployee(Employee newEmployee);
public void modifyEmployee(int id, Employee newInfo);
public void deleteEmployee(int id);
}
Now you may have multiple implementations, lets say we have one for RDBMS and other for direct file-system
public class DBOperation_RDBMS implements DBOperation
// implements DBOperation above stating that you intend to implement all
// methods in DBOperation
public void addEmployee(Employee newEmployee) {
// here I would get JDBC (Java's Interface to RDBMS) handle
// add an entry into database table.
}
public void modifyEmployee(int id, Employee newInfo) {
// here I use JDBC handle to modify employee, and id to index to employee
}
public void deleteEmployee(int id) {
// here I would use JDBC handle to delete an entry
}
}
Lets have File System database implementation
public class DBOperation_FileSystem implements DBOperation
public void addEmployee(Employee newEmployee) {
// here I would Create a file and add a Employee record in to it
}
public void modifyEmployee(int id, Employee newInfo) {
// here I would open file, search for record and change values
}
public void deleteEmployee(int id) {
// here I search entry by id, and delete the record
}
}
Lets see how main can switch between the two
public class Main {
public static void main(String[] args) throws Exception {
Employee emp = new Employee();
... set employee information
DBOperation dboper = null;
// declare your db operation object, not there is no instance
// associated with it
if(args[0].equals("use_rdbms")) {
dboper = new DBOperation_RDBMS();
// here conditionally, i.e when first argument to program is
// use_rdbms, we instantiate RDBM implementation and associate
// with variable dboper, which delcared as DBOperation.
// this is where runtime binding of polymorphism kicks in
// JVM is allowing this assignment because DBOperation_RDBMS
// has a "is a" relationship with DBOperation.
} else if(args[0].equals("use_fs")) {
dboper = new DBOperation_FileSystem();
// similarly here conditionally we assign a different instance.
} else {
throw new RuntimeException("Dont know which implemnation to use");
}
dboper.addEmployee(emp);
// now dboper is refering to one of the implementation
// based on the if conditions above
// by this point JVM knows dboper variable is associated with
// 'a' implemenation, and it will call appropriate method
}
}
You can use polymorphism concept in many places, one praticle example would be: lets you are writing image decorer, and you need to support the whole bunch of images such as jpg, tif, png etc. So your application will define an interface and work on it directly. And you would have some runtime binding of various implementations for each of jpg, tif, pgn etc.
One other important use is, if you are using java, most of the time you would work on List interface, so that you can use ArrayList today or some other interface as your application grows or its needs change.
Polymorphism allows you to write code that uses objects. You can then later create new classes that your existing code can use with no modification.
For example, suppose you have a function Lib2Groc(vehicle) that directs a vehicle from the library to the grocery store. It needs to tell vehicles to turn left, so it can call TurnLeft() on the vehicle object among other things. Then if someone later invents a new vehicle, like a hovercraft, it can be used by Lib2Groc with no modification.
I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.
So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.
You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.
One of the most significant benefit that you get from polymorphic operations is ability to expand.
You can use same operations and not changing existing interfaces and implementations only because you faced necessity for some new stuff.
All that we want from polymorphism - is simplify our design decision and make our design more extensible and elegant.
You should also draw attention to Open-Closed Principle (http://en.wikipedia.org/wiki/Open/closed_principle) and for SOLID (http://en.wikipedia.org/wiki/Solid_%28Object_Oriented_Design%29) that can help you to understand key OO principles.
P.S. I think you are talking about "Dynamic polymorphism" (http://en.wikipedia.org/wiki/Dynamic_polymorphism), because there are such thing like "Static polymorphism" (http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism).
You don't need polymorphism.
Until you do.
Then its friggen awesome.
Simple answer that you'll deal with lots of times:
Somebody needs to go through a collection of stuff. Let's say they ask for a collection of type MySpecializedCollectionOfAwesome. But you've been dealing with your instances of Awesome as List. So, now, you're going to have to create an instance of MSCOA and fill it with every instance of Awesome you have in your List<T>. Big pain in the butt, right?
Well, if they asked for an IEnumerable<Awesome>, you could hand them one of MANY collections of Awesome. You could hand them an array (Awesome[]) or a List (List<Awesome>) or an observable collection of Awesome or ANYTHING ELSE you keep your Awesome in that implements IEnumerable<T>.
The power of polymorphism lets you be type safe, yet be flexible enough that you can use an instance many many different ways without creating tons of code that specifically handles this type or that type.
Tabbed Applications
A good application to me is generic buttons (for all tabs) within a tabbed-application - even the browser we are using it is implementing Polymorphism as it doesn't know the tab we are using at the compile-time (within the code in other words). Its always determined at the Run-time (right now! when we are using the browser.)