Differences in separation of static and stateful code in different languages - java

I've noticed that Java, Python, Perl, and Haskell/Clojure have distinctively different treatment of static functions. In particular,
1) What are the idiomatic differences in the way static functions are implemented and utilized in different languages.
2) Do some of these languages have "more complete" separation and support of static vs statefull methods than others?
For example :
In clojure, all functions are, essentially, static - allowing for extreme modular composability , not associated with any thing in the object-ether. Clojure-functional programming can be described to java programmers as similar to static functions.
Meanwhile, in traditional idiomatic Java, there is often a mixture, where object-oriented features maintain internal state, relying on external static methods for certain, often stateless transformational operations.
Then, there is the scripting world : I've noticed in Perl and Python that the concepts of differentiating static vs stateful code are not stressed quite as much (UPDATE:As per comment - maybe this is due to the multi-paradigm nature).
And finally, we have the object-oriented breed of PHP-5 developers, who seem to code similarly to java developers in its their treatment of static vs stateful (object scoped) functions.
Any other insights into the differences in how different programmers, from different backgrounds, treat static functionality would really help me to review code with a few PHP/Perl developers that I work with.

The relevant distinction may be the programming paradigm emphasized by language. Functional languages such as Haskell & Clojure aim to eliminate side effects and emphasize determinism; encapsulating mutability or state in thinks like monads. This is in contrast to Imperative languages. Perl & PHP are multi-paradigm languages, so it is possible to implement imperative styles such as procedural and object oriented coding, or even emulate functional styles.
In collaborating with imperative programmers it might be worth focusing on loose coupling and side effect free design patterns such as Dependency Injection.

Related

Does the Android Framework utilize Imperative or Object Oriented design?

I know that Java is mostly object oriented language since you can do things like encapsulation, inheritance, and run-time polymorphism.
But when I watch a lot of talks on youtube about RxJava they say under Android you work with imperative rules? Does this relate to the life-cycle methods?
When I work with POJO's isn't that Object Oriented? Does this have to with how we handle data through our architecture layers? I'm getting confused with all these 'paradigms' and 'styles' especially since RxAndroid is getting thrown into the mix with 'functional-reactive' style.
First of all: Android is an operating system, not a programming language. That language is mainly object oriented, but lately a lot of effort is going into making java more suitable for functional programming. Frameworks such as RxJava emphasize that, too.
Of course, there are different programming models that can be used on the Android platform.
Coming from there: there is simply no sense in assuming that this large, complex environment can be reduced to some simple, always correct single word description. It is a combination of many different aspects.
Or as the US citizens say: in pluribus unum.
Android itself is a platform, not a language, so the question contains a category mistake.
In general, the only way this kind of question can be definitively answered is by resort to fundamental definitions. These were stated by Peter Wegner in 1987 in the paper 'Dimensions of Object-based Language Design'.
Wegner provides the following definitions:
Object-based: a language is object-based if it supports objects as a language feature.
Class-based: an object-based language is class-based (classical) if every object has a class.
Object-oriented: an object-based language is object-oriented if its objects belong to classes and class hierarchies can be incrementally designed by an inheritance mechanism.
I think you've got it a little bit wrong.
Java is an imperative language. You'd be better to ask what the difference between declarative vs imperative programming, or the difference between object oriented and functional programming.
Here is a great article on imperative vs declarative:
https://tylermcginnis.com/imperative-vs-declarative-programming/
Here is a stack overflow answer explaining the difference between object oriented and functional:
Functional programming vs Object Oriented programming
Android provides a framework written in java. Android isn't a language, but Java is. Java is an object oriented language.
I hope that clears things up a bit.
Some people say that Java is more like a hybrid, taking this piece from this article:
That said, Java is not a pure Object-Oriented language. Someone said Java is a hybrid, which, IMO, is an accurate description. I would posit Java is a dirty hybrid of an OO language. Consider:
String s = string2.trim();
First, since "String" is immutable, the above code reeks of functional programming. The "trim()" operation should cause the whitespace to be trimmed off both ends of "string2", without needing reassignment. That is to say, operations should act on the data as close to the object as possible. This, to me, makes Java feel dirty (it also leads to tightly-coupled systems due to the prevalence of "get" accessor methods, but that's another topic entirely). Ahem, what? That example is perfectly OO. Object-orientation does not make mutable state necessary. Actually, since strings are passed around so often, the lack of mutator methods really just saves a lot of headache.
Second, Java cannot alter the behaviour of all messages. It mixes the types of "operations" available to objects, depending on their type. The "+" is equally applicable to ints as it is Strings, but not to Matrices, or Colors. This isn't so bad, because you can do matrix.add( matrix ), but serves to illustrate the point about Java being 'dirty' (or 'impure', if you prefer).
Lastly, it is a hybrid to provide performance gains. Even though Smalltalk has an advanced virtual machine, its inability (when I was using it) to provide a machine-correlated bytecode for integer math placed a significant performance impact on its entire environment. Being a hybrid, Java cannot be called a true Object-Oriented language. But then, why does it matter?Use the right tool for the job and life will be happy!*
So:
You can work all like procedural programming if you want, and not use anything of OOP, but also, is not pure OOP programming, because not everything in Java is an object.
Also:
Java8 introduces some concepts about Functional programming, one of them is the use of lambdas.
In resume, Java is imperative, OOP and functional language(dep on version).

Which Java language mechanisms allow code reuse and minimize ripple effects?

The questions asks:
Recount all of the java lenguage mechanisms that
(a) Facilitate code reuse, and
(b) Minimize ripple effects due to requirements
changes.
I am not sure if I am understanding this correctly. For (a) I thought it would be Composition, Association and Inheritance, and for (b) I thought it would be Encapsulation and Polymorphism; but I'm not sure if this is what the question asks and I am not sure if I am missing another mechanism. Also I am not sure about what the question mean by "Java language mechanisms" ?
Can someone help me to clarify this, my book really does not do a good job of explaining this.
In my opinion, composition and association aren't Java language mechanisms, they're related to OOP as a concept.
But Interfaces, Abstract classes and Generics are.
Regarding ripple effect, I would go with this definition:
http://www.javapractices.com/topic/TopicAction.do?Id=123
Constants, private fields (Encapsulation) and again Interfaces/Abstract classes (Polymorphism).
A) Methods, Classes and Inheritance. These are the pure language mechanisms. I wouldn't say composition and association are real mechanisms, they are concepts of oop in general and not associated with the java language.
B) Named Constants instead of magic numbers, minimizing visibility. There is no real polymorphism in java as there is in c++ for example. But using Interfaces as references is a really good idea, as the implementations are easily replaceable. It also allows you to make your code more configurable using the factory pattern or even Dependency Injection. This problem and the advantages of using interfaces is well explained in this article.
Again, polymorphism and encapsulation are oop concepts and not associated directly with the java language.

