SOLID Principal - Interview Questions and Answers

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hello friends many asking in comment section that make a video on solid principles so here it is although I already posted these solid principles separately we also so if you watch them already then no need to watch this one but if not then from interview point of view these are very very important okay and one tip from my side if interviewer asks you about these principles in your interview then give him hint also like say something like whenever I created or added classes interfaces methods in my own project then I always follow these principles to create the better design okay so all right let's start with the first principle foreign principles what is the difference between solid principles and design patterns first of all of all what is a principle in journal a principle is a general or basic truth that must be followed and must not be violated right similarly solid principles are a set of principles which must be followed to develop flexible mentally maintainable and scalable Software System they are not optional they must be followed in every application okay whereas design patterns are concrete and solve a particular kind of problems in softwares okay for example Singleton pattern solves one problem of preventing multiple objects creation or in the class right but maybe that problem does not exist in your software so you do not need to implement Singleton pattern at all right therefore design patterns are optional to implement and required to solve a particular kind of problem another unrelated example is like honesty Integrity truth all are the must principles of Life which a human must follow but like career paths like Finance education technology all are good careers but you can choose only one to make a good career right similarly a great software can be made by using just one or two design patterns but violating any solid principle is not good at all for softwares in a way solid principles are more important than design patterns here are the five fixed solid solid principles and here is the list of some important design patterns not all but yes some the next difference is solid principles are not concrete they are abstract meaning for example to achieve a single responsibility responsibility principle there is no concrete or fixed solution you can achieve it by using various ways in your application whereas design patterns are concrete and solve a particular kind of problem in a particular way right so for example to implement Factory pattern there is a specific and fixed way to do it so now the differences are clear right what is single responsibility principle this is the first principle single responsibility principle SRP states that a class should have only one responsibility or a class should have only one reason to change let's say you have a class called employee this class has a method calculate salary that calculates the salary employee salary now the get Department method to get the Department of the employee okay and another method save that saves the employee to the database now to save add or delete employee to the database is not the responsibility of the employee so it is like an extra responsibility right therefore this violates the SRP because this class has extra responsibilities and one class must have same kind of responsibilities now to apply the SRP we can separate the responsibility into two separate classes like this and here is the code in this example we have separated the responsibilities based on the core employee responsibilities and the extra responsibilities which needs direct database interaction will be there in the employee repository class okay if you are aware about repositories and the services classes then they are the perfect example of single responsibility principle which you can give another good example is if you have one invoice class suppose then add invoice and delete invoice can be the part of it but sending invoicemail and error loading logging are extra responsibilities so create separate classes for them to follow SRP there the advantage of SRP is when a class have only one responsibility it becomes easier to change and test so if a class has multiple responsibilities changing one responsibility may impact others also and more testing in referrals will be required then right so this is the advantage of SRP great I think now you know SRP what is open closed principle this is the second principle of solid principles open code closed principle ocp states that a software entities like classes modules should be open for extension but closed for modification in other words in order to add some functionality in a class do not modify the class okay but extend it okay for example suppose we have a bank account class which has the properties name address and balance in your account and here you added one method also which is used to calculate interest based on your account type now if the account type is saving then the interest is three percent and therefore interest amount will be balanced multiplied by 0.3 okay similarly if the account interest will be multiplied by 0.5 in another case but suppose tomorrow we get a new account type and that is current account and for that the interest is seven percent then how you will add this thing so what you will do you will add one more elsif condition here in the middle right so basically inserting one more lcf will violate the open close principle because you are modifying the class rather than extending it now the question is how to extend this and how to follow ocp the first step is to follow ocp you must follow SRP first because SRP is the prerequisite prerequisite of ocp and to follow SRP you should only put the account level methods and properties in the account class like this okay then by using the SRP you should only put the account sorry again so then by using interface you should create one interface I account with the declared method calculate interest which accept account class object as a parameter okay then implement the interface for separate class saving account and other account like this and because you implemented the interface you must have to define the calculated interest mat third here inside it okay and you can put the same logic of calculate industry here see we have implemented SRP and our structure can Implement ocp easily now now if you want to add the new account type then you do not need to have to modify any class right like this you can add one new class current account and same way it can be implemented account interface with seven percent enter interest see ocp implemented so easily if you will first Implement SRP properly the benefit is simple testing is required to test individual classes but if you will keep on adding and modifying one class again and again keep on adding it then even for the smallest modification you have to test the whole class again right that might not be an issue for the small projects but yes in big projects more testing needs a lot of efforts great I think you now you know one more solid principle and that is ocp what is interface segregation principle let's see the definition first the interface segregation principle ISP is stated that a class should not be forced to implement interfaces that it does not use okay so let me explain with the Excel example suppose you have an interface I vehicle which has two methods drive and fly declared only okay now you are creating a class flying car which will implement the ivehicle interface method something like this perfect but suppose tomorrow your manager asks you to create a class for just a normal car okay and then you will write the code something like this here this I vehicle interface is creating the problem for you because fly method is not applicable for car class but still you have to implement it right you have to implement all the methods of the interface right so what is the what was the definition the interface segregation states that class should not be forced to implement not be forced to implement interfaces that it does not use and here we are forcing on car class to implement the iweekle interface methods this fly method and it it does not use this right so so we are violating interface aggregation principle here now what is the solution then one solution is it is better to have multiple smaller interfaces than larger interfaces for that we will divide that big interface into a small interface like this iDrive and iFly like this and then car can inherit iDrive interface and Implement just the drive method without any problem and what flying car class can Implement both iDrive and iFly interface and Implement both drive and fly method like this so basically multiple inheritance you remember it is can be done by interfaces right now we are not forcing any interface method on any class right so this is interface segregation principle segregate your interfaces as small as possible as per the derived class needs okay what is list scope substitution principle for this principle I will first explain the normal definition and at the end I will share one very easy statement about LSP let's see the normal definition first and understand with the help of the code the list of substitution principle LSC LSP states that an object of a child class must be able to replace an object of the parent class without breaking the application remember child class sub class and derived class are same things and parent class super class and base class are same things okay now let's see the example code first we will see how to follow the telescope substitution principle and then we will see how we can violate the LSP okay suppose you have a parent class employee which have two virtual methods calculate salary and calculate bonus like this for Simplicity I am not calculating here anything but just returning 1 lakh as salary and 10 000 as bonus okay now we have one class permanent employee which is derived from the employee class this class override the calculate salary method of the base class and set a new salary and this class will automatically get the calculate bonus method from the base class right because we are not we are not overriding it here and as the rule of The Inheritance Base Class methods will be automatically available for the derived classes simple right now we have one more class contractual employee class which is again derived from derived from the employee Base Class here we will again override the calculate salary method of the Base Class like this but but but this contractual employee class does not supposed to have this calculate base bonus method of the base class because bonus is not applicable for contractual employees okay therefore here we have to override the calculators bonus bonus method and throw the error like this why we are throwing the error here because if we do not override the calculus calculate bonus method and write no code here then by default the can contractual employee will automatically get the calculator bonus method of the employee class parent class like the permanent employee class inherited right and if anyone in future will create the object of the contract to contractual employee class then data object will be able to call the call calculate bonus class then write which we do not want because as per the rule of the contractual employee class that that should not be able to call bonuses right so to stop that we have to overwrite this method here and we have to throw the error now if someone will create the object of this contractual employee class and call this call calculate bonus method then they will get this error right now let's first follow the LSP and then we will violate the LSP first inside the main method we will create the object of the base employee class like this and we will also create the object of the derived classes also here now first we will call the methods from The Base Class objects like this see no problem and 1 lakh and 10 000 will be the output as salary and bonus okay because that we got from the Base Class methods right now listen carefully and read the definition again the list LSP states that an object of a child class must be able to replace the object of the parent class okay so as per the definition we will replace the parent class object employee with the permanent employee child class object P employee like this to call the exact same methods and see your application will not break these methods will completely work fine right and the output output will be like 2 lakhs and 10 000 this time that means here we are following the LSP for the permanent employee class case right because here object of a child class is able to replace the object of the parent class without breaking the application now we will see how to violate LSP when we will violate LSP now we will replace the parent class object employee with the contractual employee child class object C employee to call the again the same exact methods like this okay here the first class call of calculate salary will work fine right but but the second call of calculate bonus will break the application and this exception will come so here object of the child class is not able to replace the object of the parent class because the application breaks and therefore this for this particular example where employee is the base class and contractual employees the child class we are not following LSP now might be you will say the error is expected right because yes we are throwing the error inside the calculate bonus method of the contractual employee class here yes yes yes this is expected we were but we were forced to throw the error here that is because uh that is we have to do because otherwise I already explained you like how a contractual employee class will automatically inherit this bonus method right but but we should never design our classes and methods in this way in such a way where we have where we have to throw the error like this okay this thing we should avoid so when designing base classes and derived classes then we should make sure that whatever methods we are keeping in the base classes okay those methods must be applicable for the derived classes also derived class can override the base methods and that is completely fine but by default if those methods are not overrided then all the methods of the Base Class must be applicable for the derived class that should be the ideal design approach as per the LSP like in our example all employee class methods are applicable for permanent employee classes right all methods and therefore that they are following LSP but for counteractual employee class case our design is not good as we are we are for throwing errors here and uh because uh calculate method we all know the reason and that's why we are violating the LSP here all right now we can correct the design like we should to correct this design and to follow a LSP for contractual employee also we should remove this calculate bonus from the employee Base Class and put it somewhere else like some other class some abstract class interface some other design we can do but we should not do like this finally as I said in the beginning the short statement for LSP or the uh in other words what we can how we can Define the LSP is all the Base Class methods must be applicable for the derived classes also all the methods okay I think this is the simpler definition great now I think you have a good understanding of the LSP and even in your projects you now know how to implement LSP right what is dependency inversion principle the definition is the dependency inversion principle dip states that a high level class must not be depend upon a lower level class okay so what is high level what is lower level uh suppose we have a data access layer class that is responsible for adding a customer to the database okay and however instead of depending on an extraction like an ilogger interface it directly creates a file logger object and call its method log method to write a log message like this here data access layer is the high level class and file logger is the lower level class and you can see that access layer class is tightly coupled with the file logger class and is depend on it right but as per the definition high level high level class must not be dependent on the lower level class therefore this implementation violates the dependency inversion principle okay the disadvantage of this is if tomorrow you want to replace this logging technique or behavior in your own application for example from file logging to database logging you want okay you want to modify inside the that access layer here is the file logger log method okay the method is same but you have to use a new class now now the question so it will be a tight coupling and you have to replace like here we have only one that access layer class but there can be multiple classes like this and if you want to replace then you want to replace all over this file logo with this new database logger okay now to resolve that we have that dependency inversion principle and if you already know dependency injection then you remember how to inject the dependency class from The Constructor right so dependency injection is a design pattern to implement dependency inversion principle okay it's a one of the way to implement dependency inversion principle now to implement first we have to create an ilogger interface that declares just declare the log method as well as a file logger class that implements the ilogger interface and provides in its own implementation of the log method here inside now in the data access layer inject I logger object as a Constructor parameter and store it in a privileged field like this then when the add customer method is called it uses the ilogger object to log a message instead of creating this file file logger object directly right now high level this that access layer is high level right is not dependent on low level file logger class as we are you can see we are not using anywhere file logger inside this data access layer here the benefit is again tomorrow if you want to replace this file logger with database logger then you can easily do it just just then add a new class database logger inherit the class from the ilogger implement the log method as per the new requirement and remove this five logger class and then automatically your I logger which you injected in the data access layer Constructor will start pointing to the database logger method okay because file logger is gone now I logger is referring to database logger now no need to change any code inside this data access layer or inside any other class which is using the ilogger okay because now you are not coding for the classes you are coding for the interfaces that's it great now now I think you know dependency inversion principle right what is dry principle this is not among the solid principle but yes this is very important and very simple to know okay so the first point is dry stands for do not repeat yourself meaning once you have written one code try to not repeat it anywhere sir else try to put that code in some method and reuse it again and again then second do not write the same functionality multiple times this is just the same thing third point is instead write code once and then use it at multiple places using inheritance now the same thing but you can use inheritance for example you have written one method for 10 classes now what you do for those 10 classes create a base class and put your method over there in the Base Class okay then all the derived 10 classes will will automatically get it so getting my points so you are not repeating that one method at 10 places then so this is the dry principle and this is also very important great and congrats for completing the solid principles I think now you are aware about all the principles I recommend you to revise them again and again okay until you completely hundred percent absorb them and do not forget to press the like and the Subscribe button and all the best for your interviews and your career
Info
Channel: Interview Happy
Views: 92,682
Rating: undefined out of 5
Keywords: SOLID, Interview Questions and Answers, Software Engineering, IT Companies, Product Based Companies
Id: xmI-Ubq_AAc
Channel Id: undefined
Length: 24min 3sec (1443 seconds)
Published: Sat Jun 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.