What is More Faster Using Functions or Using Static Methods in multiple threaded programme?Please explain why it is faster.?
Even if there is a sensible difference between the 2 approaches (which I seriously doubt), you should never design your programs based on this. Good design should (almost) never be sacrificed to achieve better performance. Because you don't gain a lot, but you lose a lot.
You may have heard that "pure functions" are better for multithreading. A pure function can often be implemented as as static method in Java, but it could also be implemented as an instance method. The main point is that when multithreading it is always better if you don't have any global variables that can change. So if you have an immutable object, that's as good as having static method implementing a pure function.
Related
I'll make it short:
public aClass[] changeClassSlightly(aClass[] ac) {
// changing various things in the class
// changes done
return ac;
}
meanwhile, in the main:
aClass test = new aClass();
test = changeClassSlightly(test);
So,
is this an inefficient / looked-down-uppon or unstandard way of doing things, when wanting to implement a functionality regarding a certain class into a different class?
In my case, the here called "aClass" is a fairly simple one, but when these things get bigger and bigger, taking the whole object and spitting it out slightly changed may be considered bad programming.
Is it, though? Is it the sighn of bad data structure or common practise in Java development?
Thanks a lot in advance and thanks for bearing with me :)
I see two different questions here. Inside of changeClassSlightly(...), it looks like you're talking about mutating the ac argument. The code in your question also seems to be asking about local variable reuse, since test is both the argument and the variable containing the value returned by changeClassSlightly(...).
In general, I personally prefer using immutable objects and data structures. I also try to avoid mutating arguments. See Effective Java, Item 15: Minimize Mutability.
If a function is pure it's generally easier to reason about.
But this is very much a matter of opinion.
As for reusing the local variable: I try to avoid doing that, too, but it's really not a big deal either way.
From a performance perspective your code is not ideal. If you can set values in the constructor you can use final fields (immutable, so always thread-safe and easy for the JVM to optimize). Furthermore the values set in the constructor can be safely read without synchronization. If you use a setter later on you need to synchronize or risk not getting the new value in other threads. Synchronization is not as expensive as it once was, but it should be avoided where possible.
I would recommend the builder pattern instead.
I am currently working on a new project for university and was curious as to the best way to handle a class I've created to perform utility operations such as hashing passwords.
Should the utility class contain static methods so that I call them like
Utilities.hashPassword(password,salt);
Or should I create a new instance for each call
new Utilities().hashPassword(password, salt);
Right now I have a new instance for each call to a function inside that class, but im concerned about the performance implications of this and am wondering if its even nessecary to do.
My original reason for instantiating them was because I wasn't sure how thread-safety worked and was concerned that multiple users calling the same static function would cause problems. After reading some material on java concurrency I'm now pretty sure that even if the method is static it would be thread-safe.
Should I change them all to static methods? Would this improve performance? Right now my test server buckles under load.
Thanks
Thread-safety does not care if a method is static or a true member method.
Thread-safety cares about concurrent modification to data. So, if your method is updating some generic data structure, you are NOT thread-safe just by making it static.
Arguments against "static": anything that is static is very hard to mock within unit tests. So be really careful about making stuff static just for convenience.
Regarding the performance aspect: object creation is very cheap in java (not completely free, but cheap). In your case - you could keep it a member method - just avoid to throw away your utility object all the time.
Should I change them all to static methods?
Yes. Utility method should be static. Because, instead of new Utilities().hashPassword(password, salt); use only static import of hashPassword(password, salt). Shorter and easier to read.
Would this improve performance?
Yes. Declaring static will save memory. It will also improve readability.
See also: Java: when to use static methods
While developing a two-dimensional vector class as part of a math library, I'm considering having static and instance method pairs for stylistic and usability reasons. That is, two equivalent functions but one is static & non-mutating, and the other is instanced & mutating. I know I'm not the first person to consider this problem (See here, for example) but I haven't found any information that directly addresses it.
Pros of having static and instance method pairs:
Some people prefer to use one or the other and in some cases being able to choose makes code easier to read.
It is implied that static methods are not mutating when both static and instanced methods are provided. This can make the calling code much clearer, e.g.:
someVector = Vector2d.add(vec1, vec2);
someVector = (new Vector2d(vec1)).add(vec2); // does the same thing although more convoluted.
// similarly adding directly to a vector is simpler with a mutator method.
someVector.add(vec2);
someVector = Vector2d.add(someVector, vec2);
This is especially important when long chains of function calls are used, which is common with vectors.
In-place operations can be faster computationally than creating a new instance for every operation. The user decides when performance is important. For users of a Vector class, performance may be important as vectors are frequently used in computationally expensive code.
Pros of having only static or instance methods, but not both:
No significant code redundancy. Easier to maintain.
Less bloat. The javadocs will be almost half the size.
Not necessary to inform users that static methods never mutate and non-getter instanced methods always mutate.
How frowned upon is having static/instance method pairs? Is it used in any major libraries?
Is the pattern "static methods don't mutate, instance methods do" widely known?
I think your concept of providing both static/immutable and instance/mutable methods is a good one. I think the distinction is easy to explain and will be easy for the API users to understand and remember.
I think your API implementation code will not have redundant business logic. You will find that that you repeat a pattern where the static implementation creates a new instance and calls the instance method on that new instance.
Given that I am lazy, I would look at building a bit of infrastructure that would auto-generate the static methods, their javadoc and their unit tests at compile-time. This would be overkill if you have 10 methods, but becomes a big win if you have 1,000 methods.
On the first part, "static methods don't mutate", that's widely used in OOP. I haven't heard of it being expressed explicitly. But it is common sense: "If you change an object, why would the method be static if it could be an instance method?" So I completely agree with the "static methods don't mutate".
On the second part, "instance methods do [mutate]", that's actually not as widely used. It rather depends on whether you decide your design to apply immutability or mutability. Examples from the Java API: java.lang.String is immutable, java.util.Date is mutable (most likely by accident / bad design), java.lang.StringBuilder is mutable intentionally (that's its purpose). Mutability can lead to defensive cloning in order to protect the code from mutation bugs. Whether this really is a problem depends on a few things:
Is it an API others will use? You never know how they will use your code... IMO it's more important to protect API code from mutation bugs than normal code.
How good is the unit test coverage? Would your unit tests find all the mutation bugs that might sneak in? If you follow TDD properly (Uncle Bob's 3 Laws of TDD), and it's non-API code, mutation bugs are very unlikely to sneak in without being instantly discovered.
If you have code that has to protect itself against mutation bugs using defensive cloning, how often is that code called? If defensive clones are created frequently, it might be better to use immutable objects than mutable objects. Basically this is the call of the number of calls of read-only methods (that would eventually defensively clone) of associating classes vs. the number of calls of mutator methods on the class itself.
Personally, I prefer immutable objects, I'm a fan of final (if I could change Java, I would make final the default for all fields and variables, and introduce a keyword var to make them non-final), and I try to do functional programming in Java, although it is not a functional programming language, as much as possible. From my experience I know that I spend significantly less time debugging my code than others (actually I run the Java debugger maybe twice a year or so). I do not have enough empirical data and proper analysis for creating any kind of "causal relationship" between experience, immutability, functional programming and correctness, therefore I will only say I believe that immutability and functional programming help for correctness, and you will have to come up with your own judgement on this.
Concluding on the second part, "instance methods do [mutate]" is the widely used assumption in case the object is mutable anyway, otherwise instance methods would clone.
When ever I see a class documented as thread safe, I wonder why it was not designed to be a utility class with all static methods like java.lang.Math, etc.
I'm missing valid driving force whenever I design a class in the scenarios like no state but chained methods in a single class.
Example 1: How about a class A that has a 'thread-safe field' S; I mean, the object 'S' itself is thread-safe. Can we declare all the methods and fields like S in class A to be static.
I hope my explanation is clear enough. Please clarify.
Note: Exclude javabeans, property holding classes, etc.. My question was regarding classes which perform some actions based on input params, they might need to make use of other classes as well.
I apologize that I edited the question. First draft was totally ambiguous.
I can easily imagine a situation where a class is required to have state, yet it's also a requirement to be thread-safe. I use queues for worker-threads for example. It HAS to be thread-safe and definitely has to have state in it. (namely the elements in the queue)
EDIT:
Note: Exclude javabeans, property holding classes, etc.. My question was regarding classes which perform some actions based on input params, they might need to make use of other classes as well.
If by that you mean that your question is about truly stateless classes, then -by definition- your observation is correct. Those can almost always be expressed in static utility classes.
EDIT2:
I think you are being somewhat mislead by the fact, that a lot of times when we see static we can relax about thread-safety. (Though it's not true in every case, just a rule of thumb) While thread-safety and statelessnes can go hand in hand in a way, static is an orthogonal concept. Furthermore, statelessnes does give you thread safety but thread safety doesn't have to mean stateless. If that would be the case, the whole concept of synchronized would be unnecessary.
For testability and since static fits OO like fist fits nose.
Testable code requires that you can CREATE your tested object in a controlled way. I don't want to have to execute someone's code just because it's called from somewhere within object I'm testing. I want to test my object in isolation - assuming it's collaborators work fine. Using static methods from some tools makes me use PowerMock for testability OR kiss isolation good-bye and execute that code as well while I'm testing. Powermock is a problem (since it uses it's own classloader), so is testing more than I want.
Static means procedural code. That's fine sometimes, since procedural is fine sometimes. But try to use OO features (inheritance, polymorphism) with static methods to find another reason when NOT to use static.
Simple example illustrating this: http://www.javaworld.com/javaworld/javaqa/2001-05/01-qa-0504-oo.html?page=1 - by no means exhaustive, but shows the point I hope.
Other examples are listed in #JB Nizet's comment on the answer above.
I know this is a late answer, but honestly, I had my fair share of problems with testing objects using static methods from 'instanceless' classes and the usually sought-after solution aka PowerMock.
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.