Home > Software engineering >  when to use interface and when not?
when to use interface and when not?

Time:09-19

I completely understand that we use interface's as contract to tell developers what are the functions to implement. But is this going to be at all cases "Meaning do we have to implement an interface for each class". lets say we have only one class going to implement an interface. do we define an interface for for that class specifically. and when not to use interfaces.

My understanding is that we use interface when we would like to enforce developers to implement a set of must have functions. lets say we have a server class. then we must do interface because we always need for instance two functions one to turn the server on ServerOn(); and one to turn the server off ServerOff();

CodePudding user response:

The use of interface comes into play where you want common behavioural functions to be used at all time. Let’s say you are building an application that deals with different type of server’s and in the future you might add other types of servers. Then in this case you will always have functions to turn on server’s and turn off server’s. Use interface to add these required functions ServerOn();, ServerOff(). then each time you add a new server new type you implement the Interface IServer which then requires these function. The idea here is to apply abstractions where low level classes depends on abstractions.

The other main usage of interface that some programming languages or almost all allow the concept of polymorphism through interfaces. Meaning that all classes implements the interface called IServer for instance can be declared as IServer sqlServer; IServer orcaleServer; this helps in using DI and Unit testing. Ex: Look at the following constructor Public Server(IServer server){//rest of code}; you see we created a constructor that can take for instance OrcaleServer, SQLServer where these are classes that do implement the interface.

  • Related