Java "this" in constructors - java

Well, this is a very basic question, I've never coded in java, but I'm writing a class for a friend... Having something like:
class myClass{
private string name;
public string getName() {
return this.name;
}
public void setName (int newValue) {
this.name = newValue;
}
private int number;
public int getNumber() {
return this.number;
}
public void setNumber (int newValue) {
this.number = newValue;
}
}
The way I was thinking of building the constructor was:
public myClass (string name, int numbers) {
this.name = name;
this.number = number;
}
My questions:
I'm using the same identifiers for the properties as for the parameters. Does "this." avoid any trouble here?
Is it better to use the set methods and, if so, should i use "this."?
Thank you very much

Yes, it avoids the name clash. In the constructor's context, the name name refers to the parameter, and the name this.name refers to the instance field.
Depends on what you mean by "better." Personally, I would make the name and number fields final, so the class is immutable. In my experience, it's better to start from an immutable class definition, and only move towards something mutable if there is a legitimate need to do so.

Yes, this differentiates between an instance variable and a method parameter variable of the same name.
There's always debate on whether constructor or setter initialization is better. If you're only going to set the name and number when you first create the object, and won't need to update those variables later, just using the constructor and leaving out the setters is probably better. And yes, in the setter, you'd need to use this if your parameter has the same name as the field you want to set.

There's no problem having the parameter using the same name as the field; the this. explicitly disambiguates and the program will behave as intended.
Depending on your program it may or may not be advantageous to use setters instead of directly writing fields. If you write the values directly in the constructor, then you bypass any runtime checks that you might have in your setters, which could potentially cause your object to hold data it normally can't. On the other hand, if your setter tries to do something with the old value, then you probably don't want to call the setter because, in the constructor, there might not be a meaningful old value. I'd say it's not clearly better or worse to set the fields in the constructor than to use setters, so long as you're careful to avoid breaking the class invariants.

Yes. Using the this keyword avoids issues.
If there are logic in the get/set methods, then you should use them instead. Otherwise, setting the values in the constructor is valid.

1) When the object scope property is the same as the argument name you must use this to differentiate between them. When there is a name clash the local var or argument will take precedence over the property.
For this reason, I don't like to ever have the exact same name for each as it can easily lead to bugs.
2) I also would use the setters from within the constructor, because if there ever needs to be a validation or some other operation done on the argument at time of setting you'll only have to make the change in one place. Otherwise it is duplication and violates the DRY (Don't Repeat Yourself) principle.
I would do:
public myClass (string name, int number) {
setName( name );
setNumber( number );
}

Yes, this. avoids problems. Some people recommend that way, such as Rogue Wave in their book The Elements of Java Style.
Other common ways of dealing with this are:
name members with a "m" or "m_" prefix
private string m_name;
private int m_number;
public myClass(string name, int number) {
m_name = name;
m_number = number;
}
call the parameters a different name, usually a single letter or abbreviated version of the member name
private string name;
private int number;
public myClass(string nam, int num) {
name = nam;
number = num;
}
But I prefer the way you are using now with this.

Related

Set custom variables from method

I have some String variables:
private String cur, last, avg, vol, shop;
I have method which accept String and gives me some result:
public void SomeMethod(String somestring)
{
//Here some action with `string`
System.out.print(result)
}
So i want to put result into one of String variables, but this variable must be named as value of somestring in my method. Some method which compare somestring with existent variables names. Is such a thing even possible?
You're talking about variable variable name. They're a native feature in PHP, but not in Java, however you can achieve similar functionality using a HashMap, or using Reflection. I'm going to show you the HashMap option, because frankly Reflection is the work of Satan.
Example
Now the way to implement this is like this:
public void someMethod(String name, String value)
{
values.put(name, value);
}
And you can retrieve them with
public void getValue(String name)
{
return values.get(name);
}
I won't write the code for you, because it's a simple transformation to get this to work in your use case.
A hint because I'm feeling nice
You can replace all of your String variables with a Map implementation. Then simply add the values to the Map, as and when the need arises.

Change from String to Object Name Java

