Is Method Overloading considered polymorphism? [closed] - language-agnostic

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 4 years ago.
Improve this question
Is Method Overloading considered part of polymorphism?

There are different types of polymorphism:
overloading polymorphism (also called Ad-hoc polymorphism)
overriding polymorphism
So yes it is part of polymorphism.

"Polymorphism" is just a word and doesn't have a globally agreed-upon, precise definition. You will not be enlightened by either a "yes" or a "no" answer to your question because the difference will be in the chosen definition of "polymorphism" and not in the essence of method overloading as a feature of any particular language. You can see the evidence of that in most of the other answers here, each introducing its own definition and then evaluating the language feature against it.

Strictly speaking polymorphism, from wikipedia:
is the ability of one type, A, to appear as and be used like another type, B.
So, method overloading as such is not considered part of this definition polymorphism, as the overloads are defined as part of one type.
If you are talking about inclusion polymorphism (normally thought of as overriding), that is a different matter and then, yes it is considered to be part of polymorphism.
inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class.

There are 2 types of polymorphism.
static
dynamic.
Overloading is of type static polymorphism.. overriding comes under dynamic (or run-time) polymorphism..
ref. http://en.wikipedia.org/wiki/Polymorphism_(computer_science) which describes it more.

No, overloading is not. Maybe you refer to method overriding which is indeed part of polymorphism.
To further clarify, From the wikipedia:
Polymorphism is not the same as method
overloading or method overriding.1
Polymorphism is only concerned with
the application of specific
implementations to an interface or a
more generic base class.
So I'd say method overriding AND method overloading and convenient features of some language regarding polymorphism but notthe main concern of polymorphism (in object oriented programming) which only regards to the capability of an object to act as if it was another object in its hierarchy chain.

Method overriding or overloading is not polymorphism.
The right way to put it is that Polymorphism can be implemented using method overriding or overloading and using other ways as well.
In order to implement Polymorphism using method overriding, you can override the behaviour of a method in a sub-class.
In order to implement Polymorphism using method overloading, you need to write many methods with the same name and the same number of parameters but with different data types and implement different behavious in these methods. Now that is also polymorphism.
Other ways to implement polymorphism is operator overloading and implementing interfaces.

Wikipedia pedantics aside, one way to think about polymorphism is: the ability for a single line of code / single method call to do different things at runtime depending on the type of the object instance used to make the call.
Method overloading does not change behaviors at runtime. Overloading gives you more choices for argument lists on the same method name when you're writing and compiling the code, but when it's compiled the choice is fixed in code forever.
Not to be confused with method overriding, which is part of polymorphism.

It's a necessary evil that is and should only be used as a complement. In the end overloads should only convert and eventually forward to the main method. OverloDing is necessary because most vms for staticalky dispatched environments don't know how to convert one type to another so the parameter fits the target and this is where one uses overloads to help out.
StringBuilder
Append(String) // main
Append(Boolean) // converts and calls append(String)

Related

Whats the advantages and the disadvantages of curried functions [duplicate]

This question already has an answer here:
What are the practical advantages of currying?
(1 answer)
Closed 5 years ago.
I just know that it's it easy partial application and it's that it can (and does, for Haskell) simplify the syntax?
The main advantage is that it makes partial function application more convenient, and thereby encourages function composition.
One disadvantage is that it doesn't fit very well with a few other language features you might want, such as labeled, optional and variadic arguments. It's certainly not impossible to get it to work, OCaml for example has both labeled and optional arguments, but it gets quirky. How do you know when a function is partially applied, or fully applied and just not applying the optional argument? OCaml's solution is to assume partial application, and require functions to be "terminated" with a non-optional argument to be able to be fully applied without specifying all the optional arguments.
Another disadvantage pops up if the language is impure and has some form of type inference. It is then possible to partially apply a side-effectful function, discard the value without noticing that the type is incorrect, and thereby never have the side-effect occur. How prone a language is to mistakes like this depends on its type inference, but it's a fairly common beginner's mistake in a language such as OCaml. It can however be avoided by being a bit disciplined with type annotations.

