Best Practices -- Constructors and Setters - java

I have an IDE which I can use to automatically create constructors and setters for instance variables, but I was wondering if the way that it creates them is possibly not best practice. Here is what it does:
private String partNum;
private String partDesc;
private int quant;
private double price;
public Invoice( String partNum, String partDesc, int quant, double price )
{
this.partNum = partNum;
this.partDesc = partDesc;
this.quant = quant;
this.price = price;
}
It's the 'this.name' thing that I'm worried about, as well as the constructor labeling the parameters the same names as the variables it's constructing. The setter also does the same thing -- uses a parameter name that's the same as the name of the variable it's setting, and uses this.name.
So, is there anything wrong with this?

That is my preferred way. Otherwise, you would have to think of different arbitrary names for the input parameters and that turns into a hassle.

What you are witnessing is pretty standard Java practice, and is even mentioned in the Java Language Specification:
If a name declared as a local variable is already declared as a field
name, then that outer declaration is shadowed (§6.3.1) throughout the
scope of the local variable. Similarly, if a name is already declared
as a variable or parameter name, then that outer declaration is
shadowed throughout the scope of the local variable (provided that the
shadowing does not cause a compile-time error under the rules of
§14.4.2). The shadowed name can sometimes be accessed using an
appropriately qualified name.
For example, the keyword this can be used to access a shadowed field
x, using the form this.x. Indeed, this idiom typically appears in
constructors (§8.8):
class Pair {
Object first, second;
public Pair(Object first, Object second) {
this.first = first;
this.second = second;
}
}
In this example, the constructor takes parameters having the same
names as the fields to be initialized. This is simpler than having to
invent different names for the parameters and is not too confusing in
this stylized context. In general, however, it is considered poor
style to have local variables with the same names as fields.
When local variables to a method have the same name as class variables, they effectively 'shadow' or hide those variables. But you can still access the class variables by referring to them via the this context scope.

No. that is not at all a problem. These are just variable names. The lvalue and rvalue are going to maintain their uniqueness.

No there's nothing wrong. The this keyword resolve the ambiguity because it tells the compiler that the l-value you are setting is the member variable(es. this.partNum) and not the input parameter(partNum).
If this is a bad practice, that's more a matter of personal taste. Some people don't like to use the same name for both the member variable and the input parameter. Personally I've use this often for several reasons:
avoid proliferating of names
Eclipse start autocompleting the name if it starts with "this." :)

Related

Different ways to write getter and setter?

I have seen accessor methods using this and ones that don't. Do they produce the same results?
For example:
public setName(string name){
this.name=name;
}
public setName(string n){
name=n;
}
public void getName{
return name;
}
public void getName{
// is "this" here useless?
return this.name;
}
What are the differences? Which way is better?
You need to use this when you want to reference the class level variable which has the same name as the local variable in the method. It is only required when the variables have the same name. You can always use this if you want, but it isn't necessary. And the difference between
this.s = s;
and
s = myString;
is just a style preference, and not a big important one that wars are fought over.
Yes, they are entirely equivalent in their function and resulting bytecode (afaik).
The ’this’ keyword is only used when referencing an instance variable (a non-static variable that is defined with the class or relevant super-classes), in order to differentiate it from a local variable of the same name. Omitting the ’this’ keyword in such a situation would assign the local variable to itself.
Regarding your edit about what is better, some prefer not naming variables the same, but some like using ’this’ to explicitly refer to an instance variable. It comes down to a matter of taste and readability.
It is the same.
If your method has a variable with the same name of a class field (eg "name") you need to write "this.name" to refer to class field, because writing only "name" you are refering to method variable.
So in the second example you wrote, you have two different names ("name" and "n") and you don't need to write "this.name".
By the way, in the second example, you are free to say "this.name" if you want, but it is not mandatory... (in my opinion it is not mandatory, but it is a great way to make your code more easy to read).
At the end choose what method you prefer.
In my mind the first one is a more "elegant" way to write code.

Initializing Fields Value in Constructor Versus in Fields Declaration [duplicate]

