403 Forbidden

Request forbidden by administrative rules. real life example of interface

It's ok, if it's in 1 place, but what if you use it in hundreds of places all throughout your program?

By doing this, we're separating out our business logic entirely from our external dependencies and by doing that we have much more testable, maintainable code. You're gonna have to update so much. We're forcing something to be implemented that should be necessary but isn't so we're doing a workaround. What am I missing? Not an OP, but Thank you for a such detailed, well-written explanation. For example, imagine, that you have some class that is creating a PDF report for you. Without using interfaces, you rely on that exact class's logic, so when you want to change something, you will need to change the code in that class and in the other classes, that use it. If you now want to test this you'd have to pass THE actual BankAccountDataSource in, that probably connects to some database or reads a file or whatever, but does the same shit it would do in production. Why not put all of those classes that have no actual dependencies outside of some interfaces in a project of their own that everything can reference? So, finally, we come to implementing those two services. How that notification gets sent or even where it's sent to is an implementation detail that you just don't care about here. There's numerous frameworks to let you create mocks/substitutes with relative ease, but for a quick example: I used NSubstitute. I'd say you have a conceptual issue - you have a behavior (generating interest) that may not apply to every object in a collection, but when you iterate over the collection you don't want to check if that behavior is supported. All we have to do is implement another INotificationProvider class and.literally nothing else about our application changes. So you inject it into said classes, which is just a fancy word for passing it in through the constructor. List should contain the minimum interface you need to access on the Person object.

Now imagine we want to implement a 3rd type of notification. I have to do some weird type checking to get just those objects and then run the method. Notice that from here, our implementations have zero affects on our business logic - we can write and rewrite those services 1000 times and the business logic won't be touched at all because the business logic is no longer controlled by them - we've inverted that, we're now in control. Another way to look at this is that the implementation details of these services are controlling your program flow - and we want to stop that. There could be some BaseAccount class with those 2 fields and then you could inherit from this class and get those fields in subclasses. Or create an IInterestBearing that defines an CalculateInterest method, and do the same as above with it. What do we need to send an email? Whatever the name, this is the thing that your other classes talk to when they want to get Lists of BankAccounts.

The notification might be anything from a popup in your app, the built-in windows notifications to an email to a message on slack.

Then you'll actually implement your INotificationService into NotificationService and, for the most part, it'll be something relatively simple - in fact it's probably just going to be that switch statement we previously had in our business logic and all that switch statement is going to do is call the relevant IEmailProvider or ISMSProvider - but again, don't let the implementation details of sending emails or text messages bog you down here. Don't even worry at this stage about how you'll send an email or whatever. I am still reading through all the answers but your suggestion of having an InterestCalculator and using dependency injection seems close to the mark. They're all valid possible notification implementations. That's rad. Let's say you have a BankAccountsDataSource class. I think starting with the problem interfaces solve (which you explained well), and determining if you have a similar problem should have been OPs first step. What if we want other accounts to support interest? Instead, forget about the implementation for a second - the class you're currently working in, your business logic, shouldn't care about the implementation of something that isn't its concern and neither should you. At this point, you can write out the business logic completely, unit testing it and mocking your INotificationService without so much as sending a single email or SMS message and be assured it's working as it should.

