Is it a standard way to code or any other alternatives are there? I thinking this a while about the code that I've written. Finally gave up and thought to check with you guys.
Here is the scenario I had.
private String functionNameXYZ(String a,String b) {
//Logic goes here
}
private String functionNameXYZ(String a,String b,String c) {
//Same logic goes here , Nothing much difference because of String c
}
So I tho
ught to skip two functions for same purpose and I created a single function as below.
private String functionNameXYZ(String a, String b,String... c){
return performlogic(a,b,(c.lenght!=0)? c[0]:null);
}
private String performlogic(String a,String b, String c) {
//logic , return "string"
}
Which is standard way of coding? Was it to seperate logic into new method instead of repeating[Second case] or Was it other way? Kindly suggest if you find any better ways?
If your only two valid options are two String arguments and three String arguments, using varargs is a tad overkill, and worse - it's confusing, as it implies that you could also pass five or ten or a gazillion arguments. Instead, you could do something much simpler:
private String functionNameXYZ(String a, String b) {
functionNameXYZ(a, b, null);
}
private String functionNameXYZ(String a, String b, String c) {
// One place for the logic
}
Your first scenario is fine, except you want to maybe take any large bulk of common code in the functions and put it in a separate function (or more easily, have the function with less params call the one with more).
The overloading is fine, but rewriting the same code both places is not good practice.
Also, since Java doesn't have default parameters, I'm not too keen on having a public method's argument that is nullable, even if noted on the JavaDocs. Overloading is the way to go.
I think you need to ask yourself a question: what input is legal?
If your program should handle 2...n arguments, then absolutely go with the varargs. However if the legal input to your function is either exactly 2 or 3 arguments, then you should use the pattern:
private String functionNameXYZ(String a, String b) {
// logic of function
}
private String functionNameXYZ(String a, String b, String c) {
// place the logic for handling 'c' input then call
functionNameXYZ(a, b);
}
Alternatively, as the other poster mentioned:
private String functionNameXYZ(String a, String b) {
functionNameXYZ(a, b, null);
}
private String functionNameXYZ(String a, String b, String c) {
// One place for the logic
}
Personally, I prefer the first approach as it clearly separates the logic used to handle the 'c' parameter and the others. This is commonly used when you can seperate that logic, e.g. in constructors. However, when the logic can't easily be untangled go for the second approach.
Related
Is there a way I could pass in a dynamic value into a Custom Annotation?
For example as follows:
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface CustomAnnot {
String[] requestKeys();
}
When annotating, I want to pass in the value of the argument dynamically.
#CustomAnnot(requestKeys = {"id"}) // or maybe "#id"
public Object get(String id) {}
To note the above won't just work. Need some form of parsing for this to work.
How can I go about doing this? Trying to find online references and but unable to find anything to aid in this implementation.
#Cacheable in Spring is able to do this thus clearly this is possible. Tried to have a look over the implementation for #Cacheable and to be honest got lost. It's massive and a struggle to debug. Could I get some advice on this implementation or if anyone familiar point to the part where cacheable implements this? Thanks.
EDIT:
I need a way to get values from arguments in a method.
Example.
// maybe in this method I only want String b and c
String method1(String a, String b, String c){
return null;
}
// maybe here I want String a and c
String method2(int d, String a, String b, String c){
return null;
}
// just 1 argument here so only need String a
String method3(String a){
return null;
}
I am looking for a single way to get the values of what I need in 1 way.
I want to write this functionality once and be done with it, not have to come back again for a different method signature.
Thus I was going for a custom annotation which gives me flexibility to decide what values I want so I can pass in an array .
I've recently started writing android applications in Java, I'm completely new to Java and I did the basics of object oriented programming in c++ at college. My question is, what is good and bad practice when passing variable data to different methods in Java? For example, something I have been doing in my code is:
String one;
String two;
String three;
String four;
exampleOne(one, two, three, four);
exampleOne(String one, String two, String three, String four) {
// do something
exampleTwo(one, two, three, four);
}
exampleTwo(String one, String two, String three, String four) {
// do something
exampleThree(one, two, three, four);
}
exampleThree(String one, String two, String three, String four) {
// do something
}
In my code I've done something like this where I pass arguments up to 5 times, is it bad practice to do this? What would be a cleaner more eco option?
If there are many arguments and they would be passed many times, I would go for a DTO object.
Create a Pojo class which encapsulates those parameters and pass the instance between methods. You can add some helper functions/methods in the DTO as well, to ease some processing.
It could be useful to declare a class like this:
public class YourClass{
private String one;
private String two;
private String three;
private String four;
public YourClass(String one, String two, String three, String four){
this.one = one;
this.two = two;
this.three = three;
this.four= four;
}
public void exampleOne() {
// do something
exampleTwo();
}
public void exampleTwo() {
// do something
exampleThree();
}
public void exampleThree() {
// do something
}
}
And use it:
YourClass c = new YourClass(one, two, three, four);
c.exampleOne();
There is nothing wrong in what you did but you can clarify things up using varargs (as TAsk stated) or by creating a small container class (like a c struct, often called bean) which represents a set of parameters.
This allows you to tidy things and make code more readable.
Please be aware that when creating a class you will introduce a little overhead due to a new allocation while this wasn't true with c-struct as it is the compiler which manage references to struct members.
Parameters are passed in stack like in c and there is no concept of by-reference-arguments in java, using a bean can overcome this limitation.
Well,Passing Argument is required when ever you want to call method with some attributes but for huge number of arguments of Same type you can use following.
You can use VarArgs instead.
public void Method(String.. str) {
//Here you will have Array str[](Of String)
if(str!=null)
for (String s: str)
System.out.println(s);//Iterate through Array for More Processing
}
If you want to Pass Other Argument as well
Method(int i, String... Other) {
//VarArgs Must be Last
}
NOTE:
Pass Arguments of Different type and Use conversion methods to convert String to Double,Int,etc.(well This is not recommended but can be done because you need to make sure at which place you have passed double,int etc.)
I'm sure this question has allready been answered somewhere, but I' ve searched for half an hour now and I'm running out of keywords, because I have absolutly no idea how to do this.
I have a constructor for a class like this
public MyClass (String name)
{}
what I want is to define Strings so that only those Strings can be entered.
I assume it has something to do with static final strings, but there is quite a lot to be found to those and I dont know how to narrow down the search. Please tell me how that thing I want to do is called, so that I can search for it.
Edit:
Example to what I want:
I want to somehow define a number of Strings. (Or do somethig else that has the same effect, as I said I dont know how to do it)
String one = "ExampleOne";
String two = "ExampleTwo";
so that when I call the constuctor
MyClass myClass = new MyClass("somethingElse");
the constructor wont take it. Or even better eclipse allready showing my what options I have like it does whit "Color. "
Yes you have right you can not override String class because it is final so simply you can create your own StringWrapper class that wraps string.
public class StringWrapper{
private String content;
public StringWrapper(String c){
content = c;
}
//all your methods and fields there, for example delegated methods
public String toString(){
return content.toString();
}
}
But Enum could be also used in your case then you define your Enum values
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.
#Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
public myClass (Color color)
{}
There are two ways you can acheive this, either use a enum as constructor parameter. The enum itself contains only the allowed values, which is what I would do, keep everythign nice an oop and you can add logic to enums at a later date.
Or alternatively you can just check if the constuctor paramters value is valid, by performing a comparison and throwing an exception if not in allowed values. Have a predfined list and then, myList.contains(myString) - throw exception if false.
What I want is to define String so that only those Strings can be entered
I think that what you are after are Enums.
Enums will allow you to define a range of values which you can then use. In the example I have linked, the developer can restrict the type of input that he/she will receive to the days of the week.
You can check it in constructor's body at runtime, or if you want to compile-time checks, then you can use enum type argument (enum is a predefined set of constants).
From what I understand it seems like you want to limit what the String can be.
You would do this by putting conditional statements inside the constructor to weed out any Strings you don't want to be entered that would either notify the user that it is an invalid string or throw an exception, and the remainder of the constructor would only be executed in an else statement once it has passed all the tests making sure it is a valid String
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.
Which of the following ways is better to convert Integer, Double to String in Java.
String.valueOf(doubleVal)
doubleVal + ""
doubleVal.toString()
Thanks.
doubleVal + "" is most likely the worst since it has to do a concatanation with an empty string. However, the other two are equivalent. The source code from OpenJDK:
// java.lang.String
public static String valueOf(double d) {
return Double.toString(d);
}
// java.lang.Double
public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}
I don't think there's a performance difference. Go for the most readable!
The first one is exactly equivalent to doublevar.toString() (check the javadoc). The second one is more suited for concatenating longer strings.
If you need to format the way your number is represented as a String, you anyway need to look into other classes
The first and the third are good, the second is bad.
The reason that the second is bad is because the code doesn't show what you want to do. The code says that you want to concatentate the value with an empty string, when you actually want only the conversion that happens before the concatenation.
I prefer to use Integer.toString(int), when you use String.valueOf(int), it internally calls to Integer.toString(int) (same with long, float and double). But for readability, it would be better to use String.valueOf()
There are slight semantic differences depending on whether you're using the primitive double type, or its object wrapper Double.
Anything that will work for a primitive double will also work for the object wrapped Double, but the opposite will not work. (That is, a primitive double will not be accepted if the parameter is of type Double.)
Also, the Double type's value may be null, but the primitive double type cannot.
Beyond that, there isn't much difference at all. For the code snippets you've provided, there isn't any worth really talking about.
i) String.valueOf(int i)
ii) Integer.toString(int i)
After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)
Just two different ways of doing the same thing
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for double
Double.toString(dobule d)
and so on
In my opinion this is not some historical thing, but is more useful for developer to use the method valueOf from String class than from proper type, because is less changes to make when we want to change the type that we operate on.
Sample 1:
public String doStaff(int num) {
//Do something with num
return String.valueOf(num);
}
Sample2:
public String doStaff(int num) {
//Do somenthing with num
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
My conclusion is that using the valueOf method from String class is more flexible and that why is available there.
From the official source:
public static String valueOf(double d) {
return Double.toString(d);
}
So the first and the third are not really different, as long as doubleVal is double and not Double. This is because in the case of a Double, you will call
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
The second is certainly worse because of the need to concatenate.
CONCLUSION:
Following the question, I must assume that the most efficient way is to call the toString() method.
Java string.valueOf() method converts different types of value such as long,int,double,float into String.
Double double_val=45.9;
String string_conversion=String.valueOf(double_val);