Refactor code java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the below piece of code and statements 2(scopeId) and 3(productScopeId) are repetiting in many methods. How can I refactor the below methos in such a way that it can be used in many methods. I don't want to create a class with these two variables and return scope and product scope id. Can you please suggest any other better way. Thanks in advance for your help.
public List<Product> getAllHydroProducts()
throws RepositoryException {
String productTypeId = getProductTypeId(Group.GROUP_TYPE_NAME_HYDRO, getAllProductTypes());
String scopeId = getScopeTypeId(Group.SCOPE_TYPE_NAME_HTX, getAvailableScopes());
String productScopeId = getScopeTypeId(Group.SCOPE_TYPE_NAME_PROJECT, getAvailableScopes());
return getProductsByTypeAndScope(productTypeId , scopeId ,productScopeId );
}

I work under the assumption that you have several constants like Group.GROUP_TYPE_NAME_HYDRO, and all your methods are just like the one you show us, but with different constants (I believe you should add those other methods to your question, since without them there is no visible repeated code).
You have two possible scenarios (again, with more code would be easier):
1) You are only changing the product type constant, keeping the other two all the same in your other methods. If that's the case, you can just extract a more generic method like:
public List<Product> getAllProductsOfType(YourConstantType productType) throws RepositoryException {
return getProductsByTypeAndScope(
getProductTypeId(productType, getAllProductTypes()),
getScopeTypeId(Group.SCOPE_TYPE_NAME_HTX, getAvailableScopes()) ,
getScopeTypeId(Group.SCOPE_TYPE_NAME_PROJECT, getAvailableScopes())
);
}
Note that I don't know what your constants are, since you did't put them on your question, that's why YourConstantType is there.
Then your existing methods would just call this new one with their parameter.
2) Another scenario: You also have different scopes on your methods. In this case, I might go with a builder pattern
Also... is that a checked exception what I see there? I hope not ...

Related

What is the most intuitive way to pull an int from an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So, I have an object in a class called "arrays":
static arrays VideoGame = new arrays(arrays.product[9], arrays.price[9]);
and a function:
public static void getPrice(int price){
System.out.println("The cost is: " + price);
}
In my main file I call that function like this:
arrays.getPrice(arrays.price[9]);
Is there anything like
arrays.getPrice(VideoGame.price);
that lets you actually use the VideoGame object with the function?
EDIT: I forgot to say that "arrays" is a class I made with functions that create arrays.
I'm just going to go out on a limb and try to answer as best I can.
Assuming arrays is some custom class you made that just defines two arrays and offers getters/setters for those arrays:
Yes, what you seem to what to do is entirely possible although it seems pointless for all practical application. To do so you would just define a variable named "price" in your arrays class and make it public.
You could then use your exact code
arrays.getPrice(VideoGame.price);
However, by adding price to arrays this variable is then added to every instance of arrays. This can be avoided by adding the "static" keyword modifier to your new price variable which means that it will be instantiated at most once. Additionally, when you add the static keyword, I believe you no longer need to specify your specific object - meaning your code could now look even like:
arrays.getPrice(arrays.price);
By making a variable public, you avoid having to make a getter/setter for it, although this is discouraged.

In java, why do some developers use the underscore BEFORE for variable names? - Already seeing differences in peoples answers on this post [closed]

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 8 years ago.
Improve this question
I'm reading Martin Fowler's Refactoring book. In many of his refactoring examples, he is using variables that start with _varname. Why? Is this some old convention that is before my time? In the past year when I started learning Java, I have not seen anyone at work use this. Please advise as to where and why should this be used?
I'm already seeing differences in answers to this question...
Why does martin fowler do this in this code for extract method refactoring?
FROM:
void printOwing(double amount) {
printBanner();
//print details
System.out.println ("name:" + _name);
System.out.println ("amount" + amount);
}
TO:
void printOwing(double amount) {
printBanner();
printDetails(amount);
}
It is a convention to start the names of private fields of an object with an underscore in order to distinguish them from local variables in the code. This convention is not universal. Personally, I think that it is a bit superfluous when you have syntax highlighting that also shows the difference.
An alternative (although you could also use both) is to always reference members through this:
package org.foo.bar;
class Baz {
private String quux;
Baz (String quux) {
this.quux = quux;
}
String getQuux () {
return this.quux;
}
}
The convention is often used for private fields.
You don't have to use it, the most important is to be consistent, so if you are working on an existing code base, continue with that style.
Most likely, to distinguish local variables from class members.
EDIT: Now that you've added sample code, that is indeed the case.

