I'm a bit unsure of how I implemented something, and am hoping for some feedback.
I have a class, Metric, and it needs to multiply some numbers by a given percentage before returning them. They are returning BigDecimal, so I created class variable BigDecimal to store that percentage, then multiply them together on the return.
public class Metric extends Model {
private static final BigDecimal percentage = new BigDecimal("1.2");
public BigDecimal getMetric() {
return new BigDecimal(getValue()).multiply(percentage);
}
}
Is there any issue with a static final and declaring it right away with new? Also, I tried to research if BigDecimal is thread safe, and I couldn't find a for sure answer. Feedback on that would be appreciated.
BigDecimal is immutable and thus thread-safe. Also, there is no problem with a static final value like that -- in fact, it's recommended.
Related
Do I need to synchronize substracting when calculating remain value in constructor?
public OrderFillSummary(final BigDecimal total, final BigDecimal filled) {
AssertUtils.isGtZero(total, "total");
AssertUtils.isGtZero(filled, "filled");
this.total = total;
this.filled = filled;
this.remain = this.total.subtract(this.filled);
}
BigDecimal (and BigInteger) are immutable, and you're in a constructor, so, basically, no - though your question lacks a lot of detail. If multiple threads are even involved (if not, synchronize is for multiple threads), then explain how, though just about anything I can imagine you might say would result in the answer: No, you don't need to do that.
I have a dilemma because I don't know what is better solution. I have a static variable.
I wonder what is the best practice of declaring these variables.
Let's suppose that I have such a variable in myStatic class.
public class myStatic(){
public static int integer = 0;
/* get value */
public int getInteger() {
return integer;
}
/* set value */
public void setInteger(int nInteger) {
integer = nInteger;
}
}
Now I must increment this variables or decrements.
How to do it correctly?
1)
myStatic.integer++;
2)
myStatic mystatic = new myStatic();
int integer = mystatic.getInteger();
int nInteger = integer+1;
mystatic.setInteger(iInteger);
Is better using solution 1 or 2?
I would go with number 1, 100%, maybe just because I'm lazy, but kind of also because of:
Don't repeat yourself
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Keep it simple, stupid
This principle has been a key, and a huge success in my years of software engineering. A common problem among software engineers and developers today is that they tend to over complicate problems.
You aren't gonna need it
Principle of extreme programming (XP) that states a programmer should not add functionality until deemed necessary.
If that variable needs to be accessed everywhere and at any time, you should go with option 1.
It will act as an Environment variable even tho its not reallyyyy the same thing.
more info on env vars:
https://en.wikipedia.org/wiki/Environment_variable
Static variables need not be accessed through an object. Infact it is a waste of code.
Consider this :
public class MyStatic {
public static int i = 0;
}
You can directly access the static variable like this :
private MyStatic myStatic = null;
myStatic.i++;
This is because, the JVM doesn't even care about the object for a static property.
since static vars are class variables, they can be manipulated by any object, unless you declare a static variable as private, you had to access to it via public static methods. Then, your first approach is correct, in the second the method getInteger() does not work.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
I recomend you to read about the singleton pattern design.
I don't think I'm approaching this the right way. I'm supposed to create a class that allows users to enter in any number not matter how big it is (Of course, with the restrictions of memory it's not really infinite). I have some code but I'm pretty sure the quality is crap. I seem to be having the most trouble with a string and have been avoiding it. I'll only post what I have worked on. I just need help clearing it up because I don't think I'm going in the right direction. Here is what my code has so far. I apologize. I'm not a very seasoned coder.:
public class InfiniteInteger implements Comparable<InfiniteInteger> {
// TO DO: Instance Variables
public final int BigNumbers;
public final String Infinite;
public final int []integerArray;
public InfiniteInteger(String s) {
// TO DO: Constructor
Infinite=s;
}
public InfiniteInteger(int anInteger) {
// TO DO: Constructor
BigNumbers=anInteger;
integerArray= new int[anInteger];
}
public int getNumberOfDigits() {
// TO DO: return an integer representing the number of digits
of this infinite integer. //
int NumberOfDigits=0;
for(int i=0; NumberOfDigits<0;i++){
}
return BigNumbers;
}
/**
* Checks whether this infinite integer is a negative number.
* #return true if this infinite integer is a negative number.
* Otherwise, return false.
*/
public boolean isNegative() {
// TO DO
if(isNegative()) {
return true;
} else return false;
}
Do I need to convert the string to int in my first constructor. I also had made an array previously in the string constructor but it caused a whole lot of grief so I got rid of it and just put one in the second constructor.
You can use a BigInteger for that. It uses an bitarray with varying length.
Operations on BigInteger's are slower but will work, regardless of the number (as long as it is an integer). And furthermore BigInteger operations are optimized (for instance using special CPU instructions)...
On a sidenote if people mean any number, they sometimes mean any resonable number. In that case the range of a long is in many cases sufficient.
Use the Java built-in class BigInteger, from the Javadoc BigInteger is for
Immutable arbitrary-precision integers.
What you are trying to accomplish is already made in BigInteger class. Maybe examining it's source might be useful when creating a simpler version of it :
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/math/BigInteger.java
I am just beginning to understand the concept of Enumeration in Java, but I'm still kind of skeptical of my understanding.
For something such as: Direction, I can understand its use, where I use numbers to represent a direction, but never really need to do arithmetic with it.
However, given something like sizes, where the sizes are constants, but I will need to do arithmetic, would final declarations be more appropriate? Or attempting to do an enum with
public int getSize()
{
return size;
}
Here is my code for my current declarations:
private static class Size
{
private static final int BOX = 5; //5 pixels
private static final int GRID = 30; //amount of boxes
private static final int GAME = BOX * GRID; //total size in pixels
}
Note that this is a private nested class,
I also use these values when doing drawing, and a parameter is an integer, I simply do Size.BOX, however, is Enumeration still more appropriate for this? and how should I go about it?
The entire point of enums is to make your code more readable and maintainable. You should use them anytime you need to represent an enumerated set of elements.
However, in this case, final/constant is more appropriate since you are representing a value (number of boxes, and number of pixels) not an enumerated set. If, say, you wanted to store types of boxes (metal box, cardboard box, ect) then you would use enums.
You are correct in believing that enums are inappropriate when dealing with arithmetic values. Enums are useful for representing a set (in the programming and the mathematical sense) of uniquely defined items that relate to each other.
Using an enum to replace a size value in this way is nonsensical in context. If your item is 30 units large, then you need to represent it as such, using an integer or the like.
An example of where to use an enum in a similar context would be if you had 5 strictly defined types of items of different sizes - in this case, you could make each of the 5 an instance of your enum - but they would still have a size variable internally, with a different value for each.
Takes a bit of interface chicanery, but this works. Not necessarily the best approach in your situation, but this was a neat little exercise.
/**
<P>{#code java EnumXmpl}</P>
**/
public class EnumXmpl {
public static final void main(String[] igno_red) {
System.out.println("BOX: " + eShape.BOX.getSize());
System.out.println("GRID: " + eShape.GRID.getSize());
System.out.println("GAME: " + eShape.GAME.getSize());
}
}
interface ShapeConstants {
int iBOX_PXLS = 5;
int iGRID_BOXES = 30;
}
enum eShape implements ShapeConstants {
BOX(iBOX_PXLS),
GRID(iGRID_BOXES),
GAME(iBOX_PXLS * iGRID_BOXES);
private final int iSz;
eShape(int i_size) {
iSz = i_size;
}
public final int getSize() {
return iSz;
}
}
Output:
[C:\java_code\]java EnumXmpl
BOX: 5
GRID: 30
GAME: 150
I've been using PMD to help spot potential problems in my Java code, and I've been finding its advice to be split between the useful, the idiosyncratic, and the "WTF?!".
One of the things it keeps telling me to do is to use the final keyword for literally every variable I can attach it to, including input parameters. For actual constants this seems sensible, but for other stuff it just strikes me as odd, possibly even a tad counterproductive.
Are there concrete advantages/disadvantages to hanging final on every variable declaration you possibly can?
"Every variable declaration you possibly can" sounds a bit extreme, but final is actually beneficial in many ways. Sometimes I wish that final was the default behavior, and required no keyword, but true "variables" required a variable modifier. Scala adopted something like this approach with its val and var keywords—using val (the final-like keyword) is strongly encouraged.
It is especially important to carefully consider whether each member variable is final, volatile, or neither, because the thread safety of the class depends on getting this right. Values assigned to final and volatile variables are always visible to other threads, without using a synchronized block.
For local variables, it's not as critical, but using final can help you reason about your code more clearly and avoid some mistakes. If you don't expect a value to change within a method, say so with final, and let the compiler find unnoticed violations of this expectation. I'm not aware of any that do currently, but it's easily conceivable that a JIT compiler could use this hint to improve performance too.
In practice, I don't declare local variables final whenever I could. I don't like the visual clutter and it seems cumbersome. But, that doesn't mean it's not something I should do.
A proposal has been made to add the var keyword to Java aimed at supporting type inference. But as part of that proposal, there have been a number of suggestions for additional ways of specifying local variable immutability. For example, one suggestion was to also add the key word val to declare an immutable variable with inferred type. Alternatively, some advocate using final and var together.
final tells the reader that the value or reference assigned first is the same at any time later.
As everything that CAN be final IS final in this scenario, a missing final tells the reader that the value will change later, and to take that into account.
This is a common idiom for tools like PMD. For example, below are the corresponding rules in Checkstyle. It's really a matter of style/preference and you could argue for both sides.
In my opinion, using final for method parameters and local variables (when applicable) is good style. The "design for extension" idiom is debatable.
http://checkstyle.sourceforge.net/config_misc.html#FinalParameters
http://checkstyle.sourceforge.net/config_design.html#DesignForExtension
http://checkstyle.sourceforge.net/config_coding.html#FinalLocalVariable
PMD also has option rules you can turn on that complains about final; it's an arbitrary rule.
If I'm doing a project where the API is being exported to another team - or to the world - leave the PMD rule as it stands. If you're just developing something that will forever and always be a closed API, disable the rule and save yourself some time.
Here are some reason why it may be beneficial to have almost everything tagged as final
Final Constants
public static class CircleToolsBetter {
public final static double PI = 3.141;
public double getCircleArea(final double radius) {
return (Math.pow(radius, 2) * PI);
}
}
This can be used then for other parts of your codes or accessed by other classes, that way if you would ever change the value you wouldn't have to change them one by one.
Final Variables
public static String someMethod(final String environmentKey) {
final String key = "env." + environmentKey;
System.out.println("Key is: " + key);
return (System.getProperty(key));
}
}
In this class, you build a scoped final variable that adds a prefix to the parameter environmentKey. In this case, the final variable is final only within the execution scope, which is different at each execution of the method. Each time the method is entered, the final is reconstructed. As soon as it is constructed, it cannot be changed during the scope of the method execution. This allows you to fix a variable in a method for the duration of the method. see below:
public class FinalVariables {
public final static void main(final String[] args) {
System.out.println("Note how the key variable is changed.");
someMethod("JAVA_HOME");
someMethod("ANT_HOME");
}
}
Final Constants
public double equation2Better(final double inputValue) {
final double K = 1.414;
final double X = 45.0;
double result = (((Math.pow(inputValue, 3.0d) * K) + X) * M);
double powInputValue = 0;
if (result > 360) {
powInputValue = X * Math.sin(result);
} else {
inputValue = K * Math.sin(result); // <= Compiler error
}
These are especially useful when you have really long lines of codes, and it will generate compiler error so you don't run into logic/business error when someone accidentally changes variables that shouldn't be changed.
Final Collections
The different case when we are talking about Collections, you need to set them as an unmodifiable.
public final static Set VALID_COLORS;
static {
Set temp = new HashSet( );
temp.add(Color.red);
temp.add(Color.orange);
temp.add(Color.yellow);
temp.add(Color.green);
temp.add(Color.blue);
temp.add(Color.decode("#4B0082")); // indigo
temp.add(Color.decode("#8A2BE2")); // violet
VALID_COLORS = Collections.unmodifiableSet(temp);
}
otherwise, if you don't set it as unmodifiable:
Set colors = Rainbow.VALID_COLORS;
colors.add(Color.black); // <= logic error but allowed by compiler
Final Classes and Final Methods cannot be extended or overwritten respectively.
EDIT: TO ADDRESS THE FINAL CLASS PROBLEM REGARDING ENCAPSULATION:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making its constructor private.