Is it possible to use some construct to replace all floats with doubles (or the opposite) without refactoring?
For example you may be implementing some mathematical system that works perfectly interchangeably with floats or doubles. In C you may use: typedef float real and then use real in your code. Changing to double involves only replacing one line of code.
Is something like this possible in Java? Or is there some generic numeric type?
This is not possible in Java in the straightforward case which you describe. However, depending on how your code works, you could write your math classes to interfaces, and have all methods that return values be implemented with both a double and a float return type. Then, you could write two implementation classes, and switch between them depending on which one you wanted to use.
This seems like overkill. Why do you want to do this?
It's actually recommended to use BigDecimal instead of float/double. Don't think java has something similar to typedef float real
No, there is no way to achieve this in Java with primitive types. There is simply no typedef equivalent and there are also no template classes. From a functional view, you could work this with the object oriented way, the methods would take a wrapper class/interface type (something like java.lang.Number) and also return results as a wrapped type.
However, I would just scrap the entire idea and only implement the double version. Callers that want to work with float can just use the double version of any method - parameters will be automatically widened to double. The results then need to be cast back to float by the caller. The conversions to and from double will cost a little speed. Or if double was just nice to have and you can make do with float, create only a float version.
In terms of raw computation speed, there is little to no difference between float and double (on a desktop CPU). The speed advantage with float usually mostly comes from the halved memory bandwidth requirements.
If its just one or a few utility classes, you could also have two sets of them (e.g. FloatMathUtil and DoubleMathUtil). It would then be up to the user to decide which one to code against (they would be entirely unrelated classes in terms of API).
You can use object-oriented aproach.
Create your own class that implements the methods your mathematical system needs. Use this class instead of float. Inside it can use whatever you want float, double or BigDecimal. You can change later how your class works without changing the rest of your system.
Take a look at Double, it will give the general idea how to build it.
Implement methods for addition, multiplication etc.
E.g.:
public class MyDecimal
{
private float value;
public MyDecimal(int value)
{
this.value = value;
}
public MyDecimal(float value)
{
this.value = value;
}
public MyDecimal multiply(MyDecimal by)
{
return new MyDecimal(value * by.value);
}
...
}
So, if you want to use double instead of float you only need to change this class.
I have got a question regarding program style. Within a class, is it better to pass a variable to a method or to access the field inside a method?
public class NumberTest{
private int num;
public NumberTest (int num){
this.num = num;
calculateX(num);
calculateY();
}
private void calculateX(int num){
System.out.println (num);
}
private void calculateY(){
System.out.println(num)
}
}
I'll differ from the others here...
Where it is at all reasonable, I like to pass in the argument. This very slightly decouples the method from the class implementation, and makes it easier to unit test. For example, sometimes it is a pretty complex process to set this.num to 94404 due to other constraints.
e.g. this is a Zip Code but your business logic requires that it must match the State and Country field. Or, in practice this field is read from a Database, a Web Site, etc...
If you pass the argument, your unit test can shortcut and just pass in the value. And, in the off chance you might have a future special case where you don't want to use what's in the class field, you can do it.
Now, if you are using 27 class fields, you obviously don't want to pass in 27 arguments. But, IMO, if it's 1 or 2, I like to pass them in.
Minor Noted added after acceptance:
There is another possible difference between passing in the arg and using a field. In a multi-threaded environment, using a passed in argument may be safer that reading from a field. The field might get changed in the middle of the function, while a passed in argument, depending on type and usage, is less likely to change. In this example, a passed in int num will never change unexpectedly, but this.num might.
You're already passing the object (as this) when you call a member function anyway. You don't gain anything from having to explicitly specify the argument too, unless you need to be able to use that same function with values other than this.num.
Short version: Use the latter, unless you need to calculateX(some_whole_other_number).
those methods might look kinda similar to you, since they give you the same result, but they're actually very very different from each-other.
For instance, suppose your NumberText method looked like
public NumberTest (int num){
this.num = num;
calculateX(num * 2);
calculateY();
}
calculateX wouldn't actually take the field, but it can take something completely different.
A general rule of thumb is
If it makes sense to pass in something other than num to calculateX than you probably should pass it in. otherwise, don't
also, if you do this
private void calculateX(int num){
System.out.println (num);
}
change the parameter name to something other than num
Is num some state of NumberTest? Will you need it later? If so, make it a field.
Does NumberTest just provide function calculateX for many nums? If so make calculateX static.
The Situation is that I have to use Function pointers for so many functions in Java (so I did it this way) and saved each anonymous class to a static variable of the Interface, so that I could use them directly.
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(DoubleMatrix netSum, double theta) {
return netSum.gt(theta);
}
public String getFuncName() {
return "HARDLIM";
}
};
But the problem is that sometimes I don't need to provide the Theta so if I remove it the polymorphism won't work, (2 Functions out of 10 don't need theta) so I had to put it (Function declaration conventions now ugly) so I thought of passing the whole Object which actually contains both netsum and theta.
But I'm starting to worry, cause it's also going to ruin what this function really is for. So at last I suggested I put these function separately (non anonymous) and then make anonymous functions use them but the argument would be the object. Like the following:
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(MyObject obj) {
return MyObjectUtilFun.hardlim(obj.getNetsum,obj.getTheta);
}
public String getFuncName() {
return "HARDLIM";
}
};
So Am I taking the right steps ? or I'm messing around, Please guide me!
Do you really need the instance to be public static final? If you can instantiate the instance wherever you have a reference to theta, then your anonymous class can use that theta reference. For example:
final double theta = 123d;
class TransferePatternable {
public String transfere(String whatever) {
return whatever + theta;
}
}
TransferePatternable myInstance = new TransferePatternable();
myInstance.transfere("arg");
Alternatively you can specify the input as a generic type such that your MyObject need not be a superset of all possible inputs, but rather can differ by TransferePatternable type. Obviously the drawback here is that you need to know what type you're calling in order to provide the right input, but you sort of need to know this anyway if you don't want to provide theta in some situations.
Finally, another common solution to this problem is to replace ALL method parameters with just one Map. Then, you can pass in whatever you want! This has lots of obvious drawbacks, but lots of APIs do exactly this, and generally you'll see them refer to the map as the "context". Here are a few examples:
javax.servlet .ServletRequests store parameters in a Map
AOP has the javax.interceptor.InvocationContext class
Spring's IoC container basically is a big Map of named javabeans
The JSP Expression Language allows you to refer to Implicit Objects that basically are stored in several Maps
I myself have used this Map solution when implementing an Excel-like formula language in java years ago. Such a formula can be parsed into functions and variables, and when executing the function we provided a Map containing the variables keyed by variable name. Obviously you still need to know something about what you're invoking, and in fact we always did know enough about the formula that providing the right inputs in a Map was easy. But again I have to caution you: this sort of code is fairly hard to implement and maintain. Unless you anticipate growing a large set of functions over time, don't go down this route. It's not OO-friendly, and it should be a last resort.
If MyObject is a generally used interface or class and TransferePatternable is not expected to work with anything else, your second idea is best. It opens up the possibilities of a TransferePatternable being able to work with more than just netSum and theta and gets rid of the unneeded theta. My guess is that this is what you want to do, even if it means expanding the capabilities and scope and importance of the MyObject class/interface.
But you are restricting a TransferePatternable to working with a MyObject instance. The unused theta is a problem, but it's a small price to pay for the power of polymorphism (and its a lot simpler and neater than most other solutions). If the MyObject solution doesn't look perfect to you, stick with the unused theta. My guess is a good idea will come along sooner or later, with no harm done if it doesn't.
Is there any reason you can't have an overloaded "transfere" function in the HARDLIM?
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(DoubleMatrix netSum, double theta) {
return netSum.gt(theta);
}
public DoubleMatrix transfere(DoubleMatrix netSum) {
return netSum.whateverYouNeedToDoWithoutTheta();
}
public String getFuncName() {
return "HARDLIM";
}
};
At the end I used The second choice but with some notes in mind:
To always have functions (i.e Hardlim) defined independently in utility classes.
To state in Javadocs what this variable really is and the utility function being used.
I also found the price of confusing users with unnecessary arguments to be high cause the application is already complex no need to be more complicated.
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(MyObject obj) {
return MyObjectUtilFun.hardlim(obj.getNetsum,obj.getTheta);
}
public String getFuncName() {
return "HARDLIM";
}
};
In PL/SQL (or many other languages), I can have IN OUT or OUT parameters, which are returned from a procedure. How can I achieve a similar thing in Java?
I know this trick:
public void method(String in, String[] inOut, String[] inOut2) {
inOut[0] = in;
}
Where the in parameter represents an IN parameter and the inOut parameter can hold a return value. The convention would be that String[] inOut is an array of inOut.length == 1.
That's kind of clumsy.
EDIT Feedback to answers: Other tricks include:
holder/wrapper classes, but I don't want to introduce any new types, callbacks, etc.
return values: I'd like a general solution. I.e. one with several IN OUT parameters involved.
wrapper for IN OUT parameter as a return value: That's a viable option, but still not so nice, because that wrapper would have to be generated somehow
Does anyone know a better way to achieve this generally? The reason I need a general solution is because I want to generate convenience source code from PL/SQL in a database schema.
My question would be: Why doesn't method return something? Rather than setting an in/out argument?
But assuming you absolutely, positively must have an in/out argument, which is a whole different question, then the array trick is fine. Alternately, it's not less clumsy, but the other way is to pass in an object reference:
public class Foo {
private String value;
public Foo(String v) {
this.value = v;
}
public String getValue() {
return this.value;
}
public void setValue(String v) {
this.value = v;
}
}
// ....
public void method(String in, Foo inOut) {
inOut.setValue(in);
}
(Or, of course, just make value public.) See? I said it wasn't less clumsy.
But I'd ask again: Can't method return something? And if it needs to return multiple things, can't it return an object instance with properties for those things?
Off-topic: This is one of the areas where I really like the C# approach. One of the arguments against in/out arguments is that they're unclear at the point where you're calling the function. So C# makes you make it clear, by specifying the keyword both at the declaration of the function and when calling it. In the absense of that kind of syntactic help, I'd avoid "simulating" in/out arguments.
Java copies anything you pass as an argument. If you pass a primitive, inside method you have copy of that primitive, and no modifications will affect the actual variable outside method. If you pass object, you pass copy of reference, which actually references to the original object. This is the way how you can propagate modifications to the context of something that called the method - by modifying the state of the object that the reference is 'pointing' to. See more on this: Does Java Pass by Value or by Reference?
There's no direct way. Other technique include:
Passing a holder object (a bit like your 1-ary array)
Using, e.g., an AtomicInteger
Passing a more useful object from a business perspective that happens to be mutable
A callback to a custom interface for receiving the result
If you think about it, the array trick is not dissimilar to passing a T* in C/C++
Occasionally , we have to write methods that receive many many arguments , for example :
public void doSomething(Object objA , Object objectB ,Date date1 ,Date date2 ,String str1 ,String str2 )
{
}
When I encounter this kind of problem , I often encapsulate arguments into a map.
Map<Object,Object> params = new HashMap<Object,Object>();
params.put("objA",ObjA) ;
......
public void doSomething(Map<Object,Object> params)
{
// extracting params
Object objA = (Object)params.get("objA");
......
}
This is not a good practice , encapsulate params into a map is totally a waste of efficiency.
The good thing is , the clean signature , easy to add other params with fewest modification .
what's the best practice for this kind of problem ?
In Effective Java, Chapter 7 (Methods), Item 40 (Design method signatures carefully), Bloch writes:
There are three techniques for shortening overly long parameter lists:
break the method into multiple methods, each which require only a subset of the parameters
create helper classes to hold group of parameters (typically static member classes)
adapt the Builder pattern from object construction to method invocation.
For more details, I encourage you to buy the book, it's really worth it.
Using a map with magical String keys is a bad idea. You lose any compile time checking, and it's really unclear what the required parameters are. You'd need to write very complete documentation to make up for it. Will you remember in a few weeks what those Strings are without looking at the code? What if you made a typo? Use the wrong type? You won't find out until you run the code.
Instead use a model. Make a class which will be a container for all those parameters. That way you keep the type safety of Java. You can also pass that object around to other methods, put it in collections, etc.
Of course if the set of parameters isn't used elsewhere or passed around, a dedicated model may be overkill. There's a balance to be struck, so use common sense.
If you have many optional parameters you can create fluent API: replace single method with the chain of methods
exportWithParams().datesBetween(date1,date2)
.format("xml")
.columns("id","name","phone")
.table("angry_robots")
.invoke();
Using static import you can create inner fluent APIs:
... .datesBetween(from(date1).to(date2)) ...
It's called "Introduce Parameter Object". If you find yourself passing same parameter list on several places, just create a class which holds them all.
XXXParameter param = new XXXParameter(objA, objB, date1, date2, str1, str2);
// ...
doSomething(param);
Even if you don't find yourself passing same parameter list so often, that easy refactoring will still improve your code readability, which is always good. If you look at your code 3 months later, it will be easier to comprehend when you need to fix a bug or add a feature.
It's a general philosophy of course, and since you haven't provided any details, I cannot give you more detailed advice either. :-)
First, I'd try to refactor the method. If it's using that many parameters it may be too long any way. Breaking it down would both improve the code and potentially reduce the number of parameters to each method. You might also be able to refactor the entire operation to its own class. Second, I'd look for other instances where I'm using the same (or superset) of the same parameter list. If you have multiple instances, then it likely signals that these properties belong together. In that case, create a class to hold the parameters and use it. Lastly, I'd evaluate whether the number of parameters makes it worth creating a map object to improve code readability. I think this is a personal call -- there is pain each way with this solution and where the trade-off point is may differ. For six parameters I probably wouldn't do it. For 10 I probably would (if none of the other methods worked first).
This is often a problem when constructing objects.
In that case use builder object pattern, it works well if you have big list of parameters and not always need all of them.
You can also adapt it to method invocation.
It also increases readability a lot.
public class BigObject
{
// public getters
// private setters
public static class Buider
{
private A f1;
private B f2;
private C f3;
private D f4;
private E f5;
public Buider setField1(A f1) { this.f1 = f1; return this; }
public Buider setField2(B f2) { this.f2 = f2; return this; }
public Buider setField3(C f3) { this.f3 = f3; return this; }
public Buider setField4(D f4) { this.f4 = f4; return this; }
public Buider setField5(E f5) { this.f5 = f5; return this; }
public BigObject build()
{
BigObject result = new BigObject();
result.setField1(f1);
result.setField2(f2);
result.setField3(f3);
result.setField4(f4);
result.setField5(f5);
return result;
}
}
}
// Usage:
BigObject boo = new BigObject.Builder()
.setField1(/* whatever */)
.setField2(/* whatever */)
.setField3(/* whatever */)
.setField4(/* whatever */)
.setField5(/* whatever */)
.build();
You can also put verification logic into Builder set..() and build() methods.
There is a pattern called as Parameter object.
Idea is to use one object in place of all the parameters. Now even if you need to add parameters later, you just need to add it to the object. The method interface remains same.
You could create a class to hold that data. Needs to be meaningful enough though, but much better than using a map (OMG).
Code Complete* suggests a couple of things:
"Limit the number of a routine's parameters to about seven. Seven is a magic number for people's comprehension" (p 108).
"Put parameters in input-modify-output order ... If several routines use similar parameters, put the similar parameters in a consistent order" (p 105).
Put status or error variables last.
As tvanfosson mentioned, pass only the parts of a structured variables ( objects) that the routine needs. That said, if you're using most of the structured variable in the function, then just pass the whole structure, but be aware that this promotes coupling to some degree.
* First Edition, I know I should update. Also, it's likely that some of this advice may have changed since the second edition was written when OOP was beginning to become more popular.
Using a Map is a simple way to clean the call signature but then you have another problem. You need to look inside the method's body to see what the method expects in that Map, what are the key names or what types the values have.
A cleaner way would be to group all parameters in an object bean but that still does not fix the problem entirely.
What you have here is a design issue. With more than 7 parameters to a method you will start to have problems remembering what they represent and what order they have. From here you will get lots of bugs just by calling the method in wrong parameter order.
You need a better design of the app not a best practice to send lots of parameters.
Good practice would be to refactor. What about these objects means that they should be passed in to this method? Should they be encapsulated into a single object?
Create a bean class, and set the all parameters (setter method) and pass this bean object to the method.
Look at your code, and see why all those parameters are passed in. Sometimes it is possible to refactor the method itself.
Using a map leaves your method vulnerable. What if somebody using your method misspells a parameter name, or posts a string where your method expects a UDT?
Define a Transfer Object . It'll provide you with type-checking at the very least; it may even be possible for you to perform some validation at the point of use instead of within your method.
I would say stick with the way you did it before.
The number of parameters in your example is not a lot, but the alternatives are much more horrible.
Map - There's the efficiency thing that you mentioned, but the bigger problem here are:
Callers don't know what to send you without referring to something
else... Do you have javadocs which states exactly what keys and
values are used? If you do (which is great), then having lots of parameters
isn't a problem either.
It becomes very difficult to accept different argument types. You
can either restrict input parameters to a single type, or use
Map<String, Object> and cast all the values. Both options are
horrible most of the time.
Wrapper objects - this just moves the problem since you need to fill the wrapper object in the first place - instead of directly to your method, it will be to the constructor of the parameter object.
To determine whether moving the problem is appropriate or not depends on the reuse of said object. For instance:
Would not use it: It would only be used once on the first call, so a lot of additional code to deal with 1 line...?
{
AnObject h = obj.callMyMethod(a, b, c, d, e, f, g);
SomeObject i = obj2.callAnotherMethod(a, b, c, h);
FinalResult j = obj3.callAFinalMethod(c, e, f, h, i);
}
May use it: Here, it can do a bit more. First, it can factor the parameters for 3 method calls. it can also perform 2 other lines in itself... so it becomes a state variable in a sense...
{
AnObject h = obj.callMyMethod(a, b, c, d, e, f, g);
e = h.resultOfSomeTransformation();
SomeObject i = obj2.callAnotherMethod(a, b, c, d, e, f, g);
f = i.somethingElse();
FinalResult j = obj3.callAFinalMethod(a, b, c, d, e, f, g, h, i);
}
Builder pattern - this is an anti-pattern in my view. The most desirable error handling mechanism is to detect earlier, not later; but with the builder pattern, calls with missing (programmer did not think to include it) mandatory parameters are moved from compile time to run time. Of course if the programmer intentionally put null or such in the slot, that'll be runtime, but still catching some errors earlier is a much bigger advantage to catering for programmers who refuse to look at the parameter names of the method they are calling.
I find it only appropriate when dealing with large number of optional parameters, and even then, the benefit is marginal at best. I am very much against the builder "pattern".
The other thing people forget to consider is the role of the IDE in all this.
When methods have parameters, IDEs generate most of the code for you, and you have the red lines reminding you what you need to supply/set. When using option 3... you lose this completely. It's now up to the programmer to get it right, and there's no cues during coding and compile time... the programmer must test it to find out.
Furthermore, options 2 and 3, if adopted wide spread unnecessarily, have long term negative implications in terms of maintenance due to the large amount of duplicate code it generates. The more code there is, the more there is to maintain, the more time and money is spent to maintain it.
This is often an indication that your class holds more than one responsibility (i.e., your class does TOO much).
See The Single Responsibility Principle
for further details.
If you are passing too many parameters then try to refactor the method. Maybe it is doing a lot of things that it is not suppose to do. If that is not the case then try substituting the parameters with a single class. This way you can encapsulate everything in a single class instance and pass the instance around and not the parameters.
... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!
https://projectlombok.org/features/Builder