Is Java orthogonal?

I am wondering if Java is orthogonal or not, and if yes, then which are its features that make it orthogonal. How can you determine if a language is orthogonal or not? For example, I found on some website that C++ is not orthogonal, but no explanations, why not. What other languages are orthogonal? Please help me, because there is almost no information on the internet about this topic.
Thanks
The Art of UNIX Programming, Chapter 4. Modularity, Orthogonality, Page 89:
Orthogonality
Orthogonality is one of the most
important properties that can help
make even complex designs compact. In
a purely orthogonal design, operations
do not have side effects; each action
(whether it's an API call, a macro
invocation, or a language operation)
changes just one thing without
affecting others. There is one and
only one way to change each property
of whatever system you are
controlling.
Programming Language Pragmatics, Chapter 6, Page 228:
Orthogonality means that features can
be used in any combination, that the
combinations all make sense, and that
the meaning of a given feature is
consistent, regardless of the other
features with which it is combined.
On Lisp, 5.2 Orthogonality:
An orthogonal language is one in which
you can express a lot by combining a
small number of operators in a lot of
different ways.
I think an orthogonal programming language would be one where each of its features have minimal or no side effects, so they can be used without thinking about how that usage will affect other features. I borrow this from the definition of an orthogonal API.
In Java you'd have to evaluate for example if there is a combination of keywords/constructs that could affect each other when used simultaneously on an identifier. For example when applying public and static to a method, they do not interfere with each other, so these two are orthogonal (no side effects besides what the keyword is intended to do)
You'd have to do that to all its features to prove the orthogonality. That is one way to go about it. I do not think there exists a clear cut is or is not orthogonal in this matter either.
Using the term orthogonal programming language is unusual. Typically, in computer science you are really talking about orthogonal instruction-sets. However, if we are to extend the meaning to the grammar of a language:
"...meaning [the language] has a relatively small number of basic constructs and a set of rules for combining those constructs. Every construct has a type associated with it and there are no restrictions on those types...." see ALGOL
Then we can assume that if not all instructions in the language can work on all datatypes will yield non-orthogonality. This however does not mean that the converse is true, that is to say if all language instructions do work on all data types, it does not necessarily mean that the language is orthogonal.
More formally, an orthogonal language would have exactly ONE way to do a given operation. Non-orthogonal languages would have more than one way to achieve the same effect.
Simplest example:
for loop; vs. while loop;
for and while are non-orthogonal.
Orthogonality is feature of your design independent of the language. Sure some language make it easier for you to have an orthogonal design for your system but you shouldn't focus on a specific language to keep your system's design as orthogonal as possible.
Orthogonality is not really a language feature as such, even though some languages have features that promote orthogonality (such as annotations, built-in AOP, ..). Regarding orthogonality in Java: I have written a little case study about this using log4j as example: "Orthogonality By Example" - you might find this useful.
Lack of Orthogonality in C:
An array can contain any data type except void
Parameters are passed by value but array are passed by reference
A programming language is consider orthogonal if:
there is a relatively small set of primitive constructs that can combine in a relatively small number of ways to build data and control structures
every possible structure is legal
For example a language with 4 primitive data types (Int, Float, Double, Char) and two
type operators (Array and Pointer) can create a relatively large number of data structures.
So the advantage of orthogonality is to make the language simple and regular because there are less exceptions.