At what point should large functions be made static? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When a function gets even moderately large, I generally change it to become static. For example, if a classes toString() gets pretty big, I usually change it to
public String toString() {
return ClassName.toString(this);
}
private static final String toString(ClassName c_n) {
//.........
}
If the function is not excessively large, is it overkill to do this?
EDIT
I'm getting shot down big time here. :)
I understand how the static modifier should be used in general (for singletons, for stuff unrelated to a specific instance, for utility functions). I'm asking this from an optimization point of view: To avoid a large function's byte code from being duplicated in memory, for each instance of a class. I'm obviously wrong about how it works.
Making the function static depending on the length of the function is totally wrong. Static variables/method are belong to class, not to instances.
So, if there are common functionality between the instances, not depending on any instances, then they can be static.
Here, you have made the toString() as static. But, this method should be describe an instance. Making this as static will give error prone results.
Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static. Otherwise, that should be instance method
You should make a method static if it doesn't depends of an instance of the class where it is declared. It has nothing to do with the length of the function.
Code (methods) is not replicated per instance, it doesn't need to as it is the same for all instances and is not modified.
Only instance data (properties) is replicated.

Is it acceptable if actual and formal parameters have the same name? [closed]

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 9 years ago.
Improve this question
like this:
myMethod(first, second)
public void myMethod(int first, int second)
My teacher said it's preferred not to name them the same. But I don't see the reason why? Is he wrong?
The variables should describe what they both are in their own contexts.
For example in the methods context (formal parameters) it might be compared1 and compared2. But in the calling context (actual parameters) it might be myPyjamas and myAuntsPyjamas. If they "mean" the same thing in both contexts then so be it.
So in this example they may be different:
Fanciness comparativeFanciness= comparePyjamas(myPyjamas,myAuntsPyjamas);
public static Fanciness comparePyjamas(Pyjamas compared1,Pyjamas compared2){
.....
}
for anyone wondering my pyjamas are very fancy
But in annother example they may be the same, because they both mean the same thing in both contexts:
setThrustDirection(thrustDirection);
public void setThrustDirection(Vector3d thrustDirection){
.....
}
caveat
It's often a good idea to avoid having a variable name the same as a field name (a.k.a. instance variable name) except in the constructor as you can end up shadowing the field (meaning you have to access the field as this.name and the variable as name)
Depends on the context. If there is a function to reverse a string
def reverseString(theString)
theString is kind of ok for that function but unlikely to be a good variable name in the context of calling that function. If it's a person's name then something like when it is being called
reverseString(firstName)
I think it's a possible shadowing problem. If the class has an instance variable with the same name as the parameter in the method definition, the coder needs to be careful and use this. when referring to the class level variable. I've seen lots of students forget that and wonder why the code doesn't work. I prefer unique names to prevent the problem.
The entire point of naming is to make the code more comprehensible, if your names do then they are more than acceptable, if they don't, maybe you was taught wrong...

java interface and return types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been trying for a while, but now I'm wondering if I can. Is it possible for a method in an interface to return a variable or an array without needing two interfaces or methods(if possible)?
Every method has to specify a return type and stick with it. There are no "union types" like "returns a String or an int[]".
If you really have a method that can return two different things, you can
make a wrapper type (StringOrIntArray) that can hold both
or
have the method return Object which can be pretty much anything, including arrays, and use instanceof at the caller to see what you got.
Both options are not particularly attractive. Maybe take a step back and rethink the bigger picture.
What is wrong with
interface Foo{
int foo1();
//or....
int[] foo2();
}
?

Categories