Another way is to decouple the interest calculation logic from the account and to use an InterestCalculator abstraction that will take the account, AccountRates list (the rates list may be configured separately and may be the part of IBankAccount) to get the interest calculation done. We'll create a class called NotificationMessage with those same properties and just pass that around instead. Your business logic just wants to send a notification but it's already getting bogged down with details about who to send the notification to and even the kind of notification - not exactly SRP. We've just added brand new functionality without having to change anything else. Somewhat contrived example, but if not all IBankAccounts pay interest, then the ones that do can implement IPaysInterest, and Person can calculate interest like this. The solution here is clearly simple inheritance. Some kind of account will have a specific logic for an interest and another one will do nothing (like CurrentAccount in my country). IEmailProvider and ISMSProvider are basically the same, so maybe they can just be two separate implementations of a singleINotificationProvider interface and our INotificationService can have INotificationProvider[] injected into it instead and with some simple logic, we don't need a switch statement any more, we can just loop through each provider and check if the customer has it enabled. Using interface, you could change the implementation and all your other code won't even notice. You've had a lot of good answers so far, but nobody has mentioned Inversion of control yet and I think that's a concept that'll help you understand where the power of interfaces can come in. A better solution that some have suggested would be to have IBankAccount just have the Name and Balance property, and then have two more interfaces which implement it: IAccountWithInterest and IAccountWithoutInterest. To use your example, running some calculation on all Savings Accounts, surely you'd first need to get said accounts from somewhere. The OOP idea would be to have the CalculateInterest method within the IBankAccount interface and to implement it for every kind of account you have, like CurrentAccount, SavingsAccount, DepositAccount whatever else. Our existing providers haven't been touched. well you are trying to use a specific object method CalculateInterest with a generic IBankAccount list. Then you just put CalculateInterest on the interface. Or in other words - one way interfaces are useful is when you want to write a method that operates on something, and there may be many different ways that something is implemented. So you either add CalculateInterest() to your IBankAccount interface and have it return zero for a CurrentAccount and any other account type that may not generate interest, or you check to see if each object supports calculating interest. It would have been clear there is no point in establishing the interface when the classes you plan on having implementing don't have shared and abstractable functionality. You'll end up with a method that gets called like this somewhere in your business logic: Now this already smells a bit. In your example you used interfaces, but what you should've used is inheritance. Now, say you decided to use email as a source of the notification, you'd probably be tempted to write some kind of EmailService class that has a simple SendEmail() method - and that's a perfectly valid thing to do. You will likely end up writing those interfaces, but that'll come later and this class won't even know they exist. I'm sure somebody else (basically anyone if you google Moq or NSubstitute) can explain this better than my sleep-deprived ass. But you don't haaaave that here, so what do? Every time I try to do it I end up making things more complicated and any tutorials I read are so simple as to be useless (class FlyingBird : Bird etc.). This way you can still use an interface, but have two different implementations of CalculateInterest which exactly how OOP / polymorphism should work. In this example, maybe - some people have even suggested that the CurrentAccount should implement CalculateInterest and return zero. For the latter, you could either check to see if it's a savings account (not ideal), or you could add another interface like an IInterestGeneratingAsset with a CalculateInterest() method and check to see if the object implements that interface. This. I know toy examples are part of the problem, but let me give you a realistic/practical one and step through where IoC comes into play. A naive implementation might use a switch statement to call either SendEmail() or SendSMSNotification() depending on the user choice but it's still getting way too complicated and you're still violating SRP. There's no point in using interfaces here, if your classes do not share any logic. Press J to jump to the feed. We have several classes with entirely different concerns that have similar (or identical) method signatures, something like SendMessage(Customer customer, NotificationType type, string Message) has those same 3 params used all over the place - so why not turn that into a DTO? But what if I want to perform CalculateInterest() on any SavingsAccounts? Who says a CheckingAccount doesn't pay interest? Now NotificationMessage is a core part of our application, it's a core part of our domain but it has zero dependencies of its own. Once you start accepting Interfaces you can remove "tightly coupled" classes. This would also make it easier to extend the system with additional interest-generating account types in the future. Finally we can start sending emails and SMS's so we'll create our EmailProviderand SMSProvider, implementing the logic that actually is tightly coupled to our providers.