I have 3 ints named A, B, and C. These are to be multiplied with the number 52. I have a string that contains the name of which int I want to mulitply (in example below my string type == A;.
I want to know if there is anyway to make the name of the String change into the name of the object/int that I wish to use.
What I have right now:
public class MultiplySomeNumbers{
int A = 100;
int B = 200;
int C = 300;
String type = "A";
final int multiplied = 52;
public int multiply(String type){
return multiplied* ____ //What goes here?
}
}
I DON'T want to do anything like this:
public int multiply(String type){
if(type.equalsIgnoreCase("A"){
return multiplied*A;
}else if(type.equalsIgnoreCase("B"){
...
Any help would be greatly appreciated!
No, that is not possible (maybe with Reflection, but it's still a no-go). Every single situation where you think you might need this does not need it.
There are several issues, but here are a few:
No intellisense for those generated variables
Very unclear code
Ambiguous naming (what if you create a new variable that happens to have the same name as a generated one?)
etc etc etc
You will have to go with your second option.
We might be able to provide a different solution, but the question is rather unclear as it is right now. Perhaps you could expand a little so we can help you better.
Although there may be a way to do this with reflection, it's probably a really bad idea. If you really can't just pass in the value, but want to specify a limited set of constants by which you can multiply, I'd recommend creating an enumerated type.
Taking your same example, but using an enum instead of trying to look up constants by name, would look something like this:
public class MultiplySomeNumbers{
public enum Type {
A(100),
B(200),
C(300);
private final int value;
private Type(int value) {
this.value = value;
}
public final int getValue() {
return value;
}
}
Type type = Type.A;
final int multiplied = 52;
public int multiply(Type type){
return multiplied * type.getValue();
}
}
While there is nothing wrong with using an enum for this solution, it may not be the most flexible solution. Enums are, by design, effectively immutable ... they are intended to have the sense of constants. If you wish to change the value of a variable by multiplying its value by 52, then this is not possible with enums.
What I think you really should do is use a HashMap. A Map is a key / value pair.
The key is the "variable's name"; a String quantity
The value is the "variable's current value"; an Integer quantity (not int!)
Your Map can be declared like this:
Map<String, Integer> myVariables = new HashMap<String, Integer>();
then to load your variables into the map, you simply call the Map's put() method:
myVariables.put("A", Integer.valueOf(100));
myVariables.put("B", Integer.valueOf(200));
myVariables.put("C", Integer.valueOf(300));
Retrieving the value of a variable is as simple as using the get() method with your variable name as the key:
int val = myVariables.get("A").intValue();
Notice that I have chosen to box and unbox the primitive int values myself rather than rely on autoboxing. This is just a personal choice. It does trade off conciseness, but I'd rather see what's actually happening.
In my opinion, using reflection to determine a class field to access dynamically at run time is wholly unsatisfactory and should be avoided ... most especially since using the Java Collections API enables a statically typed, type safe solution that can be checked at compile time.
You can't check for a variable's name. For more information look here, there are some good answers:
Java Reflection: How to get the name of a variable?
But maybe a HashMap can help you, where you store "A", "B", "C" as keys and the respective numbers as value.
edit: Okay, maybe with something like this http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html it could be possible.

What is the Java convention for using get methods inside other methods of the same class?

After I have written a get method in a java class, is it better to use the get method in the same class or the variable itself?
For example:
if(a.getWidth()>this.getWidth())
or:
if(a.getWidth()>this.width)
Also I am confused if i should be using the this.anything so much. It seemed easier to read when comparing objects of the same type to each other.
is it better to use the get method in the same class or the variable
itself?
IMHO use the variable. Accessor methods are primarily for other objects to use.
Also I am confused if i should be using the this.anything so much. It
seemed easier to read when comparing objects of the same type to each
other.
It's not always required for you to explicitly use the this reference..it's mainly used for readability, like you said.
I think that using the getter methods are better for mantainability. Consider the Null Object pattern which a way to achieve is by making this:
public String getName(){
if (this.name == null){
this.name = "";
}
return this.name;
}
This should save you from checking up a lot of null before operating with the variable.
public boolean isCorrect(){
if(this.name != null && this.name.isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
I'd rather write this:
public boolean isCorrect(){
if(this.getName().isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
Of course, this depends if you adopt this pattern.
Also consider that you have
double width;
double height;
public double getWidth(){
return this.width;
}
but at some point you decide to change it for a class but still have the methods so your program doesn't break down.
Dimension dimension;
public double getWidth(){
return this.getDimension().getWidth();
}
// etc...
Finally (as commented by MadProgrammer), when you use inheritance, the methods can be overridden to represent better the intended object.
1) It may seem from inside a class that there is no difference between using field and getter but what if a getter is overridden by a subclass?
class A {
String name;
String address;
String getName() {
return name;
}
String getAddress() {
return address;
}
String getDescription() {
return name + " " + address;
}
}
class B extends A {
String country;
#Override
String getAddress() {
return super.getAddress() + ", " + country;
}
}
B.getDescription() is expected to return an extended address but it wouldnt. It would if A.getDescription() was implemented as
return getName() + " " + getAddress();
2) I personally dont use this for readability because IDE marks this with a different color
The use of this is not necessary unless you have a case (such as in a constructor) where a parameter has the same name as a field.
For accessing properties, it may be beneficial in the long run to use the public getters, because you may want to add some form of processing to the property, and if you use getters everywhere, you only have to make that change once.
If your get method returns the data with some formatting, you have to use the get method, otherwise, the variable itself will be fine to use.
this is only required if your method parameters are same as your member variables, otherwise, this is not compulsory.
For example:
private String str;
public void setString(String str){
this.str = str; // here this.str is necessary because this represents the memeber variable
}
public String getString(){
return this.str; // here this is optional and you can simply omit it
}
You can use either the accessor or the variable itself, its one of those personal preference things.
Some people like to use the variable itself because you don't have the overhead of calling a function. But, if you have any restrictions on the values your variables can be, sometimes it is just cleaner to only use your accessors and mutators; especially if you are going to be subclassing. But its one of those things that can go either way.
The way that I like to use the this keyword, is I always use it for instance variables. I find that it makes the code easier to read because you can visually determine where you are using instance variables, and where you are using local variables. Again this is a personal preference thing.
The main thing is to make sure your code is clean, and readable. Also, make sure that you are following whatever coding standard your organization is using, and be sure to be consistent.

Any standard pattern or strategy for making Null Object Immutable

In java, we prefer null object pattern than cluttering the code with not null check in all referencing. Recently we faced a problem over using null object by keeping a singleton object.
Assume we have Person class as below
public class Person {
public String firstName;
public String lastName;
public boolean isNull() {
return false;
}
public static final Person NULL = new Person() {
public boolean isNull() { return true; }
}
}
In this case, though I have declared NULL object as final, I can still modify the member variable and its available globally.
Person nullRef = Person.NULL;
Person.NULL.firstName = "sample";
System.out.println(nullRef.firstName);
In this case, its just three fields and I could solve mutability problem by overriding those three getter methods. But pratically there will be many fields which will be tough to override all corresponding getter methods.
Is there any standard pattern or strategy to solve this mutability issue in NULL objects?
Use Optional From Google Guava library
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
Quoting the library documentation:
Besides the increase in readability that comes from giving null a
name, the biggest advantage of Optional is its idiot-proof-ness
This is more natural way of dealing with null objects
Optional Google Guava
You need to have two levels of interface: One for the immutable part (only getters and immutable methods) and one for mutable parts that extends the immutable interface. Then the code needs to be refactored to only use the most restrictive interface possible in all relevant places.
So
public interface ImmutablePerson {
final String getFirstName();
}
public interface MutablePerson extends ImmutablePerson {
final void setLastName(final String newName);
}
Yes, now MutablePerson "is a" ImmutablePerson, but only when used as one :)
Additionally, the isNull check indicates that you need to think more about inversion of control.
To be concrete:
When you find yourself writing code like
if (!person.isNull()) {
person.setLastName("Foo");
}
You should instead just use your Null Object and think of it as a neutral element insted. Like so:
First:
final Person NullPerson = new Person() {
void setLastName(final String newName) {
// Do nothing, this is a neutral (Null) object
}
}
...and then later:
// Never need to check for isNull ever again - null objects just decide to ignore your request
person.setLastName("Foo");
You need to make all the fields "private" so that these are not accessible outside except for the getter code.
You need to modify "setter" methods and not the getter ones for making it immutable.
For eg.
public String setFirstName(String name){
if(!isNull()){
firstName = name;
}
}

good software practice - get and set methods

as you can see the class below declares 2 private instance variables and 2 get & 2 set methods associated with each private member to allow for manipulation and validation of them.
My question is: which is better to use in the constructor deceleration, the instance variables directly as shown in the snippet below or to use the set methods associated with them and also which is promote good software practices to use in the toString method, the instance variables or their getter methods?
thank you for your time.
public Class Employee {
private String firstName;
private String lastName;
public Employee (String first, String last)
{
firstName = first;
lastName = last;
}//end of constructor
public void setFirstName(String first)
{
firstName = first;
}//end of method setFirstName
public String getFirstName()
{
return firstName;
}
public void setLastName(String last)
{
lastName = last;
}//end of method setLastName
public String getLastName()
{
return lastName;
}//end of method getLastName
public String toString()
{
return String.format ("%s: %s %s\n", "Employee Name: ", firstName, lastName);
}//end of method toString
}//end of class Employee
I tend to favour initialisation via construction. By using this method and providing appropriate checks (compilation time via final and runtime via null checks or similar) you can ensure your object is properly and completely instantiated.
Using the final keyword on your fields will make the compiler check that you've assigned a value to that field upon construction. It does mean that field is immutable, but it's surprising how often you require that.
I would be careful with providing getters for everything. If you're continually providing and using getters, that suggests that you're pulling data out of your object and manipulating it outside that object. Remember - a key principle of OO is getting objects to do things for you, rather than asking them for data and doing it yourself.
Rule #1, always limit the access to the least necessary, i.e. unless you explicitly need to change the values of the first/last names, make the object immutable (constructor with parameters, no setters only getters)
In general I tend to avoid calling non-static methods from the constructor (since the object isn't fully initialized at that stage). If the setter methods only sets a field to the parameter value, like above, I'd just set it in the constructor (i.e. not call the setter). If the setter is more complex, I'd try to factor out the logic to a static helper method, and use it both from the constructor and the setter methods. Something like:
int field_;
Constructor(int initialValue) {
field_ = helper(initialValue);
}
public void setField(int value) {
field_ = helper(value);
}
// not really complex, but avoid duplication of logic
private static int helper(int value) {
return 2*value;
}
If you expect your class to be extended (and the getter/setter overridden), it is best to use the methods instead of the variables.
NOTE: I'm not sure what happens exactly in the constructor, you are probably better off setting the variable directly.
You can mark the getter/setter as final and then you don't have to worry about overrides. Still a good practice to use those methods instead of direct access as you can put breakpoints or debug statements there more easily
I would use the setter. Sometimes you have extra code in the setters. For example, the setter for a list might also hook the list's Changed event, and by not using the setter, you will not capture the Changed event.

Categories

Resources