Why does Swift make a distinction between designated and convenience initializer? [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
Swift does make a distinction between designated and convenience initializers. The documentation, however, never states why this distinction is made.
From a programmer's point of view, it seems like an extra burden: I have to think whether some initialization mechanism is "designated" or "convenience" and there are even some practical inconveniences like that I cannot call a convenience constructor of the super class which might sometimes be totally appropriate. There have to be some advantages of this concept in return. Otherwise Apple would not have introduced this feature. So what is the reason for introducing this distinction in Swift? A references to an official statements would nice.
The distinction between designated initializers and convenience initializers is not new — it's been part of the Cocoa environment for a long time. The reason for this convention is to ensure that all the internal state managed by a class is configured as intended before a subclass, or code external to the class, starts trying to use it.
Explicit initialization is one of the "safety" features of Swift. Using values before they're initialized can lead to undefined behavior (read: bugs) in C. If you declare a variable in Swift, it has to have a value. (Optionals let you fudge this a bit while still being explicit about it.) Making Cocoa's initializer chaining convention into a requirement is how Swift ensures initialization safety on top of class inheritance.
But don't take my word for it. < /LeVar> There's a great explanation of this in the series of Swift talks from WWDC — check the videos.
Totally agree on the practical inconvenience, not being able to call a convenience constructor of the super class is a total PITA...
Though I don't have any "official" answer, the conclusion I've reached is that calling a designated constructor is the only future proof way to do so.
Convenience constructors always have the possibility of being changed in future API-releases, so making the initialization of your class depend on one is highly unsafe, while the designated initializer is always going to work, no matter what changes the API is going to go through along the way...

Why should you ever have to care whether an object reference is an interface or a class?

I often seem to run into the discussion of whether or not to apply some sort of prefix/suffix convention to interface type names, typically adding "I" to the beginning of the name.
Personally I'm in the camp that advocates no prefix, but that's not what this question is about. Rather, it's about one of the arguments I often hear in that discussion:
You can no longer see at-a-glance
whether something is an interface or a
class.
The question that immediately pops up in my head is: apart from object creation, why should you ever have to care whether an object reference is a class or an interface?
I've tagged this question as language agnostic, but as has been pointed out it may not be. I contend that it is because while specific language implementation details may be interesting, I'd like to keep this on a conceptual level. In other words, I think that, conceptually, you'd never have to care whether an object reference is typed as a class or an interface but I'm not sure, hence the question.
This is not a discussion about IDEs and what they do or don't do when visualizing the different types; caring about the type of an object is certainly a necessity when browsing through code (packages/sources/whatever form). Nor is it a discussion about the pros or cons about either naming convention. I just can't seem to figure out in what scenario, other than object creation, you actually care about wether or not you're referencing a concrete type or an interface.
Most of the time, you probably don't care. But here are some instances that I can think of where you would. There are several, and it does vary a little bit by language. Some languages don't mind as much as others.
In the case of inversion of control (where someone PASSES you a parameter) you probably don't care if it's an interface or an object as far as calling its methods etc. But when dealing with types, it definitely can make a difference.
In managed languages such as .NET languages, interfaces can usually only inherit one interface, whereas a class can inherit one class but implement many interfaces. The order of classes vs interfaces may also matter in a class or interface declaration. So you need to know which is which when defining a new class or interface.
In Delphi / VCL, interfaces are reference counted and automatically collected, whereas classes must be explicitly freed, so lifecyle management on the whole is affected, not just the creation.
Interfaces may not be viable sources for class references.
Interfaces can be cast to compatible interfaces, but in many languages, they cannot be cast to compatible classes. Classes can be cast to either.
Interfaces may be passed to parameters of type IID, or IUnknown, whereas classes cannot (without a cast and a supporting interface).
An interface's implementation is unknown. Its input and output are defined, but the implementation which creates the output is abstracted. In general, ones attitude may be that when working with a class, one may know how the class works. But when working with an interface, no such assumption should be made. In a perfect world, it might make no difference. But in reality, this most certainly can have affect your design.
I agree with you (and thereby do not use an "I" prefix for interfaces). We shouldn't have to care whether it is an abstract class or an interface.
Worth noting that Java needs to have a notion of interface solely because it does not support multiple inheritance. Otherwise, "abstract class" concept would suffice (which may be "all" abstract, or partially abstract, or almost concrete and just 1 tiny bit abstract, whatever).
Things that concrete class can have and the interfaces can't:
Constructors
Instance fields
Static methods and static fields
So if you use the convention of starting all interface names with 'I' then it indicates to the user of your library that the particular type will not have any of the above mentioned things.
But personally I feel that this is not a reason enough to start all interface names with 'I'. The modern IDEs are powerful enough to indicate if some type is an interface. Also it hides the true meaning of an interface name: imagine if Runnable and List interfaces were named IRunnable and IList repectively.
When a class is used, I can make the assumption that I will get objects from a relatively small and almost well-defined range of subclasses. That's because subclassing is - or at least it should be
- a decision that isn't made too easily, especially in languages that don't support multiple inheritance. In contrast, interfaces can be implemented by any class, and the implementation can be added later to any class.
So the information is useful, especially when browsing through code, and trying to get a feeling what the code author intended to do - but I think it should be enough, if the IDE shows interfaces/classes as distinctive icons.
You want to see at a glance which are the "interfaces" and which are the "concrete classes" so that you can focus your attention to the abstractions in the design instead of the details.
Good designs are based on abstractions - if you know and understand them you understand the system without knowing any of the details. So you know you can skip the classes without the I prefix, and focus on the ones that do have it while you are understanding the code, and you also know to avoid building new code around non-interface classes without having to refer to some other design document.
I agree that the I* naming convention is just not appropriate for modern OO languages, but truth is this question isn't really language agnostic. There are legitimate cases where you have an interface not for any architectural reason but because you simply don't have an implementation or have access to an implementation. For these cases you can read I* as *Stub or similar, and, in these cases, it might make sense to have an IBlah and a Blah class
These days, though, you rarely come up against this, and in modern OO languages when you say Interface you actually mean Interface not just I don't have the code for this. So there is no need for the I*, and in fact it encourages really bad OO design as you won't get the natural naming conflicts that would tell you something's gone wrong in your architecture. Say you had a List and an IList... what's the difference? when would you use one over the other? if you wanted to implement IList would you be constrained (conceptually at least) by what List does? I'll tell you what... if I found both an IBlah and a Blah class in any of my codebases I would purge one at random and take away that person's commit privileges.
Interfaces don't have fields, hence when you use IDisposable (or whatever), you know you're only declaring what you can do. That seems to me the main point of it.
Distinguishing between interfaces and classes may be useful, anywhere the type is referenced, in the IDE or out, to determine:
Can I make a new implementation of this type?
Can I implement this interface in a language that does not support multiple inheritance of implementation classes (e.g., Java).
Can there be multiple implementations of this type?
Can I easily mock this interface in an arbitrary mocking framework?
It is worth noting that UML distinguishes between interfaces and implementation classes. In addition, the "I" prefix is used in the examples in "The Unified Modeling Language User Guide" by the three amigos Booch, Jacobson and Rumbaugh. (Incidentally, this also provides an example why IDE syntax coloring alone is not sufficient to distinguish in all contexts.)
You should care, because :
An interface with capital "I" enables one, namely you or your co-workers to use any implementation which implements the interface. If in the future you figure out a better way to do something, say a better list sorting algorithm, you will be stuck with having the change ALL of the invoking methods as well.
It helps in understanding code - e.g. you don't need to memorize all 10 implementations of say, I_SortableList , you just care that it sorts a list (or something like that). Your code becomes practically self-documenting here.
To complete the discussion, here is a pseudocode example illustrating the above:
//Pseudocode - define implementations of ISortableList
Class SortList1 : ISortableLIst, SortList2:IsortableList, SortList3:IsortableList
//PseudoCode - the interface way
void Populate(ISortableList list, int[] nums)
{
list.set(nums)
}
//PseudoCode - the "i dont care way"
void Populate2( SortList1 list, int[] nums )
{
list.set(nums)
}
...
//Pseudocode - create instances
SortList1 list1 = new SortList1();
SortList2 list2 = new SortList2();
SortList3 list3 = new SortList3();
//Invoke Populate() - The "interface way"
Populate(list1,nums);//OK, list1 is ISortableList implementation
Populate(list2,nums);//OK, list2 is ISortableList implementation
Populate(list3,nums);//OK, list3 is ISortableList implementation
//Invoke Populate2() - the "I don't care way"
Populate(list1,nums);//OK, list1 is an instance of SortList1
Populate(list2,nums);//Not OK, list2 is not of required argument type, won't compile
Populate(list3,nums);//the same as above
Hope this helps,
Jas.

Should we avoid to use Object as the input parameter/ output value of a method?

Take Java syntax as an example, though the question itself is language independent. If the following snippet takes an object MyAbstractEmailTemplate as input argument in the method setTemplate, the class MyGateway will then become tightly-coupled with the object MyAbstractEmailTemplate, which lessens the re-usability of the class MyGateway.
A compromise is to use dependency-injection to ease the instantiation of MyAbstractEmailTemplate. This might solve the coupling problem
to some extent, but the interface is still rigid, hardly providing enough flexibility to
other developers/ applications.
So if we only use primitive data type (or even plain XML in web service) as the input/ output of a method, it seems the coupling problem no longer exists. So what do you think?
public class MyGateway {
protected MyAbstractEmailTemplate template;
public void setTemplate(MyAbstractEmailTemplate template) {
this.template = template;
}
}
It's pretty difficult to understand what you are really asking, but going the route of typing everything to Object does not lead to loose coupling because you can't do anything with the input without downcasting, which would break the Liskov Substituion Principle.
Taken to the extreme it leads you here:
public class MyClass
{
public object Invoke(object obj);
}
This is not loose coupling, it's just obscure and hard-to-maintain code.
The name MyAbstractEmailTemplate makes me believe that you are talking about an abstract class.
You should always program against interfaces, so instead of having MyGateway depend on MyAbstractEmailTemplate, it should depend on an EmailTemplate interface, where MyAbstractEmailTemplate implements EmailTemplate. Then, you can pass your custom implementations around as you want to, without further tight coupling.
Combine this with DI and you've got yourself a pretty decent solution.
Not exactly sure what you mean with "the interface is still rigid", but obviously you should design your interface in such a way that it provides the functionality you need.
MyGateway has to assume something about the inputs. Even if it used XML, it would have to assume something about the structure and content of the XML. Coupling isn't an evil in its own right; expresses the contract between two pieces of code. The oft-repeated advice to avoid tight coupling is really just saying that coupling should express the essence of a contract, not more and not less. Passing a specific type (particularly an interface type) is a very good way to achieve this balance.
The first problem you will run into is that a lot of types are simply not representable by a primitive data type (It's a Java problem that there are primitive types at all.).
The coupling should be reduced by using a proper inheritance hierarchy. What means proper? The method should take exactly that part of the interface as a parameter that is need. Not more not less.
After all you won't be able to avoid dependencies. Methods have to know about what they can do with their input or have to able to make assumptions (see C++ concepts) about the capabilities of the input.
IMHO there is nothing inherently wrong in using objects (wth small cap, not Objects) as method parameters and/or class members. Yes, these create dependencies. You can manage this in (at least) two ways:
acknowledge that by creating this dependency, the two classes become tightly coupled. This is entirely appropriate in many cases, where two (or more) classes in fact form a component, which is a meaningful unit of reuse in itself, and its parts may not make much sense or be interchangeable.
if there are multiple interchangeable candidates for a method parameter, these are obvious candidates to form a class hierarchy. Then you program for the interface and can pass any object of any class implementing that interface as parameter to your method. Note that the phrase "there are multiple interchangeable candidates for a method parameter" is a loose rephrasing of the Liskov Substitution Principle, which is the foundation of polymorphism.
in some languages, e.g. C++, the third way would be using templates. Then you need no common interface, only specific methods/members need to resolvable when the template is instantiated. However, since instantiation happens at compile time, this is entirely static binding.
sThe problem is I would say, that the best java can offer are interfaces and people start to see that they are too rigid. It would be interesting to use something like what is in Go language, that allows flexible checking for all methods of an interface to be present in the type, you do not have to be explicit about implementing some interface. We also need something better than interfaces to specify the constraints - maybe some sort of contracts. Another thing is the interface evolution.

When to make a method static? [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.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'd like to know how people decide whether to define a method as static. I'm aware that a method can only be defined as static if it doesn't require access to instance fields. So let's say we have a method that does not access instance fields, do you always define such a method as static, or only if you need to call it statically (without a reference to an instance).
Perhaps another way of asking the same question is whether you use static or non-static as the default?
I use static methods whenever I can. Advantages:
When calling a static method from inside an instance method, you can be sure that there are no side-effects on the state of the current object.
From inside a static method, you can be sure you don't accidentally modify any state of the object instance.
You can use a static method from outside the class without constructing an instance. If it was possible to make the method static, it clearly doesn't need an instance, so there's no need to require one.
Static methods may be slightly more efficient because no "this" pointer needs to be passed, and no dynamic dispatch is necessary.
Kevin Bourrillion wrote an insightful answer on this topic some time ago (admittedly from a Java perspective, but I think it's applicable to other languages too).
He argues that you should basically only use static methods for pure functions.
A "pure function" is any method which does not modify any state and whose
result depends on nothing but the
parameters provided to it. So, for
example, any function that performs
I/O (directly or indirectly) is not a
pure function, but Math.sqrt(), of
course, is.
I tend to agree. (Although in my own code, traditionally, I've probably used way too many static helper methods all over the place... :-P And this surely has made code that uses those methods harder to test.)
If what the method does depend solely on its arguments, you can make it static. If the method does not instantiate any other of your user defined classes, you can make it static. The default, though, is to have it as non-static.
Use static methods when you are performing operations that do not operate on instances of the class.
A perfect example would be a sqrt method of a Math class.
It depends. In languages where non-member functions are possible I'd say that most of the time, if the method could be made static, it should be made a non-member function instead, non-friend if possible. You can tell I have a mostly C++ background.
In "pure" OO languages where non-member functions are not possible it would depend on whether the method is only "incidentally" static (i.e. it just happens not to need access to instance members), or is truly logically static - it is a method of the whole class instead of for a particular instance.
Non static by default, static when I need the functionality to be available from at least two different classes, and I don't want to waste a constructor.
ps. Archimedes rules!
(C#) By default, I use static methods in static classes and non-static methods in non-static classes.
As I elaborate a class, I find myself naturally converging on making it entirely static or entirely non-static. Practially speaking, if I start wanting to define static members within a non-static class, I often find that it will eventually make the most sense to break those out into a separate static class -- either a utility class like Math or a global application class (like .NET's ConfigurationManager).
From an object-oriented perspective, a method is doing something to/with an object. So if you're using an instantiated object, it makes the most sense to me to think of that object's methods as non-static. Technically, you technically can make a non-static class have static members if they don't require access to an instance. But ostensibly, at least, a class's methods would still be doing something to/with that class, so I would still make them non-static. All things being equal, that is.
in context of python -
staticmethod are basically a normal function, we keep in the class only because of some logical reasons. classmethod takes 'class' as a first argument, default method takes instance aka self as a first argument but staticmethod does not takes any any argument.