Best Practices for this TDD attempt - testing

I code for about 12 years, but I've never get used to TDD in all this time.
Well, things are about to change, but since I'm learning all by myself, I hope you guys could help me.
I'm posting a game example for a VERY SIMPLE chest class.
When the player grabs a chest, it registers the current time it was obtained.
This chest takes some time to open so, I need, for UI reasons, to show the remaining time it takes to open.
Each chest has a type, and this type is bound to a database value of how much time it would take to open.
This is a "no-testing-just-get-things-done-fast-mindset". Consider that ChestsDatabase and DateManager are singletons containing the database-bound values and the current system time wrapped into a class.
public class Chest {
private readonly int _type;
private readonly float _timeObtained;
public Chest(int type, float timeObtained) {
_type = type;
_timeObtained = timeObtained;
}
public bool IsOpened() {
return GetRemainingTime() <= 0;
}
// It depends heavily on this concrete Singleton class
public float GetRemainingTime() {
return ChestsDatabase.Instance.GetTimeToOpen(_type) - GetPassedTime();
}
// It depends heavily on this concrete Singleton class
private float GetPassedTime() {
return DateManager.Instance.GetCurrentTime() - _timeObtained;
}
}
Of course, I could have made it in a Dependency Injection fashion and get rid of the singletons:
public class Chest {
private readonly ChestsDatabase _chestsDatabase;
private readonly DateManager _dateManager;
private readonly int _type;
private readonly float _timeObtained;
public Chest(ChestsDatabase chestsDatabase, DateManager dateManager, int type, float timeObtained) {
_chestsDatabase = chestsDatabase;
_dateManager = dateManager;
_type = type;
_timeObtained = timeObtained;
}
public bool IsOpened() {
return GetRemainingTime() <= 0;
}
public float GetRemainingTime() {
return _chestsDatabase.GetTimeToOpen(_type) - GetPassedTime();
}
private float GetPassedTime() {
return _dateManager.GetCurrentTime() - _timeObtained;
}
}
What if I use interfaces to express the same logic? This is going to be much more "TDD-friendly", right? (supposing that I've done the tests first, of course)
public class Chest {
private readonly IChestsDatabase _chestsDatabase;
private readonly IDateManager _dateManager;
private readonly int _type;
private readonly float _timeObtained;
public Chest(IChestsDatabase chestsDatabase, IDateManager dateManager, int type, float timeObtained) {
_chestsDatabase = chestsDatabase;
_dateManager = dateManager;
_type = type;
_timeObtained = timeObtained;
}
public bool IsOpened() {
return GetRemainingTime() <= 0;
}
public float GetRemainingTime() {
return _chestsDatabase.GetTimeToOpen(_type) - GetPassedTime();
}
private float GetPassedTime() {
return _dateManager.GetCurrentTime() - _timeObtained;
}
}
But how the hell am I supposed to test something like that?
Would it be like this?
[Test]
public void SomeTimeHavePassedAndReturnsRightValue()
{
var mockDatabase = new MockChestDatabase();
mockDatabase.ForType(0, 5); // if Type is 0, then takes 5 seconds to open
var mockManager = new MockDateManager();
var chest = new Chest(mockDatabase, mockManager, 0, 6); // Got a type 0 chest at second 6
mockManager.SetCurrentTime(8); // Now it is second 8
Assert.AreEqual(3, chest.GetRemainingTime()); // Got the chest at second 6, now it is second 8, so it passed 2 seconds. We need 5 seconds to open this chest, so the remainingTime is 3
}
Is this logically right? Am I missing something? Because this seems so big, so convoluted, so... wrong. I had to create 2 extra classes ~just~ for the purpose of these tests.
Let's see with a mocking framework:
[Test]
public void SomeTimeHavePassedAndReturnsRightValue()
{
var mockDatabase = Substitute.For<IChestsDatabase>();
mockDatabase.GetTimeToOpen(0).Returns(5);
var mockManager = Substitute.For<IDateManager>();
var chest = new Chest(mockDatabase, mockManager, 0, 6);
mockManager.GetCurrentTime().Returns(8);
Assert.AreEqual(3, chest.GetRemainingTime());
}
I got rid of two classes with the framework, but still, I feel there's something wrong. Is there a simpler way in my logic? In this single case, would you use a mocking framework or implemented classes?
Would you guys get rid of the tests altogether or would you insist in any of my solutions? Or how to make this solution better?
Hope you can help me in my TDD journey. Thanks.

For your current design your last attempt is logically right and close to what I would consider an optimal test case.
I recommend extracting mock variables to field. I would also reorder test lines to have a clear distinction between setup, execution and verification. Extracting chest type to constant also makes the test easier to understand.
private IChestsDatabase mockDatabase = Substitute.For<IChestsDatabase>();
private IDateManager mockManager = Substitute.For<IDateManager>();
private const int DefaultChestType = 0;
[Test]
public void RemainingTimeIsTimeToOpenMinusTimeAlreadyPassed()
{
mockDatabase.GetTimeToOpen(DefaultChestType).Returns(5);
mockManager.GetCurrentTime().Returns(6+2);
var chest = new Chest(mockDatabase, mockManager, DefaultChestType, 6);
var remainingTime = chest.GetRemainingTime();
Assert.AreEqual(5-2, remainingTime);
}
Now for a more general comment. The main benefit of TDD is it gives you feedback on your design. Your feelings that the test code is big, convoluted and wrong are an important feedback. Think of it as a design pressure. Tests will improve both with test refactoring, as well as when the design improves.
For your code, I would consider these design questions:
Are responsibilities assigned properly? In particular, is it Chest's reponsibility to know the passed and remaining times?
Is there any concept missing in the design? Maybe each chest has a Lock, and there is a time-base Lock.
What if we passed the TimeToOpen instead of Type to Chest upon construction? Think of it as passing a needle instead of passing a haystack, in which the needle is yet to be found. For reference, see this post
For a good discussion of how tests can provide design feedback, refer to the Growing Object Oriented Software Guided by Tests by Steve Freeman and Nat Pryce.
For a good set of practices for writing readable tests in C# I recommend The Art of Unit Testing by Roy Osherove.

There are some major points that are needed to be considered while writing unit tests as shown
Separate project for unit testing.
One class for writing unit tests of functions in one class of main
code.
Covering conditions within functions.
Test Driven development (TDD)
If you really want to know more (with examples), have a look at this tutorial
Unit Tests c# - best practices https://www.youtube.com/watch?v=grf4L3AKSrs

Related

Is making objects of two classes member of each other a bad practice?

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.

Creating objects with very many optional fields

I'm trying to recreate Hearthstone cards as objects in Java, but I'm having trouble doing this in a good and efficient way.
All cards have some common properties like a 'name'. But the problem is that there is about 300 cards to generate, and there is about 30 different abilities that each card may or may not have. Now, do I have to create a basic card class with all the possible abilities set to false and then set all its specific ability parameters to true? This approach seems to get very messy with all the getters and all the extra information that some abilities needs to specify... So my question is if there's there a better way to solve this kind of problem?
I would like to create these card objects so that I'm only 'adding' the specific abilities as fields, but I can't figure out how to do this in a good way.
Thankful for help!
Like Dave said, it's a little difficult to be sure what the best solution to your problem is without more context. However, from what I can gather, your problem is a pretty common one. For common problems, programmers often create efficient solutions that can be used over and over again called design patterns.
Design patterns aren't needed in every case, so be careful not to overuse them, but it seems like they could help you here. Both solutions mentioned by Dave may work, but the problem with making each ability an object is that it requires you to make as many classes as you have abilities. Furthermore, if each ability is a simple variable, it may be overkill to create classes for all of them, particularly since so many classes can become difficult to maintain. Although having these abilities inherit from an interface somewhat helps with maintainability, I think an easier solution can probably be found in the builder pattern.
I won't explain it in detail here, but here's a tutorial that seems reasonably simple. It's basic purpose is to
For your particular example it would look something like this:
public class Card
{
private final String name;
private final Ability soundAbility;
private final Ability animationAbility;
private final Ability customMessageAbility;
private final String technology;
// The constructor is private in this case to restrict instantiation to the builder.
private Card(CardBuilder builder)
{
this.name = builder.name;
this.soundAbility = builder.soundAbility;
this.animationAbility = builder.animationAbility;
this.customMessageAbility = builder.customMessageAbility;
this.technology = builder.technology;
}
// Getters
public String getName()
{
return this.name;
}
public Ability getSoundAbility()
{
return this.soundAbility;
}
// ... More getters and stuff ...
#Override
public String toString()
{
String text = "";
text += this.name + ":";
text += "\n\t" + this.soundAbility;
text += "\n\t" + this.animationAbility;
text += "\n\t" + this.customMessageAbility;
text += "\n\tI have the ability of " + this.technology + "!";
return text;
}
// Nested builder class
public static class CardBuilder
{
private final String name;
private Ability soundAbility;
private Ability animationAbility;
private Ability customMessageAbility;
private String technology;
public CardBuilder(String name)
{
this.name = name;
}
public CardBuilder soundAbility(Ability soundAbility)
{
this.soundAbility = soundAbility;
return this;
}
public CardBuilder animationAbility(Ability animationAbility)
{
this.animationAbility = animationAbility;
return this;
}
public CardBuilder customMessageAbility(Ability customMessageAbility)
{
this.customMessageAbility = customMessageAbility;
return this;
}
public CardBuilder technology(String technology)
{
this.technology = technology;
return this;
}
public Card build()
{
return new Card(this);
}
}
}
Then to run the program:
package builderTest;
class BuilderMain
{
public static void main(String[] args)
{
// Initialize ability objects.
Ability a1 = new SoundAbility();
Ability a2 = new AnimationAbility();
Ability a3 = new CustomMessageAbility();
// Build card
Card card = new Card.CardBuilder("Birthday Card")
.soundAbility(a1)
.animationAbility(a2)
.customMessageAbility(a3)
.technology("Flash")
.build();
System.out.println(card);
}
}
The output would be something along the lines of:
Birthday Card:
I have the ability of sound!
I have the ability of animation!
I have the ability of customizing messages!
I have the ability of Flash!
Keep in mind that I'm working without much context, so what you need might be significantly different.
Although previous answers are very good, there is still another way of achieve this Object creation
with very many optional fields
I found myself in similar situation when dealing with DB complexity and Command design pattern. As you know some table columns values are mandatory - some are not. I'm using this Effective Java book
for such cases.
So, useful here is the Consider a builder when faced with many constructor parameters. By doing so, you avoid
first, the Telescoping constructor pattern (does not scale well) - it works, but it is hard to write client code when there are many parameters, and harder still to read it.
second, the JavaBeans Pattern, which is good, but allows inconsistency and mandates mutability. It may be in an inconsistent state partway through its construction and precludes the possibility of making a class immutable too.
The Builder pattern as used simulates named optional parameters as found in Ada and Python.Like a constructor, a builder can impose invariants on its parameters. But it is critical that they be checked after copying the parameters from the builder to the object, and that they be checked on
the object fields rather than the builder fields.
Cheers.

I have a query about the variable and properties

I am the new to the programming and now I have a query regarding the variable and properties which is "what is the difference between declaring public variable and public properties?". Could anyone explain me with some instances?
Alot of people have different views on what is the "right" way, just different coding standards. Personally i think public properties give you a little more control as in you can have some simple logic in the get or set methods. Where as public properties are fine if you just want some quick global variable.
There are some instances in .net when you have to have properties rather than public variables e.g. usually when binding to datasources etc.
for more info check this link:
codinghorror.com
To clarify a little of what John said, properties allow you to add limitations and logic to what you are doing.
For instance if I have a rectangle class
class Rectangle
{
private float mWidth;
private float mHeight;
private float mArea;
public float width
{
get
{
return mWidth;
}
set
{
mWidth = value;
mArea = mHeight*mWidth;
}
}
public float height
{
get
{
return mHeight;
}
set
{
mHeight = value;
mArea = mHeight*mWidth;
}
}
public float area()
{
return mArea;
}
}
So rect.width += 20;
will update both the width and area;
Obviously this is a dumb example, but you could have done this without the properties for width and height, using public variables instead and instead just used
public float area
{
get
{
return width*height;
}
}
This will give you the correct area if you say float x = rect.area, but will not let you say something like rect.area = 40.
There are many more in depth things that you can do with properties, like databinding, for instance, but if you are just starting to program, you will get to this later.
For right now, you can treat a property as a convenient method that does not require () and that can take or give a variable.
If it is doing nothing but getting and setting, its probably better off as a variable.
If it is doing alot of internal work, and affect a considerable portion of your class, it should probably be a method.
If it is a quick function
to validate input (float rotation{set{mRotation = value%360;}})
or a multiple check output ( bool isInMotion{get{return (!isTurning && ! isMoving)}}
propertys work well.
No rules are final of course.
I hope this gives you a basic understanding of properties vs variables, though as always there is plenty more to learn.
Good Luck!

How to simplify this code or a better design?

I am developing a game, the game have different mode. Easy, Normal, and Difficult.
So, I'm thinking about how to store the game mode. My first idea is using number to represent the difficulty.
Easy = 0 Normal = 1 Difficult = 2
So, my code will have something like this:
switch(gameMode){
case 0:
//easy
break;
case 1:
//normal
break;
case 3:
//difficult
break;
}
But I think it have some problems, if I add a new mode, for example, "Extreme", I need to add case 4... ... it seems not a gd design.
So, I am thinking making a gameMode object, and different gameMode is sub class of the super class gameMode.
The gameMode object is something like this:
class GameMode{
int maxEnemyNumber;
int maxWeaponNumber;
public static GameMode init(){
GameMode gm = GameMode();
gm.maxEnemyNumber = 0;
gm.maxWeaponNumber = 0;
return gm;
}
}
class EasyMode extends GameMode{
public static GameMode init(){
GameMode gm = super.init();
gm.maxEnemyNumber = 10;
gm.maxWeaponNumber = 100;
return gm;
}
}
class NormalMode extends GameMode{
public static GameMode init(){
GameMode gm = super.init();
gm.maxEnemyNumber = 20;
gm.maxWeaponNumber = 80;
return gm;
}
}
But I think it seems too "bulky" to create an object to store gameMode, my "gameMode" only store different variables for game settings.... Is that any simple way to store data only instead of making an Object? thz u.
I think you are trying to represent a table of configuration data. Either put this in a configuration file if you're using a language that supports that, or use literal data in your code.
For instance, you might write this in C:
typedef enum difficulties {
DIFFICULTY_EASY,
DIFFICULTY_MEDIUM,
DIFFICULTY_HARD
} difficulties;
struct {
int max_enemies;
int max_weapons;
} difficulty_settings[] = {
{10, 4},
{20, 5},
{30, 6}
};
And when you want to read a particular setting, for example max_enemies for the easy level, then you can writedifficulty_settings[DIFFICULTY_EASY].max_enemies
It's easy to add more configuration (either more parameters, or more difficulty levels) by extending the table.
The overriding goal you should have here is to centralize the logic for retrieving the values related to different levels. By providing one place where these values are stored, you minimize the number of places within the code you need to change if you add another level, add other values, etc.
A class interface is a good choice for this solution. However, if you have a limited number of configuration options represented by the class, there is no reason you need to use inheritance. You can start out with a single class that encapsulates the logic. If the rest of your code retrieves its settings via the class interface you can later introduce a more complex design, such as subclasses for each mode, if it becomes necessary with limited modifications to the rest of your game.
For example, a first implementation may be something like
enum mode {
MODE_EASY = 0,
MODE_NORMAL = 1,
MODE_DIFFICULT = 2,
};
class gameSettings {
public gameSettings(mode GameMode) {
m_mode = GameMode;
}
public int getMaxWeaponNumber() {
int maxWeaponNumber;
switch(m_mode) {
case EASY_MODE:
maxWeaponNumber = 100;
break;
// Other mode settings.
}
return maxWeaponNumber;
}
// Other game settings....
private mode m_mode;
}
This combines the straightforwardness of a switch() statement with the benefits of a class interface. You can also swap out your switch() statement with a lookup table, as suggested by another poster, or some other mechanism as appropriate for your application.
I don't know java (which is what your examples look like), so I present my ideas in some simple C#.
Here is an idea. Use your game mode as a flag instead. If you start with:
[Flags]
enum GameModes
{
Unknown = 0,
ModeA = 1,
ModeB = 2,
ModeC = 4,
}
Now you have levels 1-7 available.
GameModes Difficulty = GameModes.ModeA | GameModes.ModeB; // difficulty = 3
GameModes Difficulty = GameModes.ModeB; // difficulty = 2
In addition, either method you showed will require you to add more options should levels (modes) change, get added, etc. Have your mode templates read in from XML (or other source of your choice), save the mode data into a serializable class. I don't think you should need base class extended by anything.
Use the switch approach in the constructor of your GameMode class.
Besides some syntax issues, I think you're on the right track. I don't think you have to worry about memory, considering there is probably only one mode at once. This is a form of the strategy pattern. You could extend it so the modes do more. For instance, instead of basically just holding constants, perhaps there could be a generateEnemies method that actually creates a set or list of enemies. This moves more of the strategy into the mode object. Sane defaults in the superclass can help avoid redundant code.
Its difficult to say what kind of refactoring could be done here, as there is too less information about other classes. But you could check the State pattern which encapsulates different behaviours in different state objects. Your approach of extending a base GameMode class is very similar to the state pattern. I think it's better than a switch-case-block... and patterns are reliable ways of doing things, if well applied.
Why do you think the switch is harder to mantain? If you add another mode you will have to add code, no matter what solution you employ.
The only case I can think of where you don't have to add code if you add another mode is if you generate the parameters of the game from the value of gameMode.
For instance: maxenemy = 5 * gameMode;
I think that unless you have very complicated initialisation to perform a switch is more than sufficient. I know, I know, objects and classes are nice and all that jazz, but if you just have to define a few vars and the thing works, investing time in developing a complex game mode class may not be a rewarding solution after all (I mean, how many game modes are you planning to add?).
Make use of the strategy pattern.
In Java terms:
public interface Strategy {
void execute();
}
public class SomeStrategy implements Strategy {
public void execute() {
System.out.println("Some logic.");
}
}
which you use as follows:
Map<String, Strategy> strategies = new HashMap<String, Strategy>();
strategies.put("strategyName1", new SomeStrategy1());
strategies.put("strategyName2", new SomeStrategy2());
strategies.put("strategyName3", new SomeStrategy3());
// ...
strategies.get(s).execute();

What is the real significance(use) of polymorphism

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.)