1

This question may seem dumb at first, but after having worked with different person, I see everyone seems to have their own, different knowledge about it, so here's my question.

So now I'm wondering what is the best way to do it, and why ("why" is more important for me):

I'm wondering about two methods to write Java code:

  1. Do you always pass Object or can you pass primitive data type ?
  2. Do you call variables using this.name, name or getName() inside your class instance ?

    public class MyClass {
        private String someStr;
        private int someNumber;
        private Integer someOtherNumber; // int, Integer ? which one to choose ?
    
        public MyClass(String someStr, int someNumber, int someOtherNumber) { // int someNumber ? Integer someNumber ? why ?
            this.someStr = someStr; // Here, it's clearly this.{name} = {name} because of the variable name conflict
            this.someNumber = someNumber;
            this.someOtherNumber = someOtherNumber;
        }
    
        public int someMethod(boolean first) { // Boolean ? boolean ?
            if (first) {
                return someNumber;
            } else {
                return this.someOtherNumber; // this.{name} ? just {name} or even this.get{name}() or get{name}() ? (supposing getters exists)
            }
        }
    }
    

I hope someone will provide me with a great explanation about which to use in order for me to write better code.

halfer
  • 19,824
  • 17
  • 99
  • 186
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
  • The questions topic is pretty unclear. Shouldn't it be "how to pass variables in Java"? Also, I daresay this is too general and wide a question. You could find answers easily if you googled those things separately. – Dariusz Oct 02 '13 at 08:50
  • I googled and didn't find anything useful, thus the question. The topic maybe is unclear but it's because it's also unclear to me how to handle these (again, thus the question). – Cyril N. Oct 02 '13 at 08:57

7 Answers7

4

Do you always pass Object or can you pass primitive data type ?

You can't pass an Object, only a reference to an Object. You can pass primitive data.

Do you call variables using this.name, name or getName() inside your class instance ?

I don't make it more complicated than I need to, unless it's conflicts with a local variable or my getName() does something special, but that is a matter of style.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • And what is the reason your method signature is `...(Integer someVar)` instead of `...(int someVar)` ? A particular one or no reason at all ? – Cyril N. Oct 02 '13 at 08:58
  • @CyrilN. Some use `Integer` instead of `int` because a) it can be `null`, b) using primitives is a complication the developer wasn't worried about. I tend to avoid using wrappers where ever possible and even use collections of primitives e.g. trove, to make it clear that `null` is not an option, and sometimes because it is faster. – Peter Lawrey Oct 02 '13 at 09:01
  • Ok so again, there is no "You must do it that way" but more a "everyone write code differently", right ? – Cyril N. Oct 02 '13 at 09:02
  • @CyrilN. Every one writes differently, but I firmly believe you should design and code in the manner you believe is the simplest and clearest. Spend more effort trying to take stuff out than adding stuff in and you will get more maintainable and often faster code. – Peter Lawrey Oct 02 '13 at 09:04
2

Do you always pass Object or can you pass primitive data type ?

You can pass primitives or references to objects depending on your need.

Do you call variables using this.name, name or getName() inside your class instance ?

this is used to refer to the current object. If there are conflicting variable names and you want to distinguish between the object variable and local variable then use this.

Also you seems to be confused about primitives and Wrapper classes. Wrapper classes provides utilities methods and are of use especially working with collections.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

Do you always pass Object or can you pass primitive data type ?

public int someMethod(boolean first) { // Boolean ? boolean ?

}

In the following example, you can pass boolean and Boolean with the same success. In Java this is called Autoboxing.

N.B. Be careful, because when passing an object it may be null!

Do you call variables using this.name, name or getName() inside your class instance ?

Depends. If name is an class member variable, you can access it with name if there isn't any other variable in the current scope that has the same name. In this case you should use this.name to point exactly to the class member variable. getName() may be used, as well. It's just a matter of style.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

If you need to work with the primitive data types then you should use them, e.g., int, double, char, float, etc. The only exception is String which in Java is a special class that represents a char array and also holds instance methods.

The case with Integer vs int, is when you need to use Integer methods (http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html). But if you only need a data type to hold your value then choose int.

user1021726
  • 638
  • 10
  • 23
  • A String is an exception to what? It is just a class, though an immutable one. The only way String is specially treated is in the `case` in Java 7. – Dariusz Oct 02 '13 at 08:52
1

I keep it simple. I'm using name, but if I have a local variable with the same name I must use this.name (my prefered solution) over getName(). getName() must be used if it do some logic like validation.

Cyril N.
  • 38,875
  • 36
  • 142
  • 243
JulianG
  • 1,551
  • 1
  • 19
  • 29
1

It is mostly a matter of personal style and principle.

  1. private int someOtherNumber; I almost always use int because it seems more natural to me --perhaps influenced by the C days. And, from performance and memory usage point of view using int is a better choice. As a rule of thumb, I don't use objects for primitives unless I have a good reason to.
  2. return this.getSomeOtherNumber(); I prefer using getters/setters; since sometimes -not always- the getter method is not just a simple return statement, rather it encapsulates some logic. As a result, I don't directly access class attributes (like this.someAttr or someClass.somePublicAttr) unless it's a final attribute. Believe me, it's much safer.

Continuing 2: It may seem a bit strange but I, having a strong Lisp background, try to avoid using even getter/setter methods (class state) as much as possible and instead explicity pass the required parameters and use the methods' return values. Consider the following example:

public class C {
  private int a;
  private int b;

  public int getA() { return a; }
  public void setA(int a) { this.a = a; }
  public int getB() { return a; }
  public void setB(int b) { this.b = b; }

  // Usual style
  public void someMethod1(int x) {
    mainLogic1(x);
  }

  private void mainLogic1(int x) {
    b = a + x;
  }

  // My preferred style
  public void someMethod2(int x) {
    setB(mainLogic2(x, getA()));
  }

  private int mainLogic2(int x, int a) {
    return x + a;
  }
}

As you can see, someMethod1 and mainLogic1 both have side effects which are hard to detect when looking at the code. On the other hand mainLogic2 doesn't have a side effect at all and someMethod2 side effect is easier to spot by just looking. This may seem like overkill, but it has made my Java code more readable, more testable and easier to refactor as it consists of large number of small methods with no side effects.

BahmanM
  • 1,420
  • 10
  • 18
  • Thanks for your reply, it's very interesting. And The example with your preferred style is helping me make my decision :) – Cyril N. Oct 02 '13 at 10:15
1
    Do you always pass Object or can you pass primitive data type ?

It depends on your application and your needs. If you pass a reference to an object, you are able to use the methods of the related type which may be more secure and portable. Let say you are using the class Double. Double has many peer-reviewed and tested methods which may be helpful to you.If you prefer to use primitive type, double, you need to be careful in your manipulations like comparing, validating etc. For performance issue, you may check a previous discussion below: Why do people still use primitive types in Java?

    Do you call variables using this.name, name or getName() inside your class instance ?

I prefer using this when I refer a class member because i think it will be helpful for others reading my code to understand that the variable is a class member.

Finally, whatever style you prefer, I think you should stick to it in your applications.

Do you call variables using this.name, name or getName() inside your class instance ?

Community
  • 1
  • 1
tmr
  • 125
  • 2
  • 9