Why is multiple inheritance not the main purpose of interfaces? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
My teacher kept saying that interfaces are not there so one could use them as a way to achieve multiple inheritance in c#.
Why is that? What are they for then? Noone could explain this to me easily yet, I'm so confused.
I read a few articles and books that described interfaces and it seems that all of them are suggesting to use interfaces as a workaround to implement multiple inheritance..

In a statically typed language, or when using static typing in a language that has both dynamic and static typing (such as C#), then inheritance consists of two pieces. The interface, and the implementation. The interface is a contract that says that it will fulfill a specific set of methods or properties. The implementation is the code that actually does it. Code implements an interface.
Interfaces are used to guarantee that an object implements specific contracts. This can be a single contract, or multiple ones. This is not multiple inheritance, which inherits both the interface and the implementation.
Yes, some people try to simulate multiple inheritance with multiple interfaces, but that's not its purpose, and that simulation is very poor anyways.
Multiple interfaces says that an object supports multiple contracts. Multiple inheritance says that an object re-uses multiple implementations. Again, inheritance requires both interface and implementation. Interface implementation is just the interface.

Interfaces form a contract (they say what an object can do), but don't provide implementation.
Why bother? Defining the contract is extra work, why not just create a class?
For example, let's say you want to develop a drawing app. You may come up with few objects like Circle, Triangle, Square, etc. then you start adding methods and add something like Draw(). That is something you could add to the interface that all shapes implement. In C#, by convention it would be named something like IDrawable.
But why not a class?
Let's imagine you are extending the app and adding a support for grouping shapes, to create more complex patterns. The groups can also be drawn, so they also have Draw() method. Now, if you only want to draw the "thing", you do not need to know if it is a shape or a group, or something else you haven't invented yet.
But why not a class?
Because there could be more capabilities, like Move(), Serialize(), etc, and C# doesn't allow you to inherit from multiple classes.
Why not?
It is not a technical limitation, but a choice made by C# language designers. Some languages, like C++ allow it, but it brings few technical problems, most famously the diamond problem. It also makes the compiler more complicated and it's been decided it is not worth it. It also

Related

When should I use interface/abstract class and when should I not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
We all know that interfaces and abstract classes are needed for many design principles, and were told to be "the best practice" of programming, both for maintenance and expansion purposes.
But I also heard people saying, "Do NOT overuse interfaces or abstract classes"!
So then, how do I "draw the line"?
I know the difference between interface and abstract class (kind of).
So I'm not interested in "when to use which?", I'm interested in "when is too much"?
For example, the example given by r/PiggyChu620 from this post is clearly "overengineering" the interfaces, as r/AlarmedSlide1 down below puts it.
So to avoid the same mistake r/PiggyChu620 did, is there any "borderline guideline" as to "when should I use interface/abstract class and when should I not"?
Thank you very much for your help!
It's actually pretty easy.
If you can delete an interface from your code (maybe replace it with a specific class when it's used as a parameter) and your code still works, it wasn't needed.
As with every tool, the answer to the question "when should I use it" is "when you need too". If you use it "just because", then you probably make your program simpler (and therefor more maintainable) when you don't use it at all.
Interfaces, Base classes and OOP are important because you are solving problems with it. If you find yourself doing it without solving an actual problem with it, I would consider it "overused".
Interfaces are contracts that are signed between classes, and all classes that use it are bound by the rules of the interface.
This type of design makes it easier to reuse and increases maintenance.
Suppose you create a vehicle interface. All vehicles must implement this interface, including bicycles, motorcycles, cars, etc.
This style of design creates blood and creates a beautiful and principled architecture for your program
So if you have classes that behave similarly, you can use interfaces or abstract classes.
You can refer to this link to compare abstract classes and interfaces

using a class or a function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Sorry for the noob question but I've always had a hard time distinguishing situations when it's good to create a function or a class. For some of the smaller programs I write at work, I write a whole bunch of functions to carry out specific tasks. The programs all work as intended. However, when I have some of my more senior developers take a look to give me their critique, they rewrite a lot of my functions completely over as a class. These are my coworkers so I don't want to look completely incompetent (I just started this job as a junior developer) by asking them why they did that. What do you guys think?
That is too broad question and you really have to understand the concept of the Object Oriented Programming and when you should use it.
Note: Bellow you will find my personal opinions (some of them borrowed from great books' authors and experienced programmers), and for sure the things highlighted bellow, does not reflect the entire power of the Object Oriented thinking and design. These will be gained throughout experience and feedback.
0. A use case of a class
There are many applications, on where to use an internal class to your C# code.
Data Transfer Object (DTO)
One application (of really many) and is used many times in software, is when you are transmitting data from database to your application for processing.
What better than writing an internal class that will store your data, implement useful and re-usable methods that can be used later in your application logic (e.g isAdministrator) and so on.
1. Object-Oriented Design Patterns
I will recommend you reading a book about Object-Oriented Design Patterns.
Books like that, describe some problems scenarios that can be implemented with a class using a pattern. Once you have read about these patterns and possible scenarios on where can be used, you will be able to get the book, find the pattern and solve your problem.
A co-worker of mine, state something really useful. When you are facing a problem, you should ask yourself:
"Does this problem solved again using a design pattern?"
If the answer is yes, then you go back to your reference book to find your design pattern, that will solve your problem, without re-inventing the wheel.
This approach, will teach you how and when you should use a separate class; but will also help you to maintain a communication language between you and your co-workers, that is, if you are talking about your code to a co-worker, you will be able to state the design-pattern and you will be immediately understood (given that, your co-worker know about the specific design-pattern).
2. Don't be afraid creating more than one internal classes
Another note, don't afraid to create multiple internal classes. Implement as much as possible, don't try to implement one internal class and mix responsibilities. Your class should be for a specific purpose, and should not do more than one thing (i.e responsibilities, if you are writing a class that is about transmitting data from your database to your application logic, should not - ideally - doing something else, like adding data to your database).
Consider learn more about Polymorphism, Inheritance, Encapsulation and Abstraction.
These four fundamental principles of Object Oriented Programming can also help you to learn how to structure your code object-oriented.
3. General Notes
As a Junior-Developer and not only as a Junior but as a Developer in general, you should always willing to learn from the more experience guys, by asking for feedback. Is not a shame is the law of learning and improve your code.
Another powerful source of learning, is books, consider buy some for the area you are interested in. (e.g Object Oriented Programming, Design Patterns etc).
As others noted in comments, this is really too broad and slightly opinionated, but big picture, use a class when:
You maintain state over time, and apply functions to this state.
You have a set of functions that share a common goal or deal with a common usage, data type or otherwise "obvious shared idea". That's particularly relevant when these functions can be reused in other places.
But really, to get a deeper understanding, get a book :-)
BTW, in C#, you can't put any functionality outside of a class, so the question should really be "how to divide my monolith class to smaller classes"

C# Project/task in which I could learn OOP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I had built several programs using C# like simple web browser with logic for addresses bar, status bar, some scripting. Simple program which I cannot explain it correctly in english, so instead of explaining I will tell pseudocode:
Get Values and Variables from CSV file which contains many Variables from old language
3x class for each specified variables to make list
From lists generate excel file
Simple games in unity 3D from tutorials and some other simple programs from tutorials.
And I'm looking for a project in which I will learn interfaces, abstract class, polymorphism, inheritance, encapsulation in a practical way. All the tutorials tells the theory of it, I can understand most of them but I couldn't imagine the usage of them.
http://www.codeproject.com/Articles/572738/Building-an-application-using-design-patterns-and?fid=1829944&df=90&mpp=25&prof=False&sort=Position&view=Normal&spc=Relaxed&fr=26#xx0xx
This article propably is good but there is no practical data, there isn't any items on which we could work. Therefor I cannot understand why we use interfaces etc.
I have found two tutorials:
https://www.youtube.com/watch?v=YxewTI4H2mY
youtube com/watch?v=QORB9qbsC8M
(sorry but without 10 reputation I cannot post more than 2 links)
Do you think that any of that Is a good way to learn OOP? Could you go to the last minutes of that programs and tell if that programs have good OOP code?
I love to hear any sugestions, help etc. By this time I have to say thanks to all of you who passed through this awful english question and try to answer me!
One concept that lends itself to Object orientation is any sort of database of hierarchical objects. My suggestion would be a zoo.
In a zoo, you can have a main abstract class Animal. This would have basic properties that any animal has, such as the name of the animal and its date of birth. Every animal needs to eat, so an abstract function like eat() would be appropriate.
Inheriting Animal, you can have for example abstract classes Reptile, Bird, Mammal, Insect
A reptile might then contain extra information that is only valid for a reptile.
Inheriting Reptile, you can have for example non-abstract classes Crocodile, Snake, Frog, etc.
A Crocodile could then have more properties and functions that only apply to a crocodile, such as DoDeathRoll().
For the actual animals in the zoo, you then create an instance of the lowest tier of classes. So Crocodile Humphrey = new Crocodile("Humphrey");
Regarding interfaces, you could consider interfaces such as Pettable, Flying (both birds and bats can fly, even though they don't share any other inheritance than Animal) to make functions such as ReactToPetting() or Fly() visible.
Creating a system like this will get you very much used to working with inheritance and polymorphism.

Why a class does need to implement an interface? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Soon I was writing code in .net framework, I needed a method but can't access that. After a search I have learnt to implement an interface first. I know that interfaces provide differentiation or polymorphism (i think). But why did .net framework want me to implement that interface? Why is it necessary?
That was a generic handler that needs IReadOnlySessionState,IRequiresSessionState interfaces for Session usage.
As TomTom said, because it was designed that way... why was it designed that way? here's the most likely answer, the answer why Interfaces are so usefull.
Taken from here
"An interface contains definitions for a group of related functionalities that a class or a struct can implement.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class."
In your case you are implementing multiple interfaces.
As for Polymorphism...
"A base class can also implement interface members by using virtual members. In that case, a derived class can change the interface behavior by overriding the virtual members. For more information about virtual members, see Polymorphism."

Is the lack of "objects" in Thrift awkward? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Note: I know the question title is suboptimal. Feel free to improve.
Thrift enables serialization as well as RPC. However, unlike systems like COM or CORBA or ZeroC ICE, ... it does not have the notion of a remote object or remote interface in a polymorphic way, therefore all services defined in a Thrift infrastructure are just collections of functions.
Thrift Features
Thrifts Non-Features state (interface?) polymorphism as a non-goal which is fair enough, but ...
As a programmer in languages that make natural use of objects in that I can have functions that return other objects (or interface-references), not just structs, this appears to be a bit awkward in that this would mean that all "object" functionality in a thrift service would have to be provided by functions additionally taking handles as input parameters to define what is being operated on -- a bit like doing OO in C :-)
Imagine a thrift service operating on files. It's interface would look much more like what C has (fopen etc.) than what we use today in C++, C# or possibly even Python.
Of course one could write additional wrappers in the target language, but you don't have any support from the Thrift framework, so that's what I'd call "awkward".
Phrasing it another way: Is dropping back to a purely procedural interface on the remote service level an issue?
To give this yet another twist: Even when I use the REST interface of, say, Jenkins, the URL based interface I have feels slightly "OO", as I access job objects by URL name and then specify the operations on them by GET parameters. That is, to me, it seems a string based REST approach can capture operations on resources (objects or interfaces if you like) much more naturally than a purely procedural interface. It is totally ok for Thrift to define that out of scope but it be good to know whether users find it a noticable thing.
This is a question to active Thrift users: Is the problem I describe above an actual problem in day to day use? Is it an observed problem at all?
Is this a general "problem" with SOA?
My impression is, that you mix concepts in an incorrect way and then try to draw conclusions from that.
RPC is nothing more than a remote procedure call. This means exactly that: Calling a remote piece of code, passing some arguments and getting some results. That's all. How to interpret these data is an entirely different thing.
In an OOP context, every method call (including RPC, but not limited to) is a procedure/function call with an additional hidden argument typically called this or Self. What really distinguishes an object from non-OOP code is the ability to do information hiding, derive classes and override methods, and some other nice stuff. Behind the scenes everything is just data, which becomes painfully obvious when you have to de/serialize your objects into e.g. a database - in most of the cases you will use an ORM of some kind for that task. An RPC mechanism is on an equivalent plane. What frameworks like COM or CORBA do behind the scenes is nothing else, they just hide it better from you.
At least with COM, you are not dealing with objects. You are interacting with interfaces, which are typically implemented as objects. It is hard to tell whether or not a particular interface is part of the object, or if it is added by aggregation or composition. Even the opposite can be true: It may be the case, that two otherwise unrelated interfaces may be implemented by the very same object instance for some reason. Interfaces have more in common with services than they have with objects.
SOA is not limited to RPC. For example, a REST-based interface is not considered RPC by a lot of people (although one can argue that point) and does not offer any objects that would deserve the name, yet you can do SOA with REST. And of course, SOA is also not limited to neither COM or CORBA environments, nor to SOAP or XML-RPC interfaces. SOA is primarily about services (hence the name), not objects. To put it into one sentence, RPC, OOP and SOA are different concepts, and comparing them to each other is what is called a category mistake.
How the server and client code represent your data depends on the system used and the traits of the target language. Don't let yourself be confused by the naming of the IDL entity - a struct in the IDL is not necessarily a struct in code. For example, using Thrift and C# as the target language, you get neat partial class-es generated from a struct, easily extendable with some manually written code. This may be different with another target language (say plain C or the Go language) and another system like Protobuf, Avro or the REST client of your choice.

Categories