Advice on Flexible Pickup System - unity3d

First off, this is my first time posting here and I am new to coding so please for give me for all things. :)
I am trying to make a flexible pickup system for a game in Unity using C#. I would like to be able to pick a Pickup Type from a drop down have the code then direct which variable it updates with the minimal number of values for me or future designers to have to adjust.
For Example:
In the game you have a health pickup and a stamina pickup. I place the same HealthSystemPickup.cs on both game objects. In the inspector I choose if it is a health or stamina pickup type and then adjust the increase or decrease values. The code will then tell it to either update the health or stamina based on the pickup type selected. So on and so on for any future pickup types.
What I Have so far:
I have a script that defines the PickupTypes via public enums.
I have another script that is the Pickup itself which allows you to pick from that list of enums and set an increase and decrease value upon a OnTiggerEnter event.
Simple enough and works as long as I am calling specific methods from my health system script, but not based on the PickupType... and that is what I am stuck on. I am not sure how to direct what methods I am calling based on the PickupType it is.
I'd love advice on where to investigate or direction people have taken to do something similar.
any help would be great!
thank you.

This sounds like a good candidate for using polymorphism. You can define an interface or an abstract superclass that has all the methods your other scripts would interact with, and separate classes (rather than a single class with a type enum) for the health and stamina types. Something like:
public abstract class Pickup : MonoBehaviour
{
public int amount = 10;
public abstract void PickUp(Player player);
}
public class HealthPickup : Pickup
{
public override void PickUp(Player player)
{
player.Health += amount;
}
}
public class StaminaPickup
{
public override void PickUp(Player player)
{
player.Stamina += amount;
}
}
When you need to deal with pickups in other classes, you never address HealthPickup or StaminaPickup directly, you just refer to them as instances of Pickup.

Related

Unity - Game modes as state machine?