This question already has answers here:
Initialize class fields in constructor or at declaration?
(16 answers)
Closed 9 years ago.
As we know, in java and some other object-oriented programming languages, fields value can be set in constructor or be initialized in fields declaration statements. I want to know the essential differences between the two ways above. And what conditions I should initialze fields by constructor and what condtions I should't.
Thanks for your help.
The advantage with an argumented constructors is that you can set the field values as per the inputs but you cant do the same with initialized fields.
So if you want to create different objects with different attribute values then go for constructors with arguements. And assign the values of instance variables in your constructor.
If you simply want all the instance variables to have some default value, then assign the values at declaration.
The convention is to initalize a field in the constructor. A constructor is there to essentially build the object. It only follows that building implies the instanciation, or assignment, of it's members. It also means that all your logic for creating the object is in one place, which is desirable. For example..
public NewObj(String something, int somethingElse)
{
this.something = something;
this.somethingElse = somethingElse;
// All the logic is in one place. This is especially useful
// when dealing with huge classes.
}
We follow the conventions like this so when another programmer looks at our work, they will know instantly where to look for the logic that creates the class. By placing it in the field declarations (or worse, in both the field declarations and the constructor) you are confusing that convention.
Exceptions I've seen
When creating static final variables in a class, I've found that they are usually created in the field declaration. For example..
public class NewObj
{
public static final int EMPTY_OBJ = 1;
public static final int SPECIAL_OBJ = 2;
}
final fields are preferred as they are easier to reason about and final fields can only be set in the constructor. I suggest fields which mandatory should be in the constructor.
If you have fields which you want to be able to change later, use setters.
If you have to set the fields by name, there is no easy way to this with a constructor. There is the #ConstructorProperties but few class have implemented this. Java 8 wills support access to argument names via reflection, but for now setters are easier.
Note: there are two alternatives.
You can use static factory methods. This can not only have meaningful names but can return sub-classes
You can use a builder class. This gives you more options for how you define and constructor your object. This is particularly useful if you have lots of mandatory fields.
Using Constructors with Arguments , you can initialize the fields during the object creation with the input custom values provided.
This is often helpful when you want fields to have different values .
For Example:
class Employee{
String mName;
Employee(String name)
{
mName=name;
}
This can help you to initialize Employee names easily while creating Employee Object.

using a variable in two different java classes

I was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)

What is the difference between field, variable, attribute, and property in Java POJOs?