Any example in which Clojure really shines against Java which is not concurrency/immutability-feature related?

I can perfectly see why Clojure is really good for concurrent programming. I can see the advantages of FP also in this regard.
But clearly, not every line of code that we write is part of a thread or needs concurrent access. For those parts of the code (the more simple and sequential piece of code) what is it that Java really missed that Clojure provided?
Were features like Multimethods, Dynamic binding, Destructuring bind really missed in Java?
I supposed my question can also be framed as:
If Clojure did not have the
Concurrency features that it had and
the whole Immutability/Mutability
issue was not of our concern, then
what other features Clojure provides
that would make you use it instead of
Java ?
Were features like Multimethods, Dynamic binding, Destructuring bind really missed in Java?
Yes. Also...
First-class functions. Delicious first-class functions. This isn't just an FP thing. There's a good reason people are clamoring for closures in Java 7.
Code-is-data. This is the benefit of any Lisp. Lisp code isn't just blobs of text you feed into the mouth of a compiler and never see again, it's structures of lists and vectors and symbols and literals that you can manipulate progammatically. This leads to powerful macros and first-class Symbols and lots of other goodies. It leads to a highly extensible and powerful language.
Clojure has better control and looping constructs and the ability to create your own via macros and first-class functions. Java has for and foreach and while (and didn't even have foreach for years). Clojure has map, filter, reduce, mapcat, lots of do forms, lots of if and when forms, list comprehensions via for, and so on. If these didn't exist, you could write them yourself. In Java you get to wait a decade for a committee to (maybe) approve such features.
Minus those dealing with static typing, all of the features set for Java 7, Clojure either already has or could have trivially. "Automatic resource management", Clojure has as with-open. "Language support for collections", Clojure (and Ruby, Perl, Python...) has already. "Strings in switch", Clojure has more powerful case-like constructs like condp, and whatever else you can think up. You could write any of these yourself in a dozen lines of Clojure.
Concise syntax for lists, maps, arrays, sets, sorted sets, sorted maps etc. and nearly interchangeable use of them all thanks to the seq abstraction. Literal support for regexes, characters, anonymous functions, etc.
Java has mandatory checked exceptions, which are annoying; Clojure doesn't.
Java syntax is verbose and irregular. Clojure syntax is concise and regular. Even Java written in Clojure is often more concise than Java written in Java thanks to macros like -> and doto, and constructs like proxy and (soon) reify.
Java code has too much mandatory boilerplate and endless repetition. public static void main(String[] args){...} etc. Clojure has next to none of this boilerplate, while sacrificing little to nothing in terms of expressiveness or power. Even other statically typed languages today seem to be going the way of type inference. There's good reason you need a bulky Java-centric IDE to write and endlessly "refactor" Java code; writing it by hand would drive you insane and wear your fingers down to nubs.
In Java everything is a class or interface, whether it should be or not, which is a cause of unnecessary complexity. There are many programs that have to be mangled beyond recognition to fit into an OOP style. Clojure lets you avoid this. A nice rant to this effect. Clojure focuses largely on verbs.
Interactive programming via REPL is fun. Compile/run/debug cycles are not. Clojure still compiles to .class files if you want it; in the meantime you can sit in the middle of your code and tinker freely while it's running.
Clojure's metadata and sane equality testing are enjoyable to work with. As are its auto-promotion of int to long to Bigint, native handling of rational numbers, and so on.
Dynamic typing leads to shorter, more generic thus more reusable thus more powerful code than static typing. (This is a highly debatable point, obviously, so I put it last.)
The popularity of Scala and Groovy and JRuby and Jython and endless other JVM-languages-that-aren't-Java should be seen as a good indication that while the JVM is good, Java-the-language is unpleasant for many people.
Brian has summarized it really well. Here is something that really impressed me. (From the book Programming Clojure by Stuart Halloway)
Java code, from the Apache Commons:
public class StringUtils {
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
}
Here is a similar implementation in Clojure:
(defn blank? [s] (every? #(Character/isWhitespace %) s))
Well for one there is generally a lot less "ceremony" in Clojure. Languages like Python and Ruby have this advantage over Java as well (thus the popularity of JRuby, Jython).
But note there are times when verbosity cannot be avoided in Java though there might be a clear pattern. Clojure's macros are a huge win here- even over other similarly dynamic languages.
Another thing to consider is that Clojure programs tend to be concurrency safe. So if you decide down the road to make a particular application concurrent, it won't be too painful. Without making alot of decisions up front this will be considerably more difficult with Java.
Also wondering if Clojure would have a clear advantage over Java if it lacked strong concurrency primitives and immutability is kind of like saying, "Well what if Clojure wasn't Clojure?"

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