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 7 years ago.
Improve this question
Thanks for your objectivity, especially where C# is your language of choice. Angry downvoters, I think I've asked a legitimate question here? Otherwise leave a constructive comment, please.
To the question...
C++ allows passing of (generic) function pointers simply, as follows: How to pass a generic function pointer as parameter
Java uses interfaces for this - also elegant from an OO perspective, we use nothing more than what the basic language already supplies.
However, I have never seen any real advantage to making delegate an explicit concept / keyword, as opposed to just managing the concept of callbacks the way that for example C++ or Java do -- by treating function pointers as just another circumstance under existing type system. (P.S. yes, C# generics are not the same as C++ generics, while Java has runtime rather than compile-time generics, but you get my drift).
(All hubris and dogma aside) Why did the designers of C# see fit to give a new name to a common, existing programming concept that could have been called a generic function pointer / callback? Could delegates not have been more simply represented in C#, without such a concept?
DISCLAIMER I've looked at quite a number of answers on stackoverflow and not one of them has satisfactorily answered why the designers saw fit to include another keyword for something so fundamental as callback handling.
C++ had "official" (non-Boost) "full" delegates from C++11 (std::function)... Before that, getting a pointer to a member function was always a little hackish... So I wouldn't consider C++ to be a good comparison :-) And C++ can overload the round parenthesis, so it is more easy to "hide" the hacks that need to be done and give to the programmer a "simple" way of using the std::function.
Now... Java... To "correct" (but let's say it wasn't an omission, but a calculated decision, so they didn't have anything to correct) the missing delegate concept they first had to introduce anonymous classes in Java 1.1 and then in Java 8 they introduced functional interfaces (as a non-Java programmer, I consider the last thing to be a little hackish... meta-describing that an interface has a single method and then enforcing it at compile time... I don't like it very much...). This because otherwise the boilerplate code that is needed is quite much...
Let's start simple... The IComparer<> interface... It is an interface with a single method, so it is very similar to a delegate...
a simple implementation:
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y)
{
return x.CompareTo(y);
}
}
There is a boilerplate row here, the first one (public class MyComparer : IComparer<int>). By introducing the C# delegate you already gained one row for each use of a delegate... But wait! Let's say that your "delegate" needs a reference to the class that "contains" it...
public class MyComparer : IComparer<int>
{
public MyClass Target;
public int Compare(int x, int y)
{
return Target.Ascending ? x.CompareTo(y) : y.CompareTo(x);
}
}
And now this class needs to be a nested class of MyClass. Note that I don't have anything against nested classes...
We have added a new line (public MyClass Target)... But this code is normally wrong to write... You shouldn't have public non-readonly fields. You could use an auto-property public MyClass Target { get; set; } but that too is synctactic sugar introduced in C# 3.0... without them the boilerplate code would grow... And I would prefer to have a private readonly MyClass Target.. But then I would have to add four lines for the constructor... How many lines do you want me to write for a delegate? :-)
And still C#/.NET delegates give more flexibility: the function you use can have any name, so you can have multiple of them in the same class... The MyComparer could have been implemented as two methods:
public int CompareAscending(int x, int y) {}
and
public int CompareDescending(int x, int y) {}
without adding too much code, or splitting everything in multiple (nested) classes.
Delegates are more than a simple callback. First, it works both for static methods and instance methods and the caller doesn't have to take care of the differences. Second, delegate is not a single method pointer. It can be a "pointer chain", so the caller can call many callbacks with a single call - and again, the caller doesn't have to bother wheter it is a single or multiple call.
Yes, one can implement the same mechanism from scratch - but one can build everything using machine code - what need for high level languages.
Related
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
I am learning java, and came to know that Java doesn't support multiple inheritance. So, java introduced interfaces for that. How does the problem of multiple inheritance is solved by interface?
What I read online : "Inheritance in java means code reuse".
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B. How does it use the code re-usability feature?
You haven't given proper citations for any of the assertions that you make in your Question, so it is impossible to know what they are actually saying ... or why you think that they are say these incorrect or misleading things.
I am learning java, and came to know that Java doesn't support multiple inheritance.
That is correct.
So, java introduced interfaces for that.
That is INCORRECT. Java introduced interfaces to support polymorphism. Specifically polymorphism that does not depend on class inheritance.
How does the problem of multiple inheritance is solved by interface?
It isn't.
Multiple inheritances are about inheritance of method and field declarations from multiple parent classes. Interfaces does not provide that, and it does not solve the problem.
Interfaces do allow you to declare a common API (or APIS) and implement that API without necessarily sharing code. But with careful design you can do code-sharing under the hood any; e.g. by using the Delegation design pattern.
What I read online : "Inheritance in java means code reuse".
I doubt that what it actually said. Anyway, it is INCORRECT.
Inheritance (of classes) is one way to achieve code reuse, but it is only one of many ways to achieve reuse. There are many others.
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B.
I presume that you mean something like this:
public interface I {
void someMethod();
}
public class A implements I {
void someMethod() {
// some code
}
}
public class B implements I {
void someMethod() {
// some code
}
}
How does it use the code re-usability feature?
There is no code reuse in that example. But this is not inheritance of classes (which I described as one way to achieve code reuse). It is a class implementing an interface.
(Now in Java 8, you can put code into interfaces in certain circumstances; read up on the default methods feature. And that does allow direct code reuse via an interface. But I doubt that is what the sources you have been looking at are talking about.)
Java solved the problem of multiple inheritance (or rather the problems that come with this feature) by allowing single inheritance, that is allowing only one super class. This design created a new problem of a class that needs to implement multiple contracts. a contract, like is explained in #Kermi's answer, allows other objects to refer to the same Object as different types, for various purposes, the most common one is for storing in Collections. an interface can be regarded as a super class that has no implementation (all the methods are pure virtual if you like)
So, Java removed the problems that come with multiple inheritance (the famous diamond problem) but also the advantages that come with it such as code reusability. This design follows the principal of making Java simple and easy and predictable by removing "advanced" (some say confusing) C++ features like multiple inheritance, operator overloading, pointer manipulation (among others).
There are several technics that allow Java to restore most of the code reusability of multiple inheritance. One such technic is composition: so if we take #Kermi's example, you can have a GeneralAnimal class that implements the most common behavior of an Animal. every Dog instance holds a reference to a GeneralAnimal instance (obtained through ctor or factory or dependency injection or ...) and can delegate some messages (=method calls) to that instance. The same is done in Cat instances and so on.
Interface doesn't resolve multiple inheritance problem or rather it doesn't create a multiple inheritance problem. It gives you a possibility to reuse existing implementations.
For example:
class Dog implements Comparable<Dog>, Animal
As your class implements 2 interfaces you can use them in difeerent ways. To use TreeSet object needs to implement Comparable methods (it is not the only possibility). When Dog is passed to TreeSet implementation of that structure is then sure that object has compareTo(Dog dog) method and can use it.
But than you want to store a List of Animals, and than iterate through that list with execution method declared for Animal, than you would not use Comparable interface, but Animal.
List<Animals> animals = new ArrayList<>();
animals.add(dog);
animals.add(cat);
for (Animal animal : animals) {
animal.walk();
}
Interface is a criterion, I think.
A and B should conform to it. In addition, A and B do different things such as ArrayList and LinkedList.
"Inheritance in java means code reuse" is right, but Interface is not. It embodies a norm.
When you learn Collections, you will understand it clearly.
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
Is there a Java recommendation or industry best-practice suggestion for including, or not including, the this parameter when it isn't explicitly necessary?
For instance, assuming there are no naming clashes between instance variables and local variables, is it preferential to use
this.someParam
or simply
someParam
and when calling methods that are in the same class is it preferential to use
this.someMethod()
or
someMethod()
The argument in favor of the former is that it makes the code more explicit. The argument in favor of the latter is that it makes the code cleaner.
I'm curious if there is any documentation out there that recommends one way or another (I can't find any, google searches with the word this are obviously tricky) or if it is simply a matter of preference.
On the merits of explicit versus cleaner: Excluding "this." is no doubt less text character "noise" (albeit small) in source file. The "this." explicitness would be helpful for example if using a small text viewer when looking at a method with many lines of code (should that be the case anyway?). So at best the explicitness has limited usefulness - especially as modern IDEs highlight instance variables. I am of the opinion of excluding "this." as code style.
I don't know that there is a "wrong" answer here. However, in my 15+ years writing Java, the convention that I have seen is to NOT include "this" unless it is necessary.
You can minimize confusion by naming variables in a consistent way. There are several good convention documents out there. Pick one and follow it. Some examples:
http://google-styleguide.googlecode.com/svn/trunk/javaguide.html
https://source.android.com/source/code-style.html
http://www.javaranch.com/style.jsp
There is no reason to prefer one or the other. It's a matter of opinion.
My opinion is that you should only use this if needed. There are some situations when you have to use this, such as if a local variable has the same name as an instance variable. It happens a lot in my constructors:
public MyClass(String s, int i) {
this.s = s;
this.i = i;
}
If you are working on a team, I recommend coming up with a strategy you all agree with, so you don't waste too much time reformatting each others code. Also, for me, it's pretty annoying to look at code that uses this too much (such as that generated by JD).
As for:
parameters/attributes - I always suggest using consistent approach throughout the code. In most cases all automatically generated getters and setters of Java classes need to use this to distinguish parameter name from actual object attribute. Consistency is then a good reason to use this for instance variables throughout the code. Sample setter which uses this to avoid ambiguity:
public void setName(String name) {
this.name = name;
}
methods - this.someMethod() is just longer than someMethod() and does not provide any benefit over the shorter someMethod(). If we call the latter, it is already known that we are in fact calling this.someMethod(). There is no ambiguity in calling just someMethod() like it is for parameters, so I would discourage the use of this.someMethod().
In my opinion, there is no common guidelines for all Java developers in the world defining good practices for using this. I'd rather follow the guidelines used in your company/project, or, if there are none, your own ways of writing well-read code.
There isn't a best-practice suggestion. Most teams simply have their own coding style.
Personally, I try to use use this for all my instance variables, but tend to avoid it for methods.
EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.
This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 9 years ago.
I was asked to answer this question:
Where should I put the Javadoc specific comment notation of /** and */
if I want to tell the user specifics about a certain instance variable
or method?
I answered with:
Above the function declaration.
The answer was rejected and this was the reason:
Functions are in non-object-oriented languages. Method is the proper name.
Is this true?
Are functions found only in non-object-oriented languages?
No. There are object-oriented languages that have functions. C#, for example, is an object-oriented language but it has anonymous functions.
What are the named procedures which are members of a type typically called in object-oriented languages like Java or C#?
Typically they are properly called methods, though this differs from language to language. In Java or C# I would say "method".
In Visual Basic, for example, the distiction is made between functions and subroutines on the basis of whether or not they return a value, not on the basis of whether they are associated with a type container.
JavaScript, an object-oriented language which uses prototype inheritance rather than class inheritance, typically refers to all of the above as "functions".
Do people frequently refer to methods as functions when speaking casually about Java or C#?
Yes. Were I writing documentation or a book or a scholarly article then I would be careful to make the distinction. In commonplace parlance though everyone reasonably conversant with the art of computer programming would understand "function" and "method" to be roughly synonyms. I would not have rejected your answer.
Any answer which limits this to a specific language is inherently flawed. In addition you must also deal effectively with static methods and subroutines.
Computer science began with the term 'subroutine'. Small sections of repeatable code which could be executed arbitrarily to perform a common action. Examples are found in early programming languages such as BASIC.
Functions were the evolution of subroutines. They take arguments and may or may not return a value. They take some concepts from maths - input, translated to a given output.
With objects we need to be able to call actions on objects and we do this be exposing methods. Like functions they take arguments and may or may not return a value.
Static methods are designed to act on all possible objects of a class.
The problem is that, pure object-orientated programming leaves no scope for the definition of functions (or indeed subroutines). And languages that evolve to become object orientated often retain syntax from functions to implement methods.
In Java we resort to using 'Utility' classes to provide functions as public static methods. The Math class in JavaScript is another example of this.
In PHP we tolerate the use of the word function to define methods.
In C++ we see both functions and methods, neither demarcated. Indeed, C++ makes no reference to methods, calling them member functions.
A function is not bound to a class.
A function is something like doStuff();.
A method is like someThing.doStuff(); or SomeClass.doStuff();.
In Java, there is no such thing as a function. They are all methods. i.e.
class Test {
public static void doSomething() {...}
public void otherThing() {...}
public static void main(String[] args) {
doSomething(); //implied Test.doSomething();
}
public Test() {
otherThing(); //implied this.otherThing();
}
}
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 5 years ago.
Improve this question
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends does.
So if you had a class like this:
public interface A {
public void methodInA();
}
And then you had a class like this:
public class B {
private composed A;
public B() {
// construct A within constructor
}
}
You would then be able to do this:
B myB = new B();
myB.methodInA();
Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:
#Overrides
public void methodInA(){
// B's own delegation method
}
Disadvantages include:
methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with extends
if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
probably 100 other things I've not thought of
Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.
Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.
Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:
public class Foo {
#Delegate(IBar.class)
private Bar bar;
// initialize bar via constructor or setter
}
Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:
public Baz method1(Qux val) {
return bar.method1(val);
}
As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.
Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.
I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA().
But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?
I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.
Check out what is called "Mixins" in some languages, and "Roles" in the Perl 5 Moose OO system.
There's also the difference between composition and aggregation to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?
Does the whole object graph become eligible for garbage collection or only the head of the graph?
A couple of the ORM mapping tools and frameworks over/around them provide for belongsTo or has-many relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.
Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.
Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits.
What you have suggested is in direct conflict with the principles of java.
Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes.