When is a Java subroutine not a method? - java

I came across this during learning Java in the beginning, but I am learning top down, so I would like some direction:
This was on a Java tutorial relatively early on:
As one final general note, you should be aware that subroutines in Java are often referred to as methods. Generally, the term "method" means a subroutine that is contained in a class or in an object. Since this is true of every subroutine in Java, every subroutine in Java is a method (with one very technical exception). The same is not true for other programming languages. Nevertheless, the term "method" is mostly used in the context of object-oriented programming, and until we start doing real object-oriented programming in Chapter 5, I will prefer to use the more general term, "subroutine." However, I should note that some people prefer to use the term "method" from the beginning.
My question is what is that "one very technical exception." Since I am learning multiple stack technologies, I would like to know this specific exception he is referring to. It comes from this tutorial :
http://math.hws.edu/javanotes/c2/

Quoting from chapter 5 of the tutorial you linked to:
Constructors are subroutines, but they are subroutines of a special
type. They are certainly not instance methods, since they don't belong
to objects. Since they are responsible for creating objects, they
exist before any objects have been created. They are more like static
member subroutines, but they are not and cannot be declared to be
static. In fact, according to the Java language specification, they
are technically not members of the class at all! In particular,
constructors are not referred to as "methods."

Class constructors are not methods.

Related

Wondering about Microstream class StorageConfiguration