Your business logic will just call SendNotification() with those params and be done with it. Shluuurp, get the nuget, reference the usings, and off you go creating all kinds of types that act as if they were whatever you pay tell them to be. a problem with the way stuff like this is taught is that we are often taught how to implement some sort of pattern, but not to what benefit. The only thing your Notification service needs to do is figure out which notifications the customer has switched on and fire the relevant method. So instead, you'll write an interface called something like INotificationService and it'll have a method like SendNotification(Customer customer, NotificationType type, string Message). Now look closely at what's happened here, as there's some low hanging fruit for refactoring. At some point you'll be writing out some class that needs to send one of these notifications. It would make sense if all bank account classes had CalculateInterest() method, so that you could make an IInterestCalculator interface and then use it's implementations. Interface the bitch. SMS doesn't use email addresses, it uses phone numbers to send messages to and the message structure is quite different. GetSavingsAccount() is very very very specific. We have very clean code. Here's an example of what I mean with a pretty simple example: In the Person class, we have a list of BankAccounts. Now at this stage, you can test all your logic around the customer's selected notification preferences and make sure the relevant message data is passed over correctly with Unit Tests without having to send a single email or even debug your application.

For examle also something that only pretends to be one. But here you go, there's a use case for Interfaces. Our business logic is the same. Later on you decide that actually you want the customer to be able to pick email or sms as their notification source. The point of interfaces is to make your classes less coupled, so that you do not rely on the implementation but on the abstractions, so that in future, when your code WILL change you will not have hard time going through all your code trying to change some logic. It doesn't seem right to me. So there'll almost certainly be a really similar method on both IEmailProvider and ISMSProvider called SendMessage(Customer customer, NotificationType type, string Message). It can be passed a List, string[], IQueryAble etc and it works. What are some good resources for learning how to use this to make my code better rather than just more impressive because of its OOPness? If I want just the Name or Balance - great, I can iterate over the list of IBankAccounts and get them. Or adding CalculateInterest to the IBankAccount interface and just have CurrentAccount implement CalculateInterest and return 0 if it does not generate interest. We want to invert that. Well an email address is probably the most crucial thing, but you need a subject and maybe some body text, possibly even a "from" address but lets say that's configured globally for this case. Look for quality samples that come with unit tests and implement mocking of interfaces.

Interfaces are used to separate your logic from concrete models to abstractions. This is what I'd say is the benefit as well. You can foreach that IEnumerable or use linq methods on it. This! is why you should end up with most classes implementing an interface. I think there are actually two behaviors here: So I think the idea of having a second interface for the interest calculating behavior is a better way of describing the system. If you regularly call CalculateInterest(), then you might want to further abstract it by adding an interface like IInterestBearingBankAccount. You can't have it both ways. Let's say you have a workflow where you need to send some kind of notification to the user. Awesome read! From the perspective of this single class, you want to be able to just call some kind of SendNotification() method to fire that notification off and let something else handle that, let something else figure out what kind of notification it should be and how you'd send it. Now you can pass in anything that looks like an implements IBankAccountDataSource. Even our INotificationService remains the same. You can write a method that accepts IEnumerable. And imagine, that there's new great library which is doing PDF creation faster and you want to use it. And if it doesn't, why can't it just return 0?

And thus it begins, and I effectively go down a rabbit hole whereby it would be easier to just have two different lists of List and List. I am not new to C# but something I have always struggled with is making practical use of interfaces. The answer is interfaces, but the solution isn't to create an IEmailProvider or an ISMSProvider interface with the same methods, that's not really going to help you at all and you'll just end up with a layer of abstraction that helps you write some unit tests but not much else. What OP wanted was to implement a class, and then a special type of that class with added functionality. Press question mark to learn the rest of the keyboard shortcuts. And I'm not even good with programming.

I am still convinced there's a flaw in the design of my Person class which tries to iterate all bank accounts and call CalculateInterest when it isn't needed for all accounts. The built in IEnumerable is a great example of an interface.

No se encontró la página – Santali Levantina Menú

Uso de cookies

Este sitio web utiliza cookies para que usted tenga la mejor experiencia de usuario. Si continúa navegando está dando su consentimiento para la aceptación de las mencionadas cookies y la aceptación de nuestra política de cookies

ACEPTAR
Aviso de cookies