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 9 years ago.
Improve this question
I'm reading this book, and it's going over static typing, which, after reading the chapter a little bit, I understand as:
Static typing in OOP is defined as explicitly declaring the class an object is an instance of, so that it is predetermined (at compile time, before runtime i.e. Foo var).
The opposite of this is generic programming, where the actual id of the object is yet-to-be-determined (i.e. id var).
Something to keep in mind is that static typing is never necessary (straight from the book), it only improves readability, and eases the debugging process by showing what an object can and cannot do, what it can “see”.
Generic programming, however, is sometimes necessary for things like arrays, where you might need...And this is where I'm confused. Is it actually necessary?
I know that in Java you can enforce the type of objects contained in an array like: ArrayList<Double>, but in Objective-C, and I've done minimal research on this, there is no such method, and therefore, all NSArrays contain ids at compile time.
If this feature (strangely called generics, even though it's static typing and not generic typing), is unavailable in Objective-C, does that mean that generic programming is sometimes necessary?
Yes, generic typing is necessary whenever you need to write something that needs to operate on a number of types without knowing the type at compile time.
While objective-C doesn't contain generics per-se, Ids and void* are basically the same thing. You can write a method that takes in a void* or Id and do some processing on it. Before calling the method, you would do an explicit cast to a void* on the object you want to operate on.
Edit: For instance, what would you do if you wanted to write a method which makes a shallow copy of any typed object? You'd have to do something like copy(void* src,void* dest, int size). There is no way to do this without generics.
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 1 year ago.
Improve this question
As we now Google announced in 2017 first-class support for Kotlin.
But what does it change? Is there more documentation for new features written in Kotlin language?
How does it affect Java?
My another question:
Are Kotlin written aps generally faster?(on Android device)
EDIT: Guys I though this question is properly asked.. Don't vote me down
Java Issues Addressed by Kotlin
NullSafety — The Billion Dollar Mistake is the name given to the danger of null references in code. Kotlin’s type system is aimed at eliminating the danger of these null references. This has been one of the most common pitfalls in Java — and many other programming languages as well.
No more Raw Types — Kotlin is designed with Java interoperability in mind. So now, existing Java code can be called from Kotlin in an effective way. This allows the calling of Java code from Kotlin. Alternatively, Kotlin code can be used in Java rather smoothly.
Invariant Arrays — The basic types used in Kotlin are Numbers, Arrays, Characters, and Strings. Unlike Java, the arrays in this programming language are invariant, meaning that Kotlin does not let a user assign an Array to an Array. This prevents a possible Run time Failure, which is one of the issues faced in Java.
Function Types — In Kotlin, a lambda expression or an anonymous function can access the variables declared in the outer scope. That is opposed to Java’s SAM-conversions — Kotlin has proper function types.
Use-site Variance — Wildcard Types are one of the trickiest parts of Java’s Type System. This issue does not occur in Kotlin — as it does not have any Wildcard Types, just Type Projections and declaration-site variances.
Exceptions — Kotlin does not have any checked exceptions, as all exception classes in this language are the descendants of the class Throwable. And every exception has a message, stack trace, and an optional cause.
Why Choose Kotlin
Smart Casts
Working with the mixed types requires knowing the type of an object at the Run time in order to safely cast the object to the desired type — and, further, to call methods or access properties on it. For class casting in Java, we first check the type of the variable using the ‘instance of’ operator and then cast it to the target type.
Whereas in Kotlin, when we perform an ‘!is’ or ‘is’ check on a variable, the compiler tracks this information and will automatically cast the variable to the target type where is the ‘!is’ or ‘is’ check is true in the scope.
Singletons
Once in a while, a user needs to create an object of a slight modification of some class but without explicitly declaring a new subclass for it. Java handles this case with anonymous inner classes, but Kotlin generalizes the same concept by using object expressions and declarations. Just like the anonymous inner classes in Java, the code in object expressions can access variables from the enclosing scope. But in Kotlin, this is not restricted to final variables like in Java.
Data Classes
The whole purpose of creating classes is to hold data and in some classes — standard functionality with utility functions can be mechanically derived from that data. This is known as a Data Class in Kotlin. These classes generally contain some old boilerplate code in the form of toString(), hashcode(), equals(), setters, and getters.
Basically, Kotlin’s Data Classes are like regular classes but with some additional functionality.
NOTE: There are more things that have in Kotlin which help developers to write faster, consize and clean code
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.
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
This post may be considered to be inappropriate for stackoverflow, although I'm not trying to insult the Java language or anything like that. I enjoy coding in Java, but there is something regarding System.out.println that I have been wondering for quite a while.
Why is it that we are always forced to type System.out.println() or System.out.print() every time we want to print? Sure, we could make a void function to save time and energy in programs that we will have several print statements (which I sometimes do) like so:
public static void print(String output) {
System.out.print(output);
}
and then just call print (and if you want to really be thorough you can overload the function with arguments involving ints, doubles, chars, etc). But why is it that the Java language itself doesn't already allow us to print to the console by just writing print? Some languages (such as Python) make printing to console that neat and simple - so why doesn't Java?
Again - I'm not saying that the Java language is poorly designed, or trying to start a thread that is intended to bash Java. I'm sure the language designers had their reasons for designing it the way they did, and it would help me to understand why it is so. It would be much easier to just need to type print instead of System.out.print, so there must be reasons for why we must type System.out.print - I just can't figure out those reasons. I've tried googling for information on this issue and can't find anything relevant to the issue.
Please refrain from opinionated responses about the Java language - I want actual facts that explain this phenomenon.
Simply, Java doesn't have global functions.
Also, according to The Java Language Environment (a '90s book co-authored by James Gosling):
Java has no functions. Object-oriented programming supersedes functional and procedural styles. Mixing the two styles just leads to confusion and dilutes the purity of an object-oriented language. Anything you can do with a function you can do just as well by defining a class and creating methods for that class.
It's not to say that functions and procedures are inherently wrong. But given classes and methods, we're now down to only one way to express a given task. By eliminating functions, your job as a programmer is immensely simplified: you work only with classes and their methods.
So there is at least one language designer's reasoning.
You may shorten the call by statically importing System.out:
import static System.out;
class Example {
public static void main(String[] args) {
out.println("hello world!");
}
}
Since System.out is an object, its instance methods cannot be statically imported.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Its theoretical question. I've been told that casting objects is not a best to do. So we use generics to do avoid it.
1.But internally what happens?
2.Why its discouraged ?
3.Where is the internal implementation of it in Java.
Please explain with an example and also mention the methods / classes involved the process.
Will I be able to override its default implementation? ( Just curious, Hope its not silly )
Casting means slightly different things for primitive types and for reference types.
For primitive types, it can be used to convert a primitive of one type to another type, for example for narrowing primitive conversions.
For reference types, it means that you tell the compiler "I have a variable of some type A but I want you to skip your normal type checking and treat it as if it is of type B". Casting reference types does not do any kind of conversion. It circumvents the compiler's normal type checking. A type check will still be done, but at runtime instead of at compile time. If the object is not of the right type, you'll get a ClassCastException.
Why is it discouraged: Because it makes your program less type-safe. The type system is there to help you catch mistakes, and casting means you are deliberately skipping a type check, and risk getting a ClassCastException when you run your program.
The internal implementation: This is just part of what the Java compiler does. You cannot override how casts work, and that would also not be very useful. (Changing what a cast means would change the rules of the Java programming language).
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
On a project that I am working on, we are debating when to use get (getFoo) vs a normal name (foo) in java. When I look around in java core and guava, I see that there are many examples where get is omitted. Is there any doc that covers when guava or new java APIs will use the get prefix and when not to? Is there a convention these developers use here?
Thanks for taking the time to read this.
Examples:
ByteBuffer : http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#compact()
ForwardingObject : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ForwardingObject.html#delegate()
Stopwatch : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Stopwatch.html#elapsed(java.util.concurrent.TimeUnit)
Ticker : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Ticker.html#systemTicker()
EDIT:
As of http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf, "A Java Bean is a reusable software component that can be manipulated visually
in a builder tool." In our code base, the issue of get vs no get comes when the code has nothing to do with value or data objects (objects that represent data). When the class represents data, we are fine doing get.
My main question is why both java and guava choose to use non get methods for non data objects and what are their conventions.
The get prefix comes from the JavaBeans Conventions, which states that if you have an accessor for a property, then the accessor method's name must start with get, unless it is a boolean (the primative type), in which case is should start with is. Note that you use the get prefix to return type Boolean.
Throughout most of Java's API this is the convention that is used, which would be my recommendation as well. Your decision is up to you, but whichever convention you pick, I would suggest to be consistent and not mix the two.
While the idea of dropping the "get" appeals to me, the problem comes when you also have a setter. You would have to do something like
public String name(); // getter
and
public void name(String newName); // setter, xor use the below **instead** but not both
public Foo name(String newName); // if you prefer fluent/builder style
Which "looks weird" to a Java programmer. And until 1 minute ago I thought it was illegal, and my original post mistakenly said so until I tested it. You learn something everyday...
Added in response to #DwB
One good reason to use get/set is that many 3rd party frameworks expect this convention, as they use reflection to reason about your class. However, a framework could be able to look for combinations like the above, or be configured to use these methods instead of the usual get/set. This was almost in my original post but I haven't used Spring, Hibernate etc. in a few years so I'm not up to speed on what some of them will on won't allow if you aren't using get/set.
For example, Jackson can use annotations and mixins to define mappings, no need to follow get/set convention. I would think that Spring, JSF etc. could do likewise, (somebody please edit this answer with details as needed) though with some extra work. Whether this extra work is worth the "conciseness" of eliminating get/set is unclear. I'd say no, but YMMV.