When referring to internal private variables of Java POJOs that have getters/setters, I've used the following terms:
field
variable
attribute
property
Is there any difference between the above? If so, what is the correct term to use? Is there a different term to use when this entity is persisted?
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
A data member of a class. Unless specified otherwise, a field is not static.
property
Characteristics of an object that users can set, such as the color of a window.
attribute
Not listed in the above glossary
variable
An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See also class variable, instance variable, local variable.
Yes, there is.
Variable can be local, field, or constant (although this is technically wrong). It's vague like attribute. Also, you should know that some people like to call final non-static (local or instance) variables
"Values". This probably comes from emerging JVM FP languages like Scala.
Field is generally a private variable on an instance class. It does not mean there is a getter and a setter.
Attribute is a vague term. It can easily be confused with XML or Java Naming API. Try to avoid using that term.
Property is the getter and setter combination.
Some examples below
public class Variables {
//Constant
public final static String MY_VARIABLE = "that was a lot for a constant";
//Value
final String dontChangeMeBro = "my god that is still long for a val";
//Field
protected String flipMe = "wee!!!";
//Property
private String ifYouThoughtTheConstantWasVerboseHaHa;
//Still the property
public String getIfYouThoughtTheConstantWasVerboseHaHa() {
return ifYouThoughtTheConstantWasVerboseHaHa;
}
//And now the setter
public void setIfYouThoughtTheConstantWasVerboseHaHa(String ifYouThoughtTheConstantWasVerboseHaHa) {
this.ifYouThoughtTheConstantWasVerboseHaHa = ifYouThoughtTheConstantWasVerboseHaHa;
}
}
There are many more combinations, but my fingers are getting tired :)
If your question was prompted by using JAXB and wanting to choose the correct XMLAccessType, I had the same question. The JAXB Javadoc says that a "field" is a non-static, non-transient instance variable. A "property" has a getter/setter pair (so it should be a private variable). A "public member" is public, and therefore is probably a constant. Also in JAXB, an "attribute" refers to part of an XML element, as in <myElement myAttribute="first">hello world</myElement>.
It seems that a Java "property," in general, can be defined as a field with at least a getter or some other public method that allows you to get its value. Some people also say that a property needs to have a setter. For definitions like this, context is everything.
Dietel and Dietel have a nice way of explaining fields vs variables.
“Together a class’s static variables and instance variables are known as its fields.” (Section 6.3)
“Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.” (Section 6.4)
So a class's fields are its static or instance variables - i.e. declared with class scope.
Reference - Dietel P., Dietel, H. - Java™ How To Program (Early Objects), Tenth Edition (2014)
If you take clue from Hibernate:
Hibernate reads/writes Object's state with its field.
Hibernate also maps the Java Bean style properties to DB Schema.
Hibernate Access the fields for loading/saving the object.
If the mapping is done by property, hibernate uses the getter and setter.
It is the Encapsulation that differentiates means where you have getter/setters for a field and it is called property, withthat and we hide the underlying data structure of that property within setMethod, we can prevent unwanted change inside setters. All what encapsulation stands for...
Fields must be declared and initialized before they are used. Mostly for class internal use.
Properties can be changed by setter and they are exposed by getters. Here field price has getter/setters so it is property.
class Car{
private double price;
public double getPrice() {…};
private void setPrice(double newPrice) {…};
}
<class name="Car" …>
<property name="price" column="PRICE"/>
</class>
Similarly using fields, [In hibernate it is the recommended way to MAP using fields, where private int id; is annotated #Id, but with Property you have more control]
class Car{
private double price;
}
<class name="Car">
<property name=" price" column="PRICE" access="field"/>
</class>
Java doc says:
Field is a data member of a class. A field is non static, non-transient instance variable.
Field is generally a private variable on an instance class.
The difference between a variable, field, attribute, and property in Java:
A variable is the name given to a memory location. It is the basic unit of storage in a program.
A field is a data member of a class. Unless specified otherwise, a field can be public, static, not static and final.
An attribute is another term for a field. It’s typically a public field that can be accessed directly.
In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion which are called Attributes.
A property is a term used for fields, but it typically has getter and setter combination.
Variables are comprised of fields and non-fields.
Fields can be either:
Static fields or
non-static fields also called instantiations e.g. x = F()
Non-fields can be either:
local variables, the analog of fields but inside a methods rather than outside all of them, or
parameters e.g. y in x = f(y)
In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.
Basic Example (excuse me for my syntax, I am just a beginner)
Class {
//fields
method1 {
//non-fields
}
}
Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.
If you want to understand more deeply, you can head over to the source below:-
http://sajupauledayan.com/java/fields-vs-variables-in-java
Java variable, field, property
variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field - member variable or data member. It is a variable inside a class(class variable or instance variable)
attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
[Objective-C attributes]
property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin
For example Kotlin sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
[Swift variable, property...]
The question is old but another important difference between a variable and a field is that a field gets a default value when it's declared.A variable, on the other hand, must be initialized.
My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..
A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:
public class Variables {
List<Object> listVariable; // declared but not assigned
final int aFinalVariableExample = 5; // declared, assigned and said to be final!
Integer foo(List<Object> someOtherObjectListVariable) {
// declare..
Object iAmAlsoAVariable;
// assign a value..
iAmAlsoAVariable = 5;
// change its value..
iAmAlsoAVariable = 8;
someOtherObjectListVariable.add(iAmAlsoAVariable);
return new Integer();
}
}
So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:
A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.
A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.
I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.

Advantage of using "this."

I've read many large projects in OOP, and I notice that a lot of them use this.[variable], [ClassName].[staticVariable]. For example:
public class ABC {
private float mX;
public static float y;
public float getX() {
return this.mX;
}
public float doSomethingWithY() {
return ABC.y;
}
}
And even with Eclipse auto-generated Getters & Setters feature, it also comes with this.[variable], although it's unnecessary, because no local variable is declared there.
Is there any advantage when using these notations, or it's just a code style?
EDIT so some people don't misunderstand. I know what this and [ClassName].[staticVariable] stand for. But in this case, it's unnecessary. The question is: Even if it's unnecessary, why do guru coders still add it? When they need to update/fix a huge project, will there be any advantage and disadvantage?
Basically with this, you KNOW for sure that you are working with a class attribute, not with a variable created inside the method or maybe received as a parameter.
And also, it helps in case you have a local var with the same name.
And the final reason: readability.
It's necessary in some circumstances, for example this. is required when you need to use a member variable rather than a local method parameter of the same name.
It's also necessary for static variables where you need to be specific which class you want to get the static variable from (many classes could define static variables with the same name).
Apart from the necessary cases, it's really a matter of coding style. My recommendation is to use it whenever it helps to resolve potential ambiguity.
In complicated methods, it's sometimes nice to make a distinction between instance variables in this class, and local variables in a particular function. This distinction is immediately obvious when you use "this."
For small pieces of code it doesn't matter but sometimes this can happen:
public float getX() {
....
int mX = someFunc()
...
return mX;
}
In this case, the local value is returned instead of the member variable.
You normally want to be explicit and say this.mX. However, you shouldn't have huge functions anyway.
this.? '?' is a member variable, this is a reference to the current object.
see this
Its syntax,if you want to access instance variable of a class use the (reference of the object).(instance variable name) .Like
A a= new A();// for non static class,this for the current object
a.(instance variable name)
// for non static class do the same but use (class name).variable name

Categories

Resources