Which is faster and/or less resources consuming:
class Foo()
{
public int value;
}
This way?
public int doSomeStuff(Foo f)
{
return (f.value + 1);
}
public int doOtherStuff()
{
...
Foo f = new Foo();
int x = doSomeStuff(f);
...
)
or this way?
public int doSomeStuff(int v)
{
return (v + 1);
}
public int doOtherStuff()
{
...
Foo f = new Foo();
int x = doSomeStuff(f.value);
...
)
In both cases, "doSomeStuff" will not change nothing in foo class. It just needs to know the "value".
They both perform the same, the same sequence of operations occurs. Your main concern is maintainability and sensible design here. Think carefully about which methods need which data and design it properly.
If you do have issues, you can optimise later. But you should always optimise last.
In terms of resource consuming, it is exactly the same.
But the second option is clearly better in terms of programming because if doSomeStuff only needs value, then there is no point to passing f.
I don't think there is any performance difference at all. And Java compiler will optimize to the best one anyway...
Depends how often you're going to call doSomeStuff without calling doOtherStuff, but generally performance difference is negligible and if you only call doOtherStuff then they'll be equally performant.
Probably even better:
Decalre doSomeStuff() as a method of foo, and invoke: f.doSomeStuff()
It is much more readable and will be easier to maintain doing it so, since if you have a
sub class of foo: Bar, and you want to calculate things a bit different - all you have to do is override doSomeStuff() in Bar
You should prefer readability over micro optimizations - let the compiler take care of those for you.
code snap:
class foo() {
public int value;
public int doSomeStuff() {
return value + 1;
}
}
and:
public int doOtherStuff() {
...
foo f = new foo();
int x = f.doSomeStuff();
...
}
The difference between doing:
object.intvariable + 1
and
int + 1
is so negligible as to be irrelevant for real world apps. It's probably one or two more JVM opcodes to look up foo and find its value variable which is not worth mentioning. You'd never notice that unless you were trying to create a pseudo real-time app in Java (which is all but an exercise in futility).
However, that said, the way you are doing it is very bad. You should not be exposing value directly, but be using proper data encapsulation via getter and setter methods.
It does not matter from performance perspective.
The recommendation is: do not think about pre-mature optimization. Think about correctness and good design of your code.
For example your code
Does not follow naming conventions: class names must start with capital letter
Contains public fields. It is forbidden. Use bean notation (getters and setters).
Cannot be compiled (there is no type integer. Choose among int and Integer
Related
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
What is the best (in terms of flexibility) object-oriented implementation for an alternating state toggle in Java? The implementations I have listed are only what I have come up with and are not exhaustive.
Note: The answer to this question is not subjective. By the principles of object-oriented programming, the context of usage for this implementation should be irrelevant.
[Edit] The focus here is on the structure of the code. Obviously the actual functionality is so simple as to not even warrant the effort of a dedicated implementation.
public class ImpureToggle<T> implements Supplier<T> {
//false represents state a, true represents state b
private boolean state;
private final T a;
private final T b;
public ImpureToggle(T a, T b) {
this.a = a;
this.b = b;
}
// returns a different reference depending on internal state
#Override
public T get() {
return state ? b : a;
}
public void toggle() {
state = !state;
}
}
public class ConsumerToggle<T> implements Consumer<Consumer<T>> {
private final T a;
private final T b;
//false represents state a, true represents state b
private boolean state;
public ConsumerToggle(T a, T b) {
this.a = a;
this.b = b;
}
#Override
public void accept(Consumer<T> t) {
t.accept(state ? b : a);
}
public void toggle() {
state = !state;
}
}
public interface ImpureStaticToggle {
// reassigns parameter 'state'
static <T> void toggle(T state, T a, T b) {
state = state == a ? b : a;
}
}
public interface PureStaticToggle {
// returns a different reference depending exclusively on external input
static <T> T toggle(boolean state, T a, T b) {
//false represents state a, true represents state b
return state ? b : a;
}
}
/*
Just as an example of an unarguably bad implementation:
*/
public class MutableToggle<T> implements Supplier<T> {
private T state;
private final T a;
private final T b;
public MutableToggle(T a, T b) {
state = a;
this.a = a;
this.b = b;
}
// exposes a mutable reference, which could completely break the logic of this
// object and others
#Override
public T get() {
return state;
}
public void toggle() {
state = state == a ? b : a;
}
}
[Edit] ternary for inverting boolean (was done for consistency) replaced with logical complement operator as per #gargkshitiz.
By the principles of object-oriented programming, the context of usage for this implementation should be irrelevant.
Not sure what this means, and you seem firm on not giving context, but I'll try my best to give deeper insight into why I feel what you're doing doesn't make much sense.
Don't pass booleans as arguments1
broadly speaking if there is a parameter passed into a function that selects specific behaviour to be executed then further step-wise refinement is required; Breaking up this function in to smaller functions will produce more highly cohesive ones
The problem with a parameter passed in as you describe, is that the function is doing more than two things; it may or may not check the users access rights depending on the state of the Boolean parameter, then depending on that decision tree it will carry out a piece of functionality.
It would be better to separate the concerns of Access Control from the concerns of Task, Action or Command.
Take, for example, String#regionMatches. It has an overload for ignoring case.
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) {
if (!ignoreCase) {
return regionMatches(toffset, other, ooffset, len);
}
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)length() - len)
|| (ooffset > (long)other.length() - len)) {
return false;
}
byte tv[] = value;
byte ov[] = other.value;
if (coder() == other.coder()) {
return isLatin1()
? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len)
: StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len);
}
return isLatin1()
? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len)
: StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len);
}
This is a clear example, from the standard library, of why you should avoid boolean parameters for your behaviors.
Notice how the boolean determines which implementation should be used: one which ignores casing, or one which doesn't.
This is a cheap trick typically used to make choosing an implementation less verbose:
for(int i = 0; i < 100; i++) {
boolean even = i % 2 == 0;
boolean matches = text.regionMatches(even, ...);
// use matches
}
However, at a glance, it's not clear exactly what that condition is determining. We're forced to open the documentation (or worse: the implementation).
Compare that to:
for(int i = 0; i < 100; i++) {
boolean even = i % 2 == 0;
boolean matches = false;
if(even)
matches = text.regionMatchesIgnoreCase(...);
else
matches = text.regionMatches(...);
// use matches
}
Or
for(int i = 0; i < 100; i++) {
boolean even = i % 2 == 0;
boolean matches = even ? text.regionMatchesIgnoreCase(...) : text.regionMatches(...);
// use matches
}
It's more verbose, but it's clearer as to what the condition is for: determining whether casing should be ignored.
regionMatchesIgnoreCase would be easier to comprehend at a glance, rather than needing to read the documentation to determine what the boolean represents.
Comprehension is important for avoiding time waste when fixing critical bugs. Assuming you want to blindly apply principles, this knocks out PureStaticToggle.
Don't use interfaces as utility classes1 (easy fix)
This seems to me to cut against the grain of interfaces. One would have to look around the API to determine that there are no classes that implement this interface, and that there are no producers or consumers of this interface
If you look at the new Java 8 APIs, you'll see that the final class idiom is still used despite the ability to add static methods on interfaces.
This would remove both interface alternatives. It can be easily worked around: You can ignore this principle, or use a regular class.
But, what would this utility type be for? What other methods would be in the utility type? 1 type per utility implementation seems excessive, bloats the namespace.
Using an interface doesn't make your code OOP. Interfaces in general are not an OOP concept. However, their initial/primary function (before static and private methods) were OOP. Java supports multiple paradigms, hence the exposure of static methods in interfaces.
Design by contract1
Software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants.
Assuming you want sturdy interfaces for your implementations, you should expose contracts.
If you aren't familiar with contracts, they're a set of rules followed by both the client of the code & the code itself. If the code doesn't work based on what it states in the contract, it's considered to be bugged.
In Java, they're typically defined by JavaDocs. However, no matter how you choose to expose your contracts to users, the point here is that clients should know what that piece of code will and won't do, and code should define how the user should use the code.
How would your contract look for the types you've proposed?
Contracts are built based off requirements. From the code shown, the requirements aren't clear. In fact, the interface approaches
In terms of OOP, getters violate encapsulation1
It is not encapsulation and [using] Lombok [to generate getters & setters] is just making to work with procedural code less painful
And data structure is not an object
You should encapsulate state and implementation details so that object has full control on that. Logic will be focused inside object and will not be spread all over the codebase
Getters are procedural, not object oriented.
In OOP, objects communicate via behaviors. When you expose getters, you are exposing properties of the object.
The reason why OOP prefers hidding the properties of objects can vary, with some being obvious: Properties are eventually used in logic somewhere, and the logic/behavior which relies on that property won't be easily apparent if exposed.
Using a call-back to handle the logic of the property, especially how you're doing it in ConsumerToggle, is not much different from exposing a getter.
ImpureStaticToggle won't work as it is (easy fix)
Java is pass by value.
String s = "first";
toggle(s, "second", "third");
System.out.println(s); // prints "first"
The value of s will remain unchanged. It can be fixed with a return statement & assignment when calling the function:
<T> T toggle(T state, T a, T b) {
return state == a ? b : a;
}
T value = toggle(value, a, b);
However, this approach is still flawed for reasons mentioned in some of the sections above.
Last notes
ImpureStaticToggle and PureStaticToggle are different.
The former determines a return value based on the type of a reference
The latter determines a return value based on the result of any condition.
You can use PureStaticToggle to achieve what ImpureStaticToggle does. But, you cannot use ImpureStaticToggle to do what PureStaticToggle can do. They aren't completely interchangable, and those details should impact your choice.
What you are ultimately doing with the code you've shown is changing the implementation based on a condition. That's all that's going on here.
I hate to say it, but if your goal is to follow OOP principles by "tossing the book" at your code, then all your alternatives violate commonly practiced OOP principles.
Don't overcomplicate things. I don't see any benefit in encapsulating/hiding the use of a ternary. Use the ternary as is, when needed. Invest the time you would have invested in this design into something important.
Also, for your interfaces, toggle isn't the best name either, since the behavior isn't actually toggling anything - a better name would be chooseValue or determineValue, as that's what the method is actually doing.
Your first implementation (ImpureToggle) looks okay. Just change the toggle method to be:
state = !state
But having such a Toggler with a public toggle method looks like an overkill. Either use the whole class with proper access modifiers OR instead use a local method to limit the scope and the potential bugs.
Which one is better?
public class A {
private static final String DOSOMETHING_METRICS = "doSomethingmetrics";
private static final String SAYSOMETHING_METRICS = "saySomethingmetrics";
public void doSomething() {
...
System.out.println("Metrics for " + DOSOMETHING_METRICS + "is something");
}
public void saySomething() {
...
System.out.println("Metrics for " + SAYSOMETHING_METRICS + "is something");
}
}
OR
public class A {
public void doSomething() {
final String DOSOMETHING_METRICS = "doSomethingmetrics";
...
System.out.println("Metrics for " + DOSOMETHING_METRICS + "is something");
}
public void saySomething() {
final String SAYSOMETHING_METRICS = "saySomethingmetrics";
...
System.out.println("Metrics for " + SAYSOMETHING_METRICS + "is something");
}
}
I think Method 1 wins in case of memory optimization as compiler allocated memory only once and the garbage collector doesn't need to deallocate the string created in every function call. However, I think good coding practice recommends that variable should be bound to the scope in which it has to be used and constants should be defined as close as to they first use in the program which is where Method 2 wins.
What is your take on this? Which aspect is more important? The functions here will be called multiple times (let's say at least 100K times).
In both cases, these are constant variables as defined in JLS 4.12.4. So not only are the strings "doSomethingmetrics" and "saySomethingmetrics" interned, but so are "Metrics for doSomethingmetricsis something" and "Metrics for saySomethingmetricsis something". (Yeah, you need to add a space before "is".)
The first version logically has a slightly smaller stack, but I'd expect the JIT to optimize that away anyway.
I would use whichever form you find most readable. If you want to know for sure about the performance in your particular app, then as ever, the right thing to do is test both ways.
Looking at the results of javap -v, it looks like the second method actually has a slight advantage in that the unconcatenated strings don't even need to appear in the constant pool, as there's no way of reaching them. So you should see your class file being ever-so-slightly smaller that way. But again, I very much doubt that it'll make any difference.
I think Method 1 wins in case of memory optimization
In both cases your string constants go to string pool and stored there. In second case you reallocate space for reference to your variable in stack frame. That's why I think that the first one is preferred one (but compiler can optimize the second case and they would be the same).
I will use result of a method call in some calculation. I have two ways:
Invoke method once and store the return into a local value, then use the local value in some calculation.
Use call method many times.
Please see my sample code:
public class TestMethod {
public void doSomething_way1() {
String prop1 = this.getProp1();
if (prop1 != null) {
String value = prop1 + " - another value";
System.out.println(value);
}
}
public void doSomething_way2() {
if (this.getProp1() != null) {
String value = this.getProp1() + " - another value";
System.out.println(value);
}
}
public String getProp1() {
return "return the same value";
}
}
NOTE that, the method doSomething will be invoked a lots at a time ( In web environment )
Can someone show me which way I should use in the case the result of method will be used at least 3 times?
I believe using the method call many times is more intuitive and makes the code more readable.
In your case it wont matter even if you give call to the getProp1() method multiple times. Because it does not perform any computation, object creation or I/O operation which may cause performance issues.
You could go a step further:
public void doSomething_way2() {
if (this.getProp1() != null) {
System.out.println(this.getProp1() + " - another value");
}
}
If the method is getting called a lot (I mean many, many times a second), creating the extra variable could change performance a tiny bit with respect to garbage collection and what not... I think its trivial.
In some cases, getting the value more than once could raise thread-safety issues, if the value weren't final, whereas if you fetch the value once, at least the entire operation of way1 will be consistent with a single value for prop1.
But even if threading weren't an issue, I still think it's better, stylistically, to 'cache' the value in a local variable which is well named.
(I'm assuming that your real code does something more significant than return the fixed String "something") - the getProp1 method as written is pretty thread-safe. :)
From a performance standpoint, at least from the examples given, it does not appear to be any fundamental difference doing it one way or another. Object allocations for small numbers of iterations (unless they are heavyweight objects) should be minimal.
However, from a programming design and implementation standpoint, it may be helpful to keep the program 'cohesive', i.e. have classes more closely represent things.
In which case the local variable from the return of the method (as it is a different 'thing') and subsequent calculation.
e.g.:
interface Dog{
void wagTail();
Dung eat(DogFood f);
}
interface Human{
void pickUpDung(Dung d);
}
codeLoop(Human m, Dog d, DogFood f){
d.wagTail();
Dung poo = d.eat(f);
m.pickUpDung(poo);
}
whereas a less cohesive example would be
interface Dog{
void wagTail();
void eatAndHaveHumanPickUp(DogFood f);
}
// you can fill in the rest...
it wouldn't follow the principle of cohesion, because you wouldn't normally expect a dog call to have this kind of method...
I have 3 ints named A, B, and C. These are to be multiplied with the number 52. I have a string that contains the name of which int I want to mulitply (in example below my string type == A;.
I want to know if there is anyway to make the name of the String change into the name of the object/int that I wish to use.
What I have right now:
public class MultiplySomeNumbers{
int A = 100;
int B = 200;
int C = 300;
String type = "A";
final int multiplied = 52;
public int multiply(String type){
return multiplied* ____ //What goes here?
}
}
I DON'T want to do anything like this:
public int multiply(String type){
if(type.equalsIgnoreCase("A"){
return multiplied*A;
}else if(type.equalsIgnoreCase("B"){
...
Any help would be greatly appreciated!
No, that is not possible (maybe with Reflection, but it's still a no-go). Every single situation where you think you might need this does not need it.
There are several issues, but here are a few:
No intellisense for those generated variables
Very unclear code
Ambiguous naming (what if you create a new variable that happens to have the same name as a generated one?)
etc etc etc
You will have to go with your second option.
We might be able to provide a different solution, but the question is rather unclear as it is right now. Perhaps you could expand a little so we can help you better.
Although there may be a way to do this with reflection, it's probably a really bad idea. If you really can't just pass in the value, but want to specify a limited set of constants by which you can multiply, I'd recommend creating an enumerated type.
Taking your same example, but using an enum instead of trying to look up constants by name, would look something like this:
public class MultiplySomeNumbers{
public enum Type {
A(100),
B(200),
C(300);
private final int value;
private Type(int value) {
this.value = value;
}
public final int getValue() {
return value;
}
}
Type type = Type.A;
final int multiplied = 52;
public int multiply(Type type){
return multiplied * type.getValue();
}
}
While there is nothing wrong with using an enum for this solution, it may not be the most flexible solution. Enums are, by design, effectively immutable ... they are intended to have the sense of constants. If you wish to change the value of a variable by multiplying its value by 52, then this is not possible with enums.
What I think you really should do is use a HashMap. A Map is a key / value pair.
The key is the "variable's name"; a String quantity
The value is the "variable's current value"; an Integer quantity (not int!)
Your Map can be declared like this:
Map<String, Integer> myVariables = new HashMap<String, Integer>();
then to load your variables into the map, you simply call the Map's put() method:
myVariables.put("A", Integer.valueOf(100));
myVariables.put("B", Integer.valueOf(200));
myVariables.put("C", Integer.valueOf(300));
Retrieving the value of a variable is as simple as using the get() method with your variable name as the key:
int val = myVariables.get("A").intValue();
Notice that I have chosen to box and unbox the primitive int values myself rather than rely on autoboxing. This is just a personal choice. It does trade off conciseness, but I'd rather see what's actually happening.
In my opinion, using reflection to determine a class field to access dynamically at run time is wholly unsatisfactory and should be avoided ... most especially since using the Java Collections API enables a statically typed, type safe solution that can be checked at compile time.
You can't check for a variable's name. For more information look here, there are some good answers:
Java Reflection: How to get the name of a variable?
But maybe a HashMap can help you, where you store "A", "B", "C" as keys and the respective numbers as value.
edit: Okay, maybe with something like this http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html it could be possible.
I sometimes (actually, often) find myself using a one-element array to return multiple values from a method. Something like this:
public static int foo(int param1, int param2[], String param3[])
{
// method body
....
// set return values
param2[0] = <some value>;
param3[0] = <some value>;
return <some value>;
}
Is this a bad practice? (It seems like it is because some of my friends said they didn't know what it was doing for 2 seconds!)
But the reason I used this in the first place was because this looked closest to what is know as pass-by-reference in C++. And the practice wasn't discouraged in C++, so ...
But if this is really a wrong way of doing things, any idea how to rewrite this in the clean way?
Thanks
Create an object that contains the data you want to return.
Then you can return an instance of that object.
class FooData {
private int someInt;
private int anotherInt;
private String someString;
public FooData(int a, int b, String c) {
someInt = a;
anotherInt = b;
someString = c;
}
}
public FooData foo() {
// do stuff
FooData fd = new FooData(blah, blahh, blahhh);
return fd;
}
While I agree with the general opinion here that using arrays for such a purpose is bad practice, I'd like to add a few things.
Are you sure that "pass by reference" really is what you need in the first place?
Many have said that your code is bad style, but now let me tell you why that is IMHO.
"Pass by reference" is mostly a synonym for "programming by side effect" which is a thing you always want to avoid. It makes code much harder to debug and understand, and in a multi-threaded environment, the bad effects of this attitude really can hit you hard.
To write scalable and thread-safe code in Java, you should make objects "read-only" as much as possible, i.e. ideally, you create an object and initialize it at the same time, then use it with this unmodifiable state throughout your application. Logical changes to the state can almost always be considered a "creation" of new state, i.e. creation of a new instance initialized to a state then needed. Many modern scripting languages only let you work in this way, and it makes things much easier to understand.
As opposed to C++, Java is much more efficient in allocating and releasing short-lived objects, so there is actually nothing wrong with what others here have suggested: To create an instance of a special class to hold the function result, just for the purpose of returning the result. Even if you do that in a loop, the JVM will be smart enough to deal with that efficiently. Java will only allocate memory from the OS in very large chunks when needed, and will deal with object creation and release internally without the overhead involved in languages like C/C++. "Pass by reference" really doesn't help you very much in Java.
EDIT: I suggest you search this forum or the net for the terms "side-effect", "functional programming" or "immutability". This will most likely open a new perspective to your question.
I believe that it is bad practice to "return" values using one-element arrays that are parameters to your method.
Here's another SO question about this topic. In short, it's very bad for readability.
There is an easy workaround: Wrap all values that you wish to return in a class you define specifically for this purpose, and return an instance of that class.
return new ValueHolder(someValue1, someValue2, someValue3);
That's not very idiomatic java. There are usually better approaches to software design.
What you're really doing with the "one-element array" is creating a mutable object (since String is immutable, as are primitives like int) and passing it by reference. Modifying this mutable object is called a "side effect" of the method. In general, you should minimize mutability (Effective Java Item 15) and your methods should be side-effect free. There are a couple approaches here.
1. Split the method into two (or three) methods that all take the same params:
public static int foo1(int param1)
{
// method body
....
return <some value>;
}
Similarly, you might have
public static int foo2(int param1) { ... }
and
public static String foo3(int param1) { ... }.
2. Return a composite object.
public Container {
private final int originalReturn;
private final int param2;
private final String param3;
public Container(int originalReturn, int param2, String param3) {
this.originalReturn = originalReturn;
this.param2 = param2;
this.param3 = param3;
}
// getters
}
public static Container foo(int param1, int param2[], String param3[])
{
// method body
....
// set return values
return new Container(<some value>, <some value>, <some value>);
}
This is indeed bad practice if the values are unrelated. This is usually an indicator that you can split that function into two, with each returning one of the values.
EDIT:
I am assuming that you are returning two values calculated in the method in an array. Is this not the case?
e.g.
public int[] getStatistics(int[] nums)
{
//code
int[] returns = new int[2];
returns[0] = mean;
returns[1] = mode;
return returns;
}
The above function could be split into getMean() and getMode().
Passing variables by reference allows the function to "legally" change their value. See this article to clear up the confusion of when this is possible in Java, and when it's not...
This is bad practice if the values are of different type and different entities, e.g. name and address, etc. It is fine with create an array with same data type, e.g list of addresses.