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();
}
}
Related
We know that a lambda expression can refer to and use static instance variables, instance variables and local variables( if they are effectively final). All this seems ok. Whenever I see any session on Lambdas and Java's take on functional programming I see one common point which is "Writing concurrent code is tough and so adapting functional code helps".
However if I can access Static and instance variables in a lambda does this not defeat this point altogether. I know we have parallel streams which are very helpful in certain concurrent case but still is the closure scope not broken in Java if we are going towards functional programming style.
Also we should be creating pure functions in a functional style of programming. However if I am dependent on the state of the instance then my function is not pure.
I might be incorrect in inferring what I have shared but if I am then was there a particular reason to allow these design principles.
public class UsingStaticVariables {
static int staticTest = 10;
public static void main(String args[]) {
staticTest++;
System.out.println("Static test first value is " + staticTest);
Supplier<Integer> supplier = () -> {return staticTest++; };
staticTest++;
System.out.println("Static test second value is " + staticTest);
System.out.println("Static Test lambda output is " + supplier.get());
}
}
if I can access Static and instance variables in a lambda does this
not defeat this point altogether[?]
The ability for lambdas to access static and instance variables does not make the whole feature fail at providing an approach to functional programming. Only when lambdas actually do access such data is pure functional programming violated.
But also, it sounds like you may be working from a false premise. Lambdas provide for more convenient representations of higher-order functions than Java previously had, but there is no reason to take that as a sign of Java moving toward being a pure functional language. I am confident that that will never happen.
I know we have parallel streams
which are very helpful in certain concurrent case but still is the
closure scope not broken in Java if we are going towards functional
programming style.
Nothing requires you to make your lambdas touch anything they cannot reach via their arguments. And avoiding that is a very good idea in lambdas that are going to be shared between threads, but even that doesn't protect you from all the intricacies of multithreaded programming.
Java supports -- even more so nowadays -- multiple programming paradigms and mixed programming paradigms. This is generally a good thing for programmers, which is probably why a lot of programming languages seem to move in that direction, regardless of where they start.
[W]as there a particular reason to allow these design principles[?]
The motivation for most of Java language and standard library development has pretty much always been to make the language easier to use in a variety of ways, for as many programming tasks as possible. Lambdas seem to have been motivated much more by a desire to reduce the importance of anonymous inner classes than by any ideal of providing better support for functional programming style. The FP angle largely comes along for the ride, though the standard library does seem to have really latched on to that.
From this blog:
I’ve been programming in Java for over 16 years and teaching it for nearly half that time. So it’s going to take a little practice to stop repeating this sentence: “Interfaces may only contain methods that are public and abstract.” As of Java 8, that statement is no longer true. It is now possible to add both instance and static methods to Java interfaces.
Does new C# version allow this also or will in some intended future?
I always felt Interface was good in theory but in practice caused many kind of maintenance nightmare on your interface consumers as described in the article.
Update : I'm also interested by the critics, all the more if you have read the author's article especially about abstract class alternative as not solving real world problem.
It is to the implementing class in C# to determine the scope of the method or property implemented. C# knows implicit and explicit interface implementation, which helps to set the scope of the method. (You can create a secondary method or property that has the wanted scope (internal, private, protected).
Static interface methods are not possible in C# and I wonder why you would want that. Static methods are bound to the type and not to the instance, so you can't call this.StaticMethod for example. That makes defining them on interfaces useless.
And default methods are just... horrible. Make an abstract class. Period.
I'm a beginner/intermediate programmer going from Java to C# and has been doing a little reading on functions on codeproject.com. My understanding is that namespace in C# is equivalent to packages in java. Using a namespace is the same as importing a package, though it's possible to have nested namespace. Classes exist within namespaces, and methods exist within classes. But I read somewhere that functions are class independent? Are functions not methods then? Does that mean that in C#, you can define functions outside of classes within namespaces, and can use them like methods in a class once you import a namespace? In practical usage, say if I'm trying to write a Math Library, would it be better to write functions or static methods? Are there any difference in terms of usage between the two?
As you can tell, I'm also a little mixed-up on the actual definition of a function. Is it a property (mathematical property where each input has single output) that any code can have? If yes, does that mean static methods are also functions (as long as it doesn't depend on a variable outside its scope)? Is it a special type of method/routine defined with delegate/other syntax that can be passed as parameters and assigned to variables? Responses to the question on stack overflow difference between methods and functions seems to differ quite a bit, and the accepted answer is different from the top results from googling.
I realize there are multiple questions, but they are seem interrelated (at least to me). All these definitions are bouncing around my poor head, and anything that clarifies the concept or correct my misconception would be a great help. Explanations with examples would be amazing, since I'm having trouble with the terminology. Thank you.
Let's keep it simple. No matter what the definition of functions, in C# or Java you have:
A package or a namespace which can only contain classes; not functions, nor methods.
Within a Class you have methods which would serve as functions, in the sense that they receive parameters and may output results.
You can have static methods, either in Java or C#. These methods are Class dependent, not object dependent, meaning they are called directly from a class without an object instance.
There are also entities called lambda expressions. These are objects which are defined as functions. These are used in functional programming.
And that's pretty much it. There are no functions defined directly from packages or namespaces, as there are no packages within packages nor namespaces within namespaces.
For a Math library, you may define a public Math class with all its functions, or in our case, static methods. Thus you would call: Math.sin(..), Mas.cos(...), and so on.
Note that lambda expressions serve a purpose of making some areas of programming easier, such as: SQL expressions in code, filtering collections, and so on.
Finally note that lambda expressions should not be confused with methods which belong to a class. I would suggest a nice reading from MSDN called Lambda Expressions. This reading would ease the understanding of such a nice, but dense topic.
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.
In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods