I thought only functions had return statements since they were explicitly called whereas methods are implicitly called on the class. However, I have seen examples of code where a method has a return statement. Is this conventional? Also, am I wrong in saying that only functions return values, and are methods having return statements a standard convention across multiple languages of only OOP languages?
A method is a function that is associated with an object (or class). So yes, they can return values, or not.
Also - trying things out yourself and/or reading documentation is a much better way to learn than asking us as soon as you get stuck! ;)
Here is Oracle's documentation for defining methods.
I think this is problems of theory. Let me put clear some points.
Before OOP
procedures was a bits of programs for do someting
functions was a bits of programs for do someting and return values, like Math f(x) = x*y+E2
After OOP
procedures and functions are called methods and is equal if they return or not some value.
PD: Also we have methods:
with firm: function A(b,x) { ... }
without firm: function A() { ... }
anoimate: function () { ... }
The post contains incorrect assumptions. For starters Java only has "methods (in this context), even if static. Given this it is trivially true that methods at large in Java can return a value.
Now, as an example1, for an equivalency with a language like VB.NET (which derives from BASIC),
A method that returns a value is a "Function Procedure" (BASIC lingo) - these methods return a value and can then be used as an appropriately-typed expression. They must contain a return statement on all possible code-execution paths.
A method that has a void return type is a "Sub Procedure" (BASIC lingo) - these methods do not (and cannot) return a value. Such methods may only be called as statements.
1 The terms "function", "procedure", and "subroutine", eg, are highly dependent upon language/context which is why the above is prefaced. As such, correct Java-terminology dictates using "methods [returning some value upon completion]" and "void methods" to describe the difference - although I find that "function" is still used colloquially (in my circles) when describing the operation of "computing a value without side effects" or when such is supplied as a higher-order argument (eg. lambdas).
Methods can have return statements as long as the return type is not void. When you define the method, you can make the method public or private, static or not static, choose the return type (byte, short, int, long, float, double, boolean, char), name the method, and define the inputs.
`public static returnType methodName(input) {
// body
}`
Related
In Java, a method could be defined as following:
Object m(boolean b) {
if (b) {
return "123";
} else {
return new Integer(123);
}
}
In this case, the return value of m could be either String or Integer in runtime. So is there any way to get all possible run time return types of a method in static time?
For this particular method, yes. Just call it with true and false and check the return value with getClass(). For a general case, no.
Generally you wouldn't need to either. Thanks to Java's strong typing and generics, the type of the return value should never be a huge surprise.
Returning multiple different types as shown in your example should be avoided, and in cases where it's useful/necessary (such as factory pattern) it should be irrelevant to the caller.
If you know the implementation of the method, yes. You know all the types it could return because you can read the code and tell for yourself what they are.
But, programmatically? For any method, in general? No, you can't do that, not at run-time. This is why it's very important to write good, sensical method signatures with meaningful return-types. Returning Object is seldom the best idea. When you say that your method returns Object, the contract of that method is that literally anything is allowed to come out of it. There's nothing wrong with that, but that's the most specific thing you can say about a method if all you know is its signature.
I just read Bloch's Effective Java and there was one section talking about an "identity function" in the Generics chapter.
public interface UnaryFunction<T> {
T apply(T arg);
}
// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION = new UnaryFunction<Object>() {
public Object apply(Object arg) { return arg; }
};
// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types.
#SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY_FUNCTION;
}
I already read "Why is it safe to suppress this unchecked warning?" and the answers explain the unchecked warning question, but leave me totally unhappy with the concept of the "identity function" when it seems the identity function has nothing to do with identities.
Bloch just assumes I know what it is, but in the implementation he uses to illustrate it, it has nothing to do with identity or identities.
I checked it out on wikipedia: Identity Function # wikipedia but the pure theoretical description of it tells me nothing about what it has got to do with identities either.
I searched on google, and some people refer to the .equals() and .hashCode() methods as identity functions which makes a bit of sense, but of course their implementation is completely different from Bloch's method which returns the input parameter untouched. What does that have to do with identity?
Other people talked about database functions as identity functions, giving a new ID on each call, which makes more sense as well, but is obviously very limited in scope.
An identity function, in the context of the code in your question, is simply a function that returns the same argument passed to it :
In math you can denote it as:
f(x) = x
Identity functions are similar to other "identity" concepts, i.e. an operation that effectively does nothing.
As an example: in math you have identity matrices which if multiplied with a vector/matrix result in the same vector/matrix as if the multiplication never happend.
The same applied to an identity function: it returns the parameter as is and effectively does nothing when it comes to logic. It's as if the function never had been called - as I said from a logic point of view, you might still see some technical impact, e.g. a few instructions being executed.
Just curious is there any technical limitation in having multiple return values for methods in languages like java, c, c++ or limitation is just by spec? In assembly language I understand callee can pop one value to register.
Because in the days of C there is/was a single register used to hold the return value.
Because if you need more values, you can just return a struct, reference (in Java/C#), or pointer.
Because you can use an out parameter.
Allowing multiple return values would add complexity, and it's simply worked around. There's no reason for it to be there. (Indeed, in C++ you can return a tuple (from TR1, C++11, or boost) which effectively is multiple return values)
Its by design, because there is no need to allow multiple values in return statement. You can always define a struct with all the needed members, and create an instance of the struct and return it. Simple!
Example,
struct Person
{
std::string Name;
int Age;
std::string Qualification;
//...
};
Person GetInfo()
{
Person person;
//fill person's members ...
return person;
}
You can use std::pair, std::vector, std::map, std::list and so on. In C++0x, you can use std::tuple as well.
If the Genie gave you only one wish, you could just wish to have any number of wishes. It's the same with just one return value from a method. You can use your return value as a pointer to an address where an object full of attributes resides and then query those attributes (properties)... This way there really is no limitation. :-)
Fun coding and many happy returns :-)
It's just a decision and because people are used to it. In principle there wouldn't be anything preventing a language designer from implementing a syntax like this:
(int, int, int) call(int x, int y, int z);
and a function call could look like this:
(a, b, c) = call(1, 2, 3);
or whatever syntax they would choose for this task. Though one could discuss if it would add to readability. And as others have pointed out, some languages implement this by tuples or similar constructs.
Sure, the return statement:
(int, int, int) call(int x, int y, int z);
{
return x+1, y+1, z+1
}
You could even think of useful applications like:
(err, filehandle) = OpenFileDialog(...)
where the function can return either a detailed error code or a valid file handle. Though exceptions take this place nowadays. But exceptions are in some sense a way to return at least two alternating values, either the requested function return value or the raised exception.
Because good programming languages encourage programmers to do the right thing. If a method needs to return multiple values, those values probably are related, and thus should be group together in something like a struc.
Just my 2 cents.
It's mostly due to historical reasons having to do with machine calling conventions. Also because C doesn't have a pattern matching syntax on the callee side to retrieve the results. Note that languages like ML or Haskell have a syntactically lightweight tuple type that is perfectly usable for returning multiple values.
Edited:
Actually thinking about it a little bit, I guess if you wanted to split hairs, ML and Haskell still have a "single" return value. It's just that tuples are so lightweight syntactically that it's convenient to think about functions returning multiple values rather than a single tuple.
To be totally rigorous, there are two languages that I can think of that have "proper" multiple-values returns that are not just tuples in some shape. One is Scheme, (c.f call-with-values), and the other is MATLAB:
function [x,y] = myFunc(a, b)
...
end
[p, q] = myFunc(3,4)
In both of these languages, there is a special syntactic distinction between a single value that happens to be an aggregate (cons cell, array, respectively) and multiple values.
It's just a decision made by the language and/or ABI designers. No more, no less. In assembly language, you can make those decisions yourself, though - I'm not sure what your last comment means.
We don't need the ability to return multiple values built into the C++ language, because the library works just fine:
std::tuple<int,float> func()
{
return std::make_tuple(1, 2.f);
}
int i;
float f;
std::tie(i, f) = func();
Most other languages have similar functionality in their standard library.
Actually, there are at least 2 ways to return multiple values.
First is to return create a struct or class, put all the return data, and return it.
second is to pass parameters by reference (non-const) and put the values in there.
It is useful to support this, and given how people find it convenient in other languages, C and Java may move that way too.
C++ is already standardising on the kind of convenient, intuitive handling of return values familiar from e.g. Ruby and python for the function-caller side, which is more important than at the return itself, because a single function is likely called from a great many call sites.
Specifically, the C++17 paper here (see also wording here) documents a notation...
auto [x,y,z] = expression;
...where expression can be a function returning - or any other expression evaluating to - an array, a tuple, or a struct with all public members. The above can be preceded by const to make the local variables const.
The feature also documents this...
for (const auto& [key,value] : mymap)
...
...which avoids repeated use of the less-expressive ->first and ->second.
With C++ moving in this direction, it's likely C and other C-derived languages will look carefully at doing likewise.
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.
As part of developing a small ScriptEngine, I reflectively call java methods. A call by the script engine gives me the object the method name and an array of arguments. To call the method I tried to resolve it with a call to Class.getMethod(name, argument types).
This however only works when the classes of the arguments and the classes expected by the Method are the same.
Object o1 = new Object();
Object out = System.out;
//Works as System.out.println(Object) is defined
Method ms = out.getClass().getMethod("println",o1.getClass());
Object o2 = new Integer(4);
//Does not work as System.out.println(Integer) is not defined
Method mo = out.getClass().getMethod("println",o2.getClass());
I would like to know if there is a "simple" way to get the right method, if possible with the closest fit for the argument types, or if I have to implement this myself.
Closest fit would be:
Object o1 = new Integer(1);
Object o2 = new String("");
getMethod(name, o1.getClass())//println(Object)
getMethod(name, o2.getClass())//println(String)
Update:
To clarify what I need:
The Script Engine is a small project I write in my free time so there are no strikt rules I have to follow. So I thought that selecting methods called from the Engine the same way the java compiler selects methods at compile time only with the dynamic type and not the static type of the Object would work.(with or without autoboxing)
This is what I first hoped that the Class.getMethod() would solve. But the Class.getMethod() requires the exact same Classes as argument types as the Method declares, using a subclass will result in a no such method Exception. This may happen for good reasons, but makes the method useless for me, as I don't know in advance which argument types would fit.
An alternate would be to call Class.getMethods() and iterate through the returned array and try to find a fitting method. This would however be complicated if I don't just want to take the first "good" method which I come across, so I hoped that there would be an existing solution which at least handles:
closest fit: If arg.getClass() ==
subclass and methods m(Superclass),
m(Subclass) then call m(Subclass)
variable arguments:
System.out.printf(String ,String...)
Support for autoboxing would be nice, too.
If a call cannot be resolved it may throw an exception ( ma(String,Object), ma(Object, String), args= String,String)
(If you made it till here, thanks for taking the time to read it:-))
As others have pointed out there is no standard method that does this, so you are going to have to implement your own overload resolution algorithm.
It would probably make sense to follow javac's overload resolution rules as closely as possible:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#292575
You can probably ignore generics for a dynamically-typed scripting language, but you might still benefit from the bridge methods that the compiler generates automatically.
Some pitfalls to watch out for:
Class.isAssignableFrom does not know about automatic widening primitive conversions, because these are syntactic sugar implemented in the compiler; They do not occur in the VM or class hierarchy. e.g. int.class.isAssignableFrom(short.class) returns false.
Similarly Class.isAssignableFrom does not know about auto-boxing. Integer.class.isAssignableFrom(int.class) returns false.
Class.isInstance and Class.cast take an Object as an argument; You cannot pass primitive values to them. They also return an Object, so they cannot be used for unboxing ((int) new Integer(42) is legal in Java source but int.class.cast(new Integer(42)) throws an exception.)
I would suggest that you use getMethods(). It returns an array of all public methods (Method[]).
The most important thing here is:
"If the class declares multiple public member methods with the same parameter types, they are all included in the returned array."
What you will then need to do is to use the results in this array to determine which one of them (if any) are the closest match. Since what the closest match should be depends very much on your requirements and specific application, it does make sense to code it yourself.
Sample code illustrating one approach of how you might go about doing this:
public Method getMethod(String methodName, Class<?> clasz)
{
try
{
Method[] methods = clasz.getMethods();
for (Method method : methods)
{
if (methodName.equals(method.getName()))
{
Class<?>[] params = method.getParameterTypes();
if (params.length == 1)
{
Class<?> param = params[0];
if ((param == int.class) || (param == float.class) || (param == float.class))
{
//method.invoke(object, value);
return method;
}
else if (param.isAssignableFrom(Number.class))
{
return method;
}
//else if (...)
//{
// ...
//}
}
}
}
}
catch (Exception e)
{
//some handling
}
return null;
}
In this example, the getMethod(String, Class<?>) method will return a method that with only one parameter which is an int, float, double, or a superclass of Number.
This is a rudimentary implementation - It returns the first method that fits the bill. You would need to extend it to create a list of all methods that match, and then sort them according to some sort of criteria, and return the best matching method.
You can then take it even further by creating the more general getMethod(String, Class<?>) method, to handle more of the possible "close match" scenarios, and possibly even more than one paramter
HTH
Edit: As #finnw has pointed out, be careful when using Class#isAssignableFrom(Class<?> cls), due to its limitations, as I have in my sample code, testing the primitives separately from the Number objects.
AFAIK, there is no simple way to do this kind of thing. Certainly, there's nothing in the standard Java class libraries to do this.
The problem is that there is no single "right" answer. You need to consider all of your use-cases, decide what the "right method" should be and implement your reflection code accordingly.