I am making a quiz game in Unity and I've come across architectural problem.
I want the game to have few game modes, like standard, faster answer - more points, etc. Each of which will behave in its own specific way but some things will be very similar like answering questions, starting timer, etc.
Currently its structured based on this. There is a QuizSystem that holds reference to QuestionDatabase, UIReferences(buttons,score text, etc) and GameSettings (questions per game/per mode etc).
To start the game you need to call QuizSystem.Start() and it starts its current GameMode which derives from abstract StateMachine and is a monobehaviour (dont know if neccesary). I also have abstract State class from which different game states will derive from. It has a constructor with (GameMode owner) as paramenter and 3 functions: Start(), Tick(), End().
So, this way I can have Standard game mode which will instatiate lets say StandardPreparationState, which on end will call StandardAnswerState which will start the timer and wait for user input and again call StandardPreparationState. Cycle will repeat until questions per mode amount is reached and then delegate next action to QuizSystem.
The advantage of this approach is that every mode can behave in its own way like add additional steps in between but it kinda limits reusability. What I mean by that is if some OtherMode would have the same preparation functionality but different action afterwards, it wouldn't work beacause
StandardPreparationState would transition to StandardAnswerState.
I could add another parameter such as (GameMode owner, State transitionTo) to the State constructor but that somehow seems wrong I don't know why xD
What I want to know is how do you guys implement different game modes for your games? Do you make each mode as separate scene? Or maybe use States Machine pattern and have Manager class that takes care of starting/swaping modes?
I know that each game is different but are there maybe some common approaches for that?
Thanks in advance!
This question is quite open and opinion-based. However there are few "common" approaches, one of the most important is to make game "data-driven".
What? Why? How?
Imagine you are having space shooter, where you have your ship flying around and picking guns. Each time you add new gun, you will have to code its damage, kind of projectiles and how many of them you shoot, their color, in what pattern they spawn, speed, size, ...
Everytime you would want to add a new gun, you would need to enter the code and change it there, compile, ... Lot of work.
Instead people thought, "why don't we create simple class that holds all the parameters? We will make it editable from Unity, instatiate it in the project and we won't need to code that much."
This is when Unity brought Scriptable objects.
Scriptable objects
A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances. One of the main use cases for ScriptableObjects is to reduce your Project’s memory usage by avoiding copies of values.
The idea is to create scriptable object for your mode and set up multiple kinds of modifiers that will the mode use. Folder structure might look like:
> ScriptableObjects
| |--> Modes
| |-> NormalSO (instance)
| |-> HardWithLotOfExpSO (instance)
| |-> EasyWithLowerExpSO (instance)
> Script
|--> ScriptableObjects
|-> ModeSO
ScriptableObject is class that doesn't really have the logic inside, just creates "structure" for keeping data. Example of such class would be:
public class ModeSO : ScriptableObject
{
public string modeName;
public float scoreMultiplier;
public int numberOfEnemiesMaxAlive;
public int numberOfEnemiesTotal;
public Vector3[] spawnPoints;
}
In the Unity itself you would then create instance of such objects. And what about interaction with other classes? Well, they would just work as:
Game manager hold single instance of active mode
Class that would be handling score (e.g. player / scoreboard) or Enemy would ask GameManager what is current multiplier for score
WorldSpawner would ask GameManager how many enemies should he spawn, where, and when to spawn next ones
At the beginning of the game you would be able to select difficulty by its name
Example of one of the classes (Scoreboard):
public class ScoreBoard: MonoBehavior
{
GameManager manager;
private float totalScore;
OnEnemyDestroyed(float scoreForEnemy)
{
totalScore += scoreForEnemy * (manager?.activeMode?.modifier ?? 1);
}
}
And the best is, whenever you will change some data, you will just modify the existing instance in the Unity. No need to go into code. No need to recompile whole game.
I think having different scenes for each game mode, especially if the modes are very similar save for a few settings, is unnecessary. I'd have to see more of your design to know how your game logic is being handled (is it all managed in one GameManager script? Or are there multiple scripts in the scene that take values from this manager script to handle game mechanics?)
One way I've handled different game modes before is to use a public int value in the GameManager that represents the different modes (i.e 1 = easy, 2 = medium, 3 = hard). I would then use a switch statement in any scripts whose behavior/values depend on this mode and reference that public int to determine game settings.
Game Manager:
public class GameManager: MonoBehavior
{
public int gameMode = 0; //set to 1,2, or 3 by UI
[...] //rest of game manager code
}
Example Behavior Script:
public class EnemySpawn: MonoBehavior
{
public GameObject enemy;
GameManager gm;
private float spawnRate;
Start()
{
switch(gm.gameMode)
{
case 1:
spawnRate = 15f;
break;
case 2:
spawnRate = 10f;
break;
case 3:
spawnRate = 5f;
break;
default:
spawnRate = 10000f;
Debug.log("invalid mode");
break;
}
}
Awake()
{
InvokeRepeating("SpawnEnemy", spawnRate, 0f);
}
[...] //rest of EnemySpawn code, including a SpawnEnemy() function.
}
This example would reference the GameManager's gameMode int to determine what speed to spawn enemies at, assuming there is a SpawnEnemy() function somewhere down in the code. I can't verify if this example is syntactically correct, but it's just to show one way to handle game modes.

Is it a good practice to create a class between my own scripts and mono behavior?

So, I have bound the CombatController to an object called "godObject". In the Start() method, I call init() functions on other classes. I did this so I can control the order in which objects are initialized since, for example, the character controller relies on the grid controller being initialized.
Quick diagram:
-------------------- calls
| CombatController | ----------> CameraController.init();
-------------------- |
| ---> GridController.init();
|
| ---> CharacterController.init();
So, now I have a slight problem. I have multiple properties that I need in every controller. At the moment, I have bound everything to the combat controller itself. That means that, in every controller, I have to get an instance of the CombatController via GameObject.Find("godObject).GetComponent<CombatController>(). To be honest, I don't think this is good design.
My idea now was to create a BaseCombatController that extends MonoBehavior, and then have all other classes like GridController, CharacterController etc. extend the BaseCombatController. It might look like this:
public class BaseCombatController : MonoBehaviour
{
public GameObject activePlayer;
public void setActivePlayer(GameObject player) {
this.activePlayer = player;
}
... more stuff to come ...
}
This way, I could access activePlayer everywhere without the need to create a new instance of the CombatController. However, I'm not sure if this doesn't have possible side effects.
So, lots of text for a simple question, is that safe to do?
I use inheritance in Unity all the time. The trick, like you have in the question, is to allow your base class to inherit from monobehavior. For Example:
public class Base Item : Monobehavior
{
public string ItemName;
public int Price;
public virtual void PickUp(){//pickup logic}
//Additional functions. Update etc. Make them virtual.
}
This class sets up what an item should do. Then in a derived class you can change and extend this behavior.
public class Coin : BaseItem
{
//properties set in the inspector
public override void PickUp(){//override pickup logic}
}
I have used this design pattern a lot over the past year, and am currently using it in a retail product. I would say go for it! Unity seems to favor components over inheritance, but you could easily use them in conjunction with each other.
Hope this helps!
As far as I can see this should be safe. If you look into Unity intern or even Microsoft scripts they all extend/inhert (from) each other.
Another thing you could try would be the use of interfaces, here is the Unity Documentation to them: https://unity3d.com/learn/tutorials/topics/scripting/interfaces if you want to check it out.
You are right that GameObject.Find is pure code smell.
You can do it via the inheritance tree (as discussed earlier) or even better via interfaces (as mentioned by Assasin Bot), or (I am surprised no one mentioned it earlier) via static fields (aka the Singleton pattern).
One thing to add from experience - having to have Inits() called in a specific order is a yellow flag for your design - I've been there myself and found myself drowned by init order management.
As a general advice: Unity gives you two usefull callbacks - Awake() and Start(). If you find yourself needing Init() you are probably not using those two as they were designed.
All the Awakes() are guaranteed (for acvie objects) to run before first Start(), so do all the internal object initialisation in Awake(), and binding to external objects on Start(). If you find yourself needing finer control - you should probably simplify the design a bit.
As a rule of thumb: all objects should have their internal state (getcomponents<>, list inits etc) in order by the end of Awake(), but they shold not make any calls depending on other objects being ready before Start(). Splitting it this way usually helps a lot

Duplicating Unity's mystic Interface power

Unity3D has an interface like this, for any Component on a MonoBehavior you just do this:
public class LaraCroft:MonoBehaviour,IPointerDownHandler
{
public void OnPointerDown(PointerEventData data)
{
Debug.Log("With no other effort, this function is called
for you, by the Unity engine, every time someone touches
the glass of your iPhone or Android.");
}
You do not have to register, set a delegate or anything else. OnPointerDown (the only item in IPointerDownHandler) gets called for you every single time someone touches the screen.
Amazing!
Here's a similar interface I wrote ...
public interface ISingleFingerDownHandler
{
void OnSingleFingerDown();
}
Now, I want consumers to be able to do this...
public class LaraCroft:MonoBehaviour,ISingleFingerDownHandler
{
public void OnSingleFingerDown(PointerEventData data)
{
Debug.Log("this will get called every time
the screen is touched...");
}
Just to recap, using Unity's interface, the function gets called automatically with no further effort - the consumer does not have to register or anything else.
Sadly, I can achieve that only like this:
I write a "daemon" ..
public class ISingleFingerDaemon:MonoBehaviour
{
private ISingleFingerDownHandler needsUs = null;
// of course that would be a List,
// just one shown for simplicity in this example code
void Awake()
{
needsUs = GetComponent(typeof(ISingleFingerDownHandler))
as ISingleFingerDownHandler;
// of course, this could search the whole scene,
// just the local gameobject shown here for simplicity
}
... when something happens ...
if (needsUs != null) needsUs.OnSingleFingerDown(data);
}
And I get that daemon running somewhere.
If you're not a Unity user - what it does is looks around for and finds any of the ISingleFingerDownHandler consumers, keeps a list of them, and then appropriately calls OnPointerDown as needed. This works fine BUT
the consumer-programmer has to remember to "put the daemon somewhere" and get it running etc.
there are obvious anti-elegancies whenever you do something like this (in Unity or elsewhere), re efficiency, placement, etc etc
• this approach fails of course if a consumer comes in to existence at a time when the daemon is not searching for them (Unity's magic interfaces don't suffer this problem - they have more magic to deal with that)
(PS, I know how to write an automatic helper that places the daemon and so on: please do not reply in that vein, thanks!)
Indeed, obviously the developers at Unity have some system going on behind the scenes, which does all that beautifully because "their" interfaces are perfectly able to call all the needed calls, regardless of even items being created on the fly etc.
What's the best solution? Am I stuck with needing a daemon? And perhaps having to register?
(It would surely suck - indeed generally not be usable in typical Unity projects - to just make it a class to inherit from; that type of facility is naturally an interface.)
So to recap, Unity has this:
public class LaraCroft:MonoBehaviour,IPointerDownHandler
Surely there's a way for me to make a replacement, extension, for that...
public class LaraCroft:MonoBehaviour,ISuperiorPointerDownHandler
which can then be used the same way / which shares the magic qualities of that interface? I can do it fine, but only my making a daemon.
Update
Full solution for "ISingleFingerHandler" "IPinchHandler" and similar concepts in Unity is here: https://stackoverflow.com/a/40591301/294884
You say you don't want to do a daemon but that is exactly what Unity is doing. The StandaloneInputModule class that is automatically added when you add a UI component is that daemon.
What you can do is create a new class derived from one of the classes derived from BaseInputModule (likey PointerInputModule for your case) that can handle listening to trigger and raising your extra events then add that new class to the EventSystem object.
See the Unity manual section on the Event System for notes on how to create your custom events and more details on what the input module does.
I hate to answer my own questions, but the answer here is really:
You cannot. You do have to add a daemon.
But then, it's very much worth noting that
Indeed, Unity add a daemon - they just hide it a little.
The final absolutely critical point to understand is that:
Unity screwed-up: you cannot in fact inherit from their lovely StandAloneInputModule. This is a big mistake.
Unity's StandAloneInputModule and IPointerDownHandler family - are brilliant. But you can't inherit from them properly.
The fact is, you just have to inherit sideways from IPointerDownHandler. That's all there is to it.
The fact is you have to make your own daemon ("as if" it inherits from StandAloneInputModule) which actually just goes sideways from IPointerDownHandler family.
So the actual answer is (A) you have this
public interface ISingleFingerHandler
{
void OnSingleFingerDown (Vector2 position);
void OnSingleFingerUp (Vector2 position);
void OnSingleFingerDrag (Vector2 delta);
}
public class SingleFingerInputModule:MonoBehaviour,
IPointerDownHandler,IPointerUpHandler,IDragHandler
and (B) you do have to put that on a game object (it's a daemon), and then (C) it's just stupidly easy to finally handle pinches, etc.
public class YourFingerClass:MonoBehaviour, IPinchHandler
{
public void OnPinchZoom (float delta)
{
_processPinch(delta);
}
That's it!
Full production code for PinchInputModule ...
https://stackoverflow.com/a/40591301/294884
...which indeed inherits sideways from ("uses") IPointerDownHandler family.
My assumption is that MonoBehaviour runs a type check in ctor. Which is why you cannot use the ctor on those to avoid overriding that process. The common solution is that your interface would also require to implement a registering method (Vuforia does that for instance) so any new instance registers itself.
You could also extend MB class with your own MB system:
public class JoeMonoBehaviour : MonoBehaviour
{
protected virtual void Awake(){
Init();
}
private void Init(){
if(this is ISuperiorPointerDownHandler)
{
if(ISuperiorHandler.Instance != null){
ISuperiorHandlerInstance.RegisterPointerDownHandler(this as ISuperiorPointerDownHandler);
}
}
}
}
It does not have the magic of Unity but you cannot achieve the magic of Unity with MonoBehaviour. It require the sub class to make sure it calls the base.Awake() if overriding it.
You'd have to come up with your own side engine system to run your own engine logic. Not sure that'd be worth it.
Another solution is to create your own Instantiate:
namespace JoeBlowEngine{
public static GameObject Instantiate(GameObject prefab, Vector3 position, Quaternion rotation){
GameObject obj = (GameObject)Instantiate(prefab, position, rotation);
MonoBehaviour [] mbs = obj.GetComponentsInChildren<MonoBehaviour>(true); // I think it should also get all components on the parent object
foreach(MonoBehaviour mb in mbs){
CheckForSuperior(mb);
CheckForInferior(mb);
// so on...
}
return obj;
}
internal static CheckForSuperior(MonoBehaviour mb)
{
if(mb is SomeType) { SomeTypeHandler.Instance.Register(mb as SomeType); }
}
}
Now it look like you are doing some magic only with :
JoeBlowEngine.Instantiate(prefab, Vector3.zero, Quaternion.identity);

what is a stateless class?

I would like to know what are drawbacks of a stateless class (if any)?
Has anyone seen a real-world application where some use case mandated the creation of a stateless class (No hello world please )?
I think a stateless class means a class without any fields.
Here's a real world example:
Writing plugins for Microsoft Dynamics CRM.
In that doc you'll see a note that says: "The plug-in's Execute method should be written to be stateless".
And basically what it means to be a stateless class is that there should be no global variables (except for a few special cases, which I won't get into unless asked).
The reason why this is mandated by CRM upon plugin developers is because CRM tries to improve performance by caching and re-using instances of plugin classes.
The way CRM executes its plugins is something roughly like this:
Main thread:
YourCustomPlugin yourCustomPluginCached = new YourCustomPlugin();
then later:
Thread1:
yourCustomPluginCached.Execute(context1);
and Thread2:
yourCustomPluginCached.Execute(context2);
What some developers do wrong is they will create a global variable to store the Context, which they set as the first line in the Execute() method. That way they don't have to pass it between all their methods. But this is actually a huge mistake.
Because if they do that, and in the scenario above, if the execution in thread2 begins before the execution from thread1 finishes. That would mean that context1 in thread1 would be overwritten with context2. And now that plugin will have some unexpected result. In 99% of cases, even when developed incorrectly this way, there are no problems, or no noticeable problems. But in 1% of cases, it will cause something to go wrong, and that something will be incredibly difficult for the dev to figure out what went wrong, and will probably never occur when they are testing/debugging. So it will probably go unfixed for a long time.
I never heard "stateless class", but I think you mean immutable objects (very useful notion!).
Or maybe a class which doesn't have any fields, so usually it looks like just bunch of pure functions.
If by stateless class you mean a class of immutable objects, then the drawback is that mutating operations need to copy an object instead of changing it in-place. That might be expensive.
I use these things quite often, pretty much whenever an object's behavior is determined by some input that can be processed all at once. A recent example is a statistical language model that I implemented: the model parameters were determined entirely in the constructor based on training input, and then the model could be queried for probability estimates on unseen text, but not modified. Immutability wasn't strictly mandated, but modifying the object didn't make sense, since there was no need to add data later on (in which case much of the computation had to be redone anyway).
I too am not sure what you mean by that term, but I assume it to mean a class with no fields, as the state of an object is actually the content of its fields.
Now, usually you'd use this kind of class as a collection of related functions - say, a certain Utils class. The common way to use this kind of class is by making its method static, so you don't actually have to create an instance of the class.
The only reason I can think of to actually create such a stateless object is if you'd like the actual functionality to be determined at run-time. So, if you have a UtilsBase class which offers a bunch of virtual methods and a UtilsDerived which overrides some of the methods, you can pass whoever needs to use the utils a reference to UtilsBase, and create the actual utils object at run-time, according to the specific needs.
A bit late, but here is my share.
I am sure the poster meant a stateless object. Please, people don't make it so dramatic.
Let's get to business. Some commenters asked about static. When static is used in a class, which should be used sparingly, all those members holding the static keyword now belong to the class and not anymore to the object. They are part of the class.
For example:
Declaring a Person class with a static property called Name does not make sense
public class Person
{
public **static** string Name { get; set; }
}
by the way another word for static is "Shared" which is used in VB.NET.
If we once set the name on the Person, then that name is shared everywhere because it does not belong to the object, but to the class itself. In real world you would not call all people "Jhon", or all your customers "Customer1". Each one will have a different name, surname, phone, address, etc. The moment we set these properties, this object becomes stateful, instead of stateless. It has a name, an address, etc. The properties of an object defined in a class make it stateful.
Here Name property belongs to the class, not part of the object:
Person.Name="Fili" //You would not call every person Fili in your application.
Let's redeclare the Person class by removing the static keyword:
public class Person
{
public string Name { get; set; }
}
In the example below, the object is stateful. It has a state, it has been given a name, "Jhon", which can be changed later. A person can change his name to Jimmy, for example. Once that is done, then the state of that object has changed from Jhon to Jimmy.
//From
Person person1 = new Person {
Name = "Jhon";
}
//to
person1.Name = "Jimmy"
The object 'person1' still is the same object, but its state has changed. It is not the same anymore. It has a different name.
So, person1 had a state until a cetain point in time, but then its state was changed. Now, it is in a different state.
Now, creating a new person is something new which has nothing to do with the person1. Person2 has its own state.
Person person2 = new Person {
Name = "Imir";
}
Using the static class: Person.Name="Fili" it has a state, but it belongs to the class and it is shared everywhere.
So, a stateless object will be one that has nothing to be changed, doesn't hold a value. Will you create a person without a Name? Would you create a customer object which does not exist? No, of course not. The moment you name a person or a customer, they have a state. They exists and can change their state.
Take the example of a Airplane. When you delcare it you add a Status property for example.
public class Airplane {
public string Status {get;set;}
}
var plane1 = new Airplane{ Status="Flying"};
So, the question arises: what is the state (status) of the plane at this moment?
One would reply: it is "flying". If you change the state to "taxing", then its state is "taxing", or it is "stationary", etc.
In stateless class, all field members should be readonly type. Although c# don't have any such features which will check statelessness at compile time like:
public readonly class MyReadonlyClass
{
public readonly double X {get;set;}
public readonly double Y {get;set;}
public readonly double Z {get;set;}
public MyReadonlyClass(double x_,double y_,double z_)
{
X=x_;Y=y_;Z=z_;
}
}
public readonly static class MyStaticReadonlyClass
{
public readonly static double X {get;set;}
public readonly static double Y {get;set;}
public readonly static double Z {get;set;}
static MyStaticReadonlyClass(double x_,double y_,double z_)
{
X=x_;Y=y_;Z=z_;
}
}
Stateless is something which should not preserve its state or in other words we can say that every time we use the any functionality or member of that class then previously used/set variables should not affect the next use of that class/functionality.
Consider the following code snippet (Ignore the standards)-
class Maths {
int radius;
public void setRadius(int r) {
this.radius = r;
}
public float getCircleArea() {
return (float) (3.14 * radius * radius);
}
}
public class Geometry {
public static void main(String[] args) {
Maths m = new Maths();
m.setRadius(14);
System.out.println(m.getCircleArea());
}
}
if some other running thread changes the value of radius in class Maths then getCircleArea() would give us different results because the state of the variable 'radius' can be change as it is a global variable. This problem occurs mainly in web application where we use bean containers. Most of the beans are Singleton and only has one copy. If we use global variables then there is a possibility that value of a global variable will change.
To make a stateless class try to use local variable so that the scope of the variable will be limited.
Example of the above getCircleArea() will be.
public float getCircleArea(int radius) {
return (float) (3.14 * radius * radius);
}

What is the value of Interfaces?

Sorry to ask sich a generic question, but I've been studying these and, outside of say the head programming conveying what member MUST be in a class, I just don't see any benefits.
There are two (basic) parts to object oriented programming that give newcomers trouble; the first is inheritance and the second is composition. These are the toughest to 'get'; and once you understand those everything else is just that much easier.
What you're referring to is composition - e.g., what does a class do? If you go the inheritance route, it derives from an abstract class (say Dog IS A Animal) . If you use composition, then you are instituting a contract (A Car HAS A Driver/Loan/Insurance). Anyone that implements your interface must implement the methods of that interface.
This allows for loose coupling; and doesn't tie you down into the inheritance model where it doesn't fit.
Where inheritance fits, use it; but if the relationship between two classes is contractual in nature, or HAS-A vs. IS-A, then use an interface to model that part.
Why Use Interfaces?
For a practical example, let's jump into a business application. If you have a repository; you'll want to make the layer above your repository those of interfaces. That way if you have to change anything in the way the respository works, you won't affect anything since they all obey the same contracts.
Here's our repository:
public interface IUserRepository
{
public void Save();
public void Delete(int id);
public bool Create(User user);
public User GetUserById(int id);
}
Now, I can implement that Repository in a class:
public class UserRepository : IRepository
{
public void Save()
{
//Implement
}
public void Delete(int id)
{
//Implement
}
public bool Create(User user)
{
//Implement
}
public User GetUserById(int id)
{
//Implement
}
}
This separates the Interface from what is calling it. I could change this Class from Linq-To-SQL to inline SQL or Stored procedures, and as long as I implemented the IUserRepository interface, no one would be the wiser; and best of all, there are no classes that derive from my class that could potentially be pissed about my change.
Inheritance and Composition: Best Friends
Inheritance and Composition are meant to tackle different problems. Use each where it fits, and there are entire subsets of problems where you use both.
I was going to leave George to point out that you can now consume the interface rather than the concrete class. It seems like everyone here understands what interfaces are and how to define them, but most have failed to explain the key point of them in a way a student will easily grasp - and something that most courses fail to point out instead leaving you to either grasp at straws or figure it out for yourself so I'll attempt to spell it out in a way that doesn't require either. So hopefully you won't be left thinking "so what, it still seems like a waste of time/effort/code."
public interface ICar
{
public bool EngineIsRunning{ get; }
public void StartEngine();
public void StopEngine();
public int NumberOfWheels{ get; }
public void Drive(string direction);
}
public class SportsCar : ICar
{
public SportsCar
{
Console.WriteLine("New sports car ready for action!");
}
public bool EngineIsRunning{ get; protected set; }
public void StartEngine()
{
if(!EngineIsRunning)
{
EngineIsRunning = true;
Console.WriteLine("Engine is started.");
}
else
Console.WriteLine("Engine is already running.");
}
public void StopEngine()
{
if(EngineIsRunning)
{
EngineIsRunning = false;
Console.WriteLine("Engine is stopped.");
}
else
Console.WriteLine("Engine is already stopped.");
}
public int NumberOfWheels
{
get
{
return 4;
}
}
public void Drive(string direction)
{
if (EngineIsRunning)
Console.WriteLine("Driving {0}", direction);
else
Console.WriteLine("You can only drive when the engine is running.");
}
}
public class CarFactory
{
public ICar BuildCar(string car)
{
switch case(car)
case "SportsCar" :
return Activator.CreateInstance("SportsCar");
default :
/* Return some other concrete class that implements ICar */
}
}
public class Program
{
/* Your car type would be defined in your app.config or some other
* mechanism that is application agnostic - perhaps by implicit
* reference of an existing DLL or something else. My point is that
* while I've hard coded the CarType as "SportsCar" in this example,
* in a real world application, the CarType would not be known at
* design time - only at runtime. */
string CarType = "SportsCar";
/* Now we tell the CarFactory to build us a car of whatever type we
* found from our outside configuration */
ICar car = CarFactory.BuildCar(CarType);
/* And without knowing what type of car it was, we work to the
* interface. The CarFactory could have returned any type of car,
* our application doesn't care. We know that any class returned
* from the CarFactory has the StartEngine(), StopEngine() and Drive()
* methods as well as the NumberOfWheels and EngineIsRunning
* properties. */
if (car != null)
{
car.StartEngine();
Console.WriteLine("Engine is running: {0}", car.EngineIsRunning);
if (car.EngineIsRunning)
{
car.Drive("Forward");
car.StopEngine();
}
}
}
As you can see, we could define any type of car, and as long as that car implements the interface ICar, it will have the predefined properties and methods that we can call from our main application. We don't need to know what type of car is - or even the type of class that was returned from the CarFactory.BuildCar() method. It could return an instance of type "DragRacer" for all we care, all we need to know is that DragRacer implements ICar and we can carry on life as normal.
In a real world application, imagine instead IDataStore where our concrete data store classes provide access to a data store on disk, or on the network, some database, thumb drive, we don't care what - all we would care is that the concrete class that is returned from our class factory implements the interface IDataStore and we can call the methods and properties without needing to know about the underlying architecture of the class.
Another real world implication (for .NET at least) is that if the person who coded the sports car class makes changes to the library that contains the sports car implementation and recompiles, and you've made a hard reference to their library you will need to recompile - whereas if you've coded your application against ICar, you can just replace the DLL with their new version and you can carry on as normal.
So that a given class can inherit from multiple sources, while still only inheriting from a single parent class.
Some programming languages (C++ is the classic example) allow a class to inherit from multiple classes; in this case, interfaces aren't needed (and, generally speaking, don't exist.)
However, when you end up in a language like Java or C# where multiple-inheritance isn't allowed, you need a different mechanism to allow a class to inherit from multiple sources - that is, to represent more than one "is-a" relationships. Enter Interfaces.
So, it lets you define, quite literally, interfaces - a class implementing a given interface will implement a given set of methods, without having to specify anything about how those methods are actually written.
Maybe this resource is helpful: When to Use Interfaces
It allows you to separate the implementation from the definition.
For instance I can define one interface that one section of my code is coded against - as far as it is concerned it is calling members on the interface. Then I can swap implementations in and out as I wish - if I want to create a fake version of the database access component then I can.
Interfaces are the basic building blocks of software components
In Java, interfaces allow you to refer any class that implements the interface. This is similar to subclassing however there are times when you want to refer to classes from completely different hierarchies as if they are the same type.
Speaking from a Java standpoint, you can create an interface, telling any classes that implement said interface, that "you MUST implement these methods" but you don't introduce another class into the hierarchy.
This is desireable because you may want to guarantee that certain mechanisms exist when you want objects of different bases to have the same code semantics (ie same methods that are coded as appropriate in each class) for some purpose, but you don't want to create an abstract class, which would limit you in that now you can't inherit another class.
just a thought... i only tinker with Java. I'm no expert.
Please see my thoughts below. 2 different devices need to receive messages from our computer. one resides across the internet and uses http as a transport protocol. the other sits 10 feet away, connect via USB.
Note, this syntax is pseudo-code.
interface writeable
{
void open();
void write();
void close();
}
class A : HTTP_CONNECTION implements writeable
{
//here, opening means opening an HTTP connection.
//maybe writing means to assemble our message for a specific protocol on top of
//HTTP
//maybe closing means to terminate the connection
}
class B : USB_DEVICE implements writeable
{
//open means open a serial connection
//write means write the same message as above, for a different protocol and device
//close means to release USB object gracefully.
}
Interfaces create a layer insulation between a consumer and a supplier. This layer of insulation can be used for different things. But overall, if used correctly they reduce the dependency density (and the resulting complexity) in the application.
I wish to support Electron's answer as the most valid answer.
Object oriented programming facilitates the declaration of contracts.
A class declaration is the contract. The contract is a commitment from the class to provide features according to types/signatures that have been declared by the class. In the common oo languages, each class has a public and a protected contract.
Obviously, we all know that an interface is an empty unfulfilled class template that can be allowed to masquerade as a class. But why have empty unfulfilled class contracts?
An implemented class has all of its contracts spontaneously fulfilled.
An abstract class is a partially fulfilled contract.
A class spontaneously projects a personality thro its implemented features saying it is qualified for a certain job description. However, it also could project more than one personality to qualify itself for more than one job description.
But why should a class Motorcar not present its complete personality honestly rather than hide behind the curtains of multiple-personalities? That is because, a class Bicycle, Boat or Skateboard that wishes to present itself as much as a mode of Transport does not wish to implement all the complexities and constraints of a Motorcar. A boat needs to be capable of water travel which a Motorcar needs not. Then why not give a Motorcar all the features of a Boat too - of course, the response to such a proposal would be - are you kiddin?
Sometimes, we just wish to declare an unfulfilled contract without bothering with the implementation. A totally unfulfilled abstract class is simply an interface. Perhaps, an interface is akin to the blank legal forms you could buy from a stationary shop.
Therefore, in an environment that allows multiple inheritances, interfaces/totally-abstract-classes are useful when we just wish to declare unfulfilled contracts that someone else could fulfill.
In an environment that disallows multiple inheritances, having interfaces is the only way to allow an implementing class to project multiple personalities.
Consider
interface Transportation
{
takePassengers();
gotoDestination(Destination d);
}
class Motorcar implements Transportation
{
cleanWindshiedl();
getOilChange();
doMillionsOtherThings();
...
takePassengers();
gotoDestination(Destination d);
}
class Kayak implements Transportation
{
paddle();
getCarriedAcrossRapids();
...
takePassengers();
gotoDestination(Destination d);
}
An activity requiring Transportation has to be blind to the millions alternatives of transportation. Because it just wants to call
Transportation.takePassengers or
Transportation.gotoDestination
because it is requesting for transportation however it is fulfilled. This is modular thinking and programming, because we don't want to restrict ourselves to a Motorcar or Kayak for transportation. If we restricted to all the transportation we know, we would need to spend a lot of time finding out all the current transportation technologies and see if it fits into our plan of activities.
We also do not know that in the future, a new mode of transport called AntiGravityCar would be developed. And after spending so much time unnecessarily accommodating every mode of transport we possibly know, we find that our routine does not allow us to use AntiGravityCar. But with a specific contract that is blind any technology other than that it requires, not only do we not waste time considering all sorts of behaviours of various transports, but any future transport development that implements the Transport interface can simply include itself into the activity without further ado.
None of the answers yet mention the key word: substitutability. Any object which implements interface Foo may be substituted for "a thing that implements Foo" in any code that needs the latter. In many frameworks, an object must give a single answer to the question "What type of thing are you", and a single answer to "What is your type derived from"; nonetheless, it may be helpful for a type to be substitutable for many different kinds of things. Interfaces allow for that. A VolkswagonBeetleConvertible is derived from VolkswagonBeetle, and a FordMustangConvertible is derived from FordMustang. Both VolkswagonBeetleConvertible and FordMustangConvertible implement IOpenableTop, even though neither class' parent type does. Consequently, the two derived types mentioned can be substituted for "a thing which implements IOpenableTop".