there are two questions with microstream database and its class StorageConfiguration:
1) What ist the difference of the methods New() and Builder() and the DEFAULT construct?
2) Why the methods are writting uppercased? That does not seem to be Java naming convention.
Thanks for any answers!
I am the MicroStream lead developer and I can gladly answer those questions.
To 1)
"New" is a "static factory method" for the type itself.
"Builder" is a static factory method for a "builder" instance of the type.
Both terms can be perfectly googled for more information about them.
A quick service as a starting point:
"static factory method":
https://www.baeldung.com/java-constructors-vs-static-factory-methods
"builder pattern":
https://en.wikipedia.org/wiki/Builder_pattern
--
To your actually second question, about the "DEFAULT" construct:
If I may, there is no "DEFAULT" construct, but "Default".
(Conventions are important ... mostly. See below.)
"Default" is simply the default implementation (= class) of the interface StorageConfiguration.
Building a software architecture directly in classes quickly turns out to be too rigid and thus bad design. Referencing and instantiating classes directly creates a lot of hardcoded dependencies to one single implementation that can't be changed or made more flexible later on. Inheritance is actually only very rarely flexible enough to be a solution for arising architecture flexibility problems. Interfaces, on the other hand, only define a type and the actual class implementing it hardly matters and can even be easily interchangeable. For example, by only designing via interfaces, every instance can easily be "wrapped" by any desired logic via using the decorator pattern. E.g. adding a logging aspect to a type.
There is a good article with an anecdote about James Gosling (the inventor of Java) named "Why extends is evil" that describes this:
https://www.javaworld.com/article/2073649/why-extends-is-evil.html
So:
"Default" is just the default class implementing the interface it is nested in. It makes sense to name such a class "Default", doesn't it? There can be other classes next to it, like "Wrapper" or "LazyInitializing" or "Dummy" or "Randomizing" or whatever.
This design pattern is used in the entire code of MicroStream, giving it an incredibly flexible and powerful architecture. For example:
With a single line of code, every part of MicroStream (every single "gear" in the machine) can be replaced by a custom implementation. One that does things differently (maybe better?) or fixes a bug without even needing a new MicroStream version. Or one that adds logging or customized exception handling or that introduces object communication where there normally is none. Maybe directly with the application logic (but at your own risk!). Anything is possible, at least inside the boundaries of the interfaces.
Thinking in interfaces might be confusing in the beginning (which is why a lot of developers "burn mark" interfaces with a counterproductive "I" prefix. It hurts me every time I see that), but THEY are the actual design types in Java. Classes are only their implementation vehicles and next to irrelevant on the design level.
--
To 2)
I think a more fitting term for "static factory method" is "pseudo constructor". It is a method that acts as a public API constructor for that type, but it isn't an actual constructor. Following the argumentation about the design advantages of such constructor-encapsulating static methods, the question about the best, consistent naming pattern arose to me. The JDK gives some horribly bad examples that should not be copied. Like "of" or "get". Those names hardly carry the meaning of the method's purpose.
It should be as short but still as descriptive as possible. "create" or "build" would be okay, but are they really the best option? "new" would be best, but ironically, that is a keyword associated with the constructors that should be hidden from public API. "neW" or "nEw" would look extremely ugly and would be cumbersome to type. But what about "New"? Yes, it's not strictly Java naming conventions. But there already is one type of methods that does is an exception to the general naming rule. Which one? Constructors! It's not "new person(...") but "new Person(...)". A method beginning with a capital letter. Since the beginning of Java. So if the static method should take the place of a constructor, wouldn't it be quite logical and a very good signal to apply that same exception ... or ... "extension" of the naming convention to that, too? So ... "New" it is. Perfectly short, perfectly clear. Also not longer and VERY similar to the original constructors. "Person.New" instead of "new Person".
The "naming convention extension" that fits BOTH naming exceptions alike is: "every static method that starts with a capital letter is guaranteed to return a new instance of that type." Not a cached one. Always a new one. (this can be sometime crucial to guarantee the correctness of algorithms.)
This also has some neat side effects. For example:
The pseudo-constructor method for creating a new instance of
"StorageConfigurationBuilder" can be "StorageConfiguration.Builder()".
It is self-explaining, simple, clear.
Or if there is a method "public static Vector Normalized(Vector v)", it implicitely
tells that the passed instance will not be changed, but a new instance will
be returned for the normalized vector value. It's like having the
option to give constructors proper names all of a sudden. Instead of
a sea of different "Vector(...)" methods and having to rely on the
JavaDoc to indirectly explain their meaning, the explanation is right
there in the name. "New(...)", "Normalized(...)", "Copy(...)" etc.
AND it also plays along very nicely with the nested-Default-class
pattern: No need to write "new StorageConfiguration.Default()" (which
would be bad because too hardcoded, anyway), but just
"StorageConfiguration.New" suffices. It will internally create and
return a new "StorageConfiguration.Default" instance. And should that
internal logic ever change, it won't even be noticable by the API
user.
Why do I do that if no one else does?
If one thinks about it, that cannot be a valid argument. I stick VERY closely to standards and conventions as far as they make sense. They do about 99% of the time, but if they contain a problem (like forbidding a static method to be called "new") or lacking a perfectly reasonable feature (like PersonBuilder b = Person.Builder()" or choosing properly speaking names for constructors), then, after careful thought, I br... extend them as needed. This is called innovation. If no one else had that insight so far, bad for them, not for me. The question is not why an inventor creates an improvment, but why no one else has done it so far. If there is an obvious possibility for improvement, it can't be a valid reason not to do it just because no one else did it. Such a thinking causes stagnation and death of progress. Like locking oneself in a 1970ies data storing technology for over 40 years instead of just doing the obviously easier, faster, direct, better way.
I suggest to see the capital letter method naming extension as a testimony to innovation: If a new idea objectively brings considerably more advantages than disadvantages, it should - or almost MUST - be done.
I hereby invite everyone to adopt it.

Aren't classes in Java equivalent to structures in c

I just started learning java yesterday since i want to make android apps. So far i only know c. I am reading a book called "Head first java" and it keeps talking about object and classes which are pretty new to me. I just have one question and if someone can clarify this for me that'd be very helpful:
What is/are the difference(s) between classes(java) and structures(c)?
ps: I'd also love if you can recommend me a book that really is for absolute beginners because the book i'm reading right now doesn't have enough details for those that are completely new to object oriented programming. Thank you.
No. You don't get inheritance, methods, abstract methods, polymorphism, and many more object oriented concepts with Structs.
You can try to make C conform to object oriented behavior using structs, but that's different from using an object oriented language.
"Aren't classes in Java equivalent to structures in c?"
Short answer, No.
My answer is too short cause the differences is the difference between two completely different paradigms, and it needs a complete book (not even a chapter) like : "Thinking in java".
Java classes perform several roles, only one of which is (implicitly) defining the layout of the data structure called the instance of that class, but you are right in thinking that objects are essentially data structures, just like instances of struct.
The main difference is that C's struct is something much more raw and "close to the metal" than a Java class. Basically, with much additional framework code and strict adherence to many conventions you could reimplement a good part of Java's objects, but the syntax would not be as clean as in Java.
There are many other differences, such as what exactly is covered by compiler's static checking, automatic memory management, etc. In the end, differences outweigh similarities, but as a point of understanding, it is not wrong to compare Java objects with C structs.
I know, that I am contradicting the view of a lot of people here, but you are right, a class really is nothing more or less than a struct with a lot of bells and whistles.
To be precise, the C++ language actually specifies that an instance of a class without virtual functions and/or virtual inheritance has the same memory layout as a C struct with the same data members in the same order.
All that is added to the struct to provide runtime polymorphism is a single v-table pointer, which is used to look up the virtual members. Inheritance is generated by including the base class structures as data members of the child class struct.
Of course, when you think about it for a second, you realize that classes must be implemented with structs, one way or another. C++/Java classes must be implemented somehow, after all. And it helps to remind yourself that object orientation is not primarily a language feature, it is a paradigm that can be used in any imperative programming language. It can be used in Java, in C++, in C, in Pascal, in Fortran, and even in assembler. All which the so-called object oriented languages add, is syntactic sugar to handle all the technical stuff of object orientation.
Nevertheless, it is important to learn all the bells and whistles when you start working in C++ or Java.

Is there member initialization list syntax in Java like C++?

I am a Java programmer who is currently reading GoF book on design patterns where examples are given in C++ and Smalltalk syntax . I came across a particular syntax in C++ which I found out to be called member initialization list . From the answers given it seems like using member initialization list is a good practice(much more efficient) than using assignments for member variables .Is there something similar in Java ? If not then there should be a good reason why Java designers didn't incorporate this feature . What are your thoughts on the same ?
The reasons why it's necessary in C++ thankfully don't apply to Java.
Fields are only references or primitives so you don't need to worry that you're constructing the field objects and performing assignment operations on them.
Java allows assignment of final fields exactly once in constructor bodies (though the specification of this is quite verbose).
No, you need to initialize members in their declaration, the constructor(s), or in an initialization method called from constructors.
(Assuming the members need initialization beyond their default values.)

Scala closures compared to Java innerclasses -> final VS var

I've first asked this question about the use of final with anonymous inner classes in Java:
Why do we use final keyword with anonymous inner classes?
I'm actually reading the Scala book of Martin Odersky. It seems Scala simplifies a lot of Java code, but for Scala closures I could notice a significant difference.
While in Java we "simulate" closures with an anonymous inner class, capturing a final variable (which will be copied to live on the heap instead of the stack) , it seems in Scala we can create a closure which can capture a val, but also a var, and thus update it in the closure call!
So it is like we can use a Java anonymous innerclass without the final keyword!
I've not finished reading the book, but for now i didn't find enough information on this language design choice.
Can someone tell me why Martin Odersky, who really seems to take care of function's side effects, choose closures to be able to capture both val and var, instead of only val?
What are the benefits and drawbacks of Java and Scala implementations?
Thanks
Related question:
With Scala closures, when do captured variables start to live on the JVM heap?
An object can be seen a bag of closures that share access to the same environment and that environment is usually mutable. So why make closures generated from anonymous functions less powerful?
Also, other languages with mutable variables and anonymous functions work the same way. Principle of lease astonishment. Java is actually WEIRD in not allowing mutable variables to be captured by inner classes.
And sometimes they're just darn useful. For example a self modifying thunk to create your own variant of lazy or future processing.
Downsides? They have all the downsides of shared mutable state.
Here are some benefits and drawbacks.
There is a principle in language design that the cost of something should be apparent to the programmer. (I first saw this in Holt's Design and Definition of the Turing Language, but I forget the name he gave it.) Two things that look the same should cost the same. Two local vars should have similar costs. This is in Java's favour. Two local vars in Java are implemented the same and so cost the same regardless of whether one of them is mentioned in an inner class. Another point in Java's favour is that in most cases the captured variable is indeed final, so there is little cost to the programmer to be prevented from capturing nonfinal local vars. Also the insistence on final simplifies the compiler, since it means that all local variables are stack variables.
There is another principle of language design that says be orthogonal. If a val can be captured why not a var. As long as there is a sensible interpretation, why put in restrictions. When languages are not orthogonal enough, they seems perverse. On the other-hand, languages that have too much orthogonality may have complex (and hence buggy and/or late and/or few) implementations. For example Algol 68 had orthogonality in spades, but implementing it was not easy, meaning few implementations and little uptake. Pascal (designed at about the same time) had all sorts of inelegant restrictions that made writing compilers easier. The result was lots of implementations and lots of uptake.

static methods make Java a pseudo functional language?

I've been mulling about a post by Misko Hevery that static methods in Java are a death to testability. I don't want to discuss the testability issue but more on the concept of static methods. Why do people hate it so much?
It's true that we don't have closures (but we have a slightly awkward anonymous functions), lambdas & functions as first class objects. In a way, I think static methods can be used to mimic functions as first class objects.
One characteristic of functional programming is immutability of data. static does imply that you don't need an object (instance) representing state, so that's not a bad start. You do however have state on the class level, but you can make this final. Since (static) methods aren't first-class functions at all, you will still need ugly constructions like anonymous classes to approach a certain style of functional programming in Java.
FP is best done in an functional language, since it has the necessary language support for things like higher-order functions, immutability, referential transparency and so on.
However, this does not mean that you can't program in a functional style in an imperative language like Java. Other examples can be given as well. It's not because you are programming in Java that you are doing OOP. You can program with global data and unstructured control flows (goto) in a structured language as C++. I can do OOP in a functional language like Scheme. Etc.
Steve McConnell mentions the difference of programming in a language versus programming into a language in Code Complete (also a very popular reference on SO).
So, in short, if you say that "static methods mimic first-class functions", I do not agree.
If, however, and I think that this was more the point you were trying to get across, you would say that "static methods can help for programming in a functional style in Java", I agree.
Static methods make testing hard because they can't be replaced, it's as simple as that.
How can static methods "mimic" functions as first class objects1? Arguably they're worse than anything else on this front. You can "mimic" functions as first class objects by creating single-method interfaces, and indeed Google's Java Collections does exactly this in a number of places (for predicates, projections etc). That can't be done with static methods - there's no way (other than with reflection) to pass the concept of "when you want to apply a function, use this method.
No, I can't see how static methods help here. They discourage state-changing (as the only state available is the global state and any mutable state passed in via the parameters) but they don't help on the "functions as first class objects" side.
C# has better support for this (with lambda expressions and delegates) but even that's not as general as it might be. (Compare it with F#, for example.)
1 As of Java 8, method references will allow methods to be converted to instances of appropriate single-method interfaces, which will make all of this more relevant. Back in 2009 that was a long way off though...
Functional != function, and for the record I will claim that a method != function...
Java is a statically typed, object oriented language. Java has also maintained a relative purity in that manner but it's no where near a functional language.
While it's true that you can mimic the behavior of functional programming with imperative programming you're never gonna get that tidy syntax which you'll wanna have for lambda calculus. In a way, if the language doesn't support proper lambda calculus it's not a functional programming language.
C++ has functions, but C++ also have classes. C++ therefore have two type of functions, member functions and functions. When you say method you mean a member function. Because the method is invoked on an instance of an object. But when you say static method you mean just function (in the C/C++ sense). This is just a vocabulary for referring to elements of your code. And in Java code can not exist outside a class, a method would imply that it belongs to some class i.e. type.
So far nothing of what I've said relates to functional programming but I think you get the point where you wrong.
I suggest you look at pure functional programming languages such as Haskell or Erlang. Because functional programming languages generally don't have closers either.
Your claim that static methods can be used to mimic functions as first class objects sounds really bizarre to me. It sounds more like a dynamic programming language than functional programming.
My biggest objection against static methods is that they are not polymorphic and that they are not used in an object-oriented way, instead one has to you the class (not an object) to access them.
If you only use static methods then you are programming in a procedural, non-object-oriented style.
However, the only context I can think of where this would be OK is during the first programming lessons before object orientation is introduced.
In Java, you can't give a function as an argument to another function.
In a functional language, if you have a function
def addOne(i) = i + 1
you can pass that to another function that eg applies it to all elements of a list.
In Java, with
public static int addOne(int i) { return i + 1; }
there is no way to do that.

Categories