Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Why use return statement (newbie)

    Hi folks!
    I am complete newbie to OOP, and generally quite new to any programming so forgive me my probably silly question. Why use return statement like this:
    Code:
    class Num
        public int num() {
            i = 10;
            return i;
        }
    }
    
    public class Main {
        public static void main (String [] args) {
            Num n = new Num();
            n.num();
            System.out.println(n.i);
        }
    }
    when we can just
    Code:
    class Num {
        public void num() {
            i = 10;
       }
    }
    
    public class Main {
        public static void main (String [] args) {
            Num n = new Num();
            n.num();
            System.out.println(n.i);
        }
    }
    In all tutorials for beginners I see the former solution with return statement or the latter with even additional method which job is just return value like this:
    Code:
    ...
    public int getN() {
        return i;
    }
    ...
    Why?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    I'm not sure why you think this will work:
    PHP Code:
    class Num {
        public 
    void num() {
            
    10;
       }
    }

    public class 
    Main {
        public static 
    void main (String [] args) {
            
    Num n = new Num();
            
    n.num();
            
    System.out.println(n.i);
        }

    Even if that main were in the class Num, it won't have access to 'i' since it's not declared as a member property (or even a local one so that code for Num would just fail to compile).

    Public properties should be avoided as you cannot run any verification or validation if it is left public. It should be private or protected, and accesor and mutator functions written for them. If the main were in a class with a private property, it can still access that property, but it cannot access it if its not a part of the same class.

  • #3
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    I'm not sure why you think this will work:
    PHP Code:
    class Num {
        public 
    void num() {
            
    10;
       }
    }

    public class 
    Main {
        public static 
    void main (String [] args) {
            
    Num n = new Num();
            
    n.num();
            
    System.out.println(n.i);
        }

    Even if that main were in the class Num, it won't have access to 'i' since it's not declared as a member property (or even a local one so that code for Num would just fail to compile).

    Public properties should be avoided as you cannot run any verification or validation if it is left public. It should be private or protected, and accesor and mutator functions written for them. If the main were in a class with a private property, it can still access that property, but it cannot access it if its not a part of the same class.
    My mistake - forgot about declaration of "i". Now it works:
    Code:
    class Num {
        int i;
        public void num() {
            i = 10;
        }
    }
    
    public class Main {
        public static void main (String [] args) {
            Num n = new Num();
            n.num();
            System.out.println(n.i);
        }
    }
    You are saying that the only reason of using a return statement is validation? So changing num() method to private/protected and writing still public method which invokes it and returns its value will enable validation?

  • #4
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,755
    Thanks
    41
    Thanked 191 Times in 190 Posts
    for your properties (I think called 'fields' in Java) you generally just do a return of the variable...
    Code:
    public int getNum()
    {
      return i;
    }
    you usually have/use variables in methods because you are not always sure what the variable will be
    Code:
    private int computeNewNum(int varibleNumber)
    {
      i = (variableNumber * i)
      return i;
    }
    // input 2
    // output 20
    // input 5
    // output 100
    if field "i" is 10 and you pass 2, it will become 20; then pass a 5- 100 and so on. That is the reason you use variables. each return would be different depending what you passed it- also i is being set. You could also use i as a static variable and do something like
    Code:
    private int computeNewNum(int variableNumber)
    {
      return (i * variableNumber);
    }
    // input 2
    // output 20
    // input 5
    // output 50
    see? the second one doesn't assign i.

    making a field private means that only that object can access it and change it via method.

    Code:
    public class Demo
    {
      private int i = 10;
    
      public Demo(){...}
      
      public void seti(int variableNumber)
      {
        i = variableNumber;
      }
    
      public int geti()
      {
        return i;
      }
    }
    you can't access i in any other class. You can call the Demo.seti() and 'change' i, but you are not accessing it directly. You can throw in validation @ this point.
    Code:
    public void seti(int variableNumber)
    {
      if(variableNumber >= 0 && variableNumber <= 100)
        i = variableNumber;
      else
        throw new exception();
    }
    note* syntax's might be off-
    Last edited by alykins; 07-31-2012 at 06:14 PM.

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #5
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by alykins View Post
    for your properties (I think called 'fields' in Java) you generally just do a return of the variable...
    Code:
    public int getNum()
    {
      return i;
    }
    you usually have/use variables in methods because you are not always sure what the variable will be
    Code:
    private int computeNewNum(int varibleNumber)
    {
      i = (variableNumber * i)
      return i;
    }
    // input 2
    // output 20
    // input 5
    // output 100
    if field "i" is 10 and you pass 2, it will become 20; then pass a 5- 100 and so on. That is the reason you use variables. each return would be different depending what you passed it- also i is being set. You could also use i as a static variable and do something like
    Code:
    private int computeNewNum(int variableNumber)
    {
      return (i * variableNumber);
    }
    // input 2
    // output 20
    // input 5
    // output 50
    see? the second one doesn't assign i.
    That is ok - all above is true and I know what variables are and how they work. My question is - what is return statement for (apart from quiting method). Let's rewrite my example to make this method protected/private and do not initialize i.
    Code:
    public class Main {
        int i;
    
        protected void num(int i, int a) {
            this.i = i * a;
        }
    
        public static void main (String [] args) {
            Main n = new Main();
            n.num(10,5);
            System.out.println(n.i);
        }
    }
    It works and shows that whatever we do to "i" value it is not necessary to return it.

    making a field private means that only that object can access it and change it via method.

    Code:
    public class Demo
    {
      private int i = 10;
    
      public Demo(){...}
      
      public void seti(int variableNumber)
      {
        i = variableNumber;
      }
    
      public int geti()
      {
        return i;
      }
    }
    you can't access i in any other class. You can call the Demo.seti() and 'change' i, but you are not accessing it directly. You can throw in validation @ this point.
    Code:
    public void seti(int variableNumber)
    {
      if(variableNumber >= 0 && variableNumber <= 100)
        i = variableNumber;
      else
        throw new exception();
    }
    note* syntax's might be off-
    So once again - the only reason for writing the whole method (which job is just to return value) is to make fields and method be private/protected in other classes than the class in which we instantiate object?

  • #6
    New Coder
    Join Date
    Dec 2011
    Location
    abuja
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts
    If I understand your question 'why use return in some methods?'.
    You only use 'return' when your method is declared with any of java primitive types.
    Remember the format for declaring method:
    accessModifier type methodName(parameters)
    {
    statements;
    }

    'void' is a type that doesnt return anything,so it doesnt use return.
    E.g:
    Consider me(int) sending you(statements) to the market, when you return, you must give me a feedback(return statement).

  • #7
    New Coder
    Join Date
    Dec 2011
    Location
    abuja
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts
    If I understand your question 'why use return in some methods?'.
    You only use 'return' when your method is declared with any of java primitive types.
    Remember the format for declaring method:
    accessModifier type methodName(parameters)
    {
    statements;
    }

    'void' is a type that doesnt return anything,so it doesnt use return.
    E.g:
    Consider me(int) sending you(statements) to the market, when you return, you must give me a feedback(return statement).

  • #8
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by greeninho View Post
    If I understand your question 'why use return in some methods?'.
    You only use 'return' when your method is declared with any of java primitive types.
    Remember the format for declaring method:
    accessModifier type methodName(parameters)
    {
    statements;
    }

    'void' is a type that doesnt return anything,so it doesnt use return.
    E.g:
    Consider me(int) sending you(statements) to the market, when you return, you must give me a feedback(return statement).
    My question was: what's a "return val" statement for? Did you have a look at my last code in previous post? There is no return statement, but I still get a proper feedback from method - I obtained calculated value of "i" variable without returning it. I just invoked it.

  • #9
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    The reason why is that you do not want public properties at all.
    PHP Code:
    class Employee
    {
        public 
    double dHoursWorked;

        public function 
    getHoursWorked()
        {
            return 
    this.dHoursWorked;
        }

        public function 
    setHoursWorked(double dWorked)
        {
            if (
    dWorked 0)
            {
                throw new 
    IllegalArgumentException("Impossible to work negative hours!");
            }
            
    this.dHoursWorked dWorked;
        }

        public static 
    void main(String... argv)
        {
            
    Employee e = new Employee();
            try
            {
                
    e.setHoursWorked(-5);
            }
            catch (
    Exception ex)
            {
                
    ex.printStackTrace();
            }

            
    // but:
            
    e.dHoursWorked = -5;
        }

    Not the most feasible example but still. Assuming that an Employee cannot work negative hours, the above class allows you to specify the number of hours set as a negative number. That of course is not good. dHoursWorked should be a private or protected scope variable, so that it can never be set to a negative value as specified by the set method. Since it can no longer be assigned to outside of the scope of the class directly, any setting will be guaranteed to be > 0. Note that a main within the scope of a class is considered to be within the scope of that class, so dHoursWorked is accessible even if it were private. This is more to prevent external control of the object beyond the scope of what it should have access to.

    This is why you should be returning even properties for a class instead of making them public. The only thing that should be specified as public should also be affixed with the final property on it.

    In other words, dynamic variables should never be accessible using aninstance.property. They should always be accessible using aninstance.setProperty(avalue); and aninstance.getProperty(avalue);. Languages like C# use set overloads to chain the get and set directly to the dereferencing of the property itself, so by calling aninstance.property = avalue chains the call to the set associated with 'property'. Java does not have this ability. Its been awhile since I've done C#, so excuse me if I biff it up a bit.

    In C# you do as so:
    PHP Code:
    public class Num
    {
        private 
    int _i;
        public 
    int i
        
    {
            
    get
            
    {
                return 
    this._i;
            }

            
    set
            
    {
                
    this._i value;
            }
        }

        public static 
    void Main(string[] argv)
        {
            
    Num n = new Num();
            
    n.5;
            
    Console.out.writeln(n.i);
        }

    whilst in java:
    PHP Code:
    public class Num
    {
        private 
    int i;
        public 
    int getI()
        {
            return 
    this.i;
        }

        public 
    void setI(int i)
        {
            
    this.i;
        }

        public static 
    void main(String[] argv)
        {
            
    Num n = new Num();
            
    n.setI(5);
            
    System.out.println(n.getI());
        }

    C# you can write the validation in the set of the field handler, while in Java you write it in the setter.

  • #10
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,755
    Thanks
    41
    Thanked 191 Times in 190 Posts
    Between Fou-Lu's and my own examples/explanations, as well as greeninho's clarification on the return types (ie void, int, double, etc) I don't think there is anything more we can do to make it "more" clear... I think what you should do (because at this point I am guessing you are understanding what we are saying, but the "ah-ha!" moment hasn't hit yet) is just take it on faith that good coding practice is done this way. And albeit a piss-poor explanation- for now all you really need (since you are a "newbie") is...
    do it this way because people in the industry who have been doing it, and developed it said so.
    Eventually you will get to the point, and level of understanding, that this will all make sense. You will see where/when to make thing public or private; you will notice the benefits. It is all too much to try and understand "everything" at once.

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #11
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Ok guys.
    Thanks for explanations. So as far as I understand: along with good programming practice I should put private/protected for variables as well as for methods which process these variables, and write separate public method which returns result of these methods (their process - calculations, changing, etc.)? In other words - methods in class should be private/protected so no one can interfere from outside. For these methods should by public methods which returns their result?

  • #12
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Quote Originally Posted by tomjas View Post
    Ok guys.
    Thanks for explanations. So as far as I understand: along with good programming practice I should put private/protected for variables as well as for methods which process these variables, and write separate public method which returns result of these methods (their process - calculations, changing, etc.)? In other words - methods in class should be private/protected so no one can interfere from outside. For these methods should by public methods which returns their result?
    No that's not right. The setters and getters should be public if the property can be accessed from outside of this class. You don't need to specify multiple write methods for a single property, just the one is sufficient. If you make everything private or protected, than this class becomes useless outside of itself since you cannot call anything on the object outside of it.

  • #13
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    No that's not right. The setters and getters should be public if the property can be accessed from outside of this class. You don't need to specify multiple write methods for a single property, just the one is sufficient. If you make everything private or protected, than this class becomes useless outside of itself since you cannot call anything on the object outside of it.
    Ok - there have been some misunderstanding. In my first post I tried to give as simple snippet of code as possible and the whole discussion went wrong way. My mistake was giving something like that:
    Code:
    class Num {
        public int num() {
            i = 10;
            return i;
        }
    }
    and we started to discuss that variable "i" should be private/protected to avoid changing it so it must be returned and so on. I am learning from http://docs.oracle.com/javase/tutorial/java/ and I found such example:
    Code:
    public class Bicycle{
            
        private int cadence;
        private int gear;
        private int speed;
        private int id;
        private static int numberOfBicycles = 0;
            
        public MouintainBicycle(int startCadence, int startSpeed, int startGear){
            gear = startGear;
            cadence = startCadence;
            speed = startSpeed;
    
            // increment number of Bicycles
            // and assign ID number
            id = ++numberOfBicycles;
        }
    
        // new method to return the ID instance variable
        public int getID() {
            return id;
        }
            ...
    }
    And again - method MountainBicycle must be public so as to we could invoke it and pass parameters. Right? The last statement of this method is "id = ++numberOfBicycles;" After invoking it from my main method (and of course writing for this method some stupid code that calculates somehow id) I can still obtain the id like this:
    Code:
    ...
    Bicycle bke = new Bicycle();
    bike.MountainBicycle(10,10,10);
    int numberOfBicycles = bike.id;
    So again - what for is the getID() method with its "return id" statement? There is no need to return it if we have access from outside to calculated id? That's what I was asking from the beginning. Of course I assume that there are some other reasons for that than just "good programming practices".

  • #14
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    You can only invoke it this way since you are writing the main method within the class itself. Create a new class with a main method and invoke the same and you will get an compilation error. I mentioned that main methods within a class are considered within a valid scope, and as such can access private properties.

    This code of course wouldn't compile. MountainBicycle is not provided with a return type, nor is it a constructor for the class Bicycle. Constructors only need to be provided with the public scope if you wish to allow construction using new MyClassType(). If you do not want to allow instance creation with the new keyword, then a private/protected scope is added to prevent that.

    Remember the basic scopes are: private - only this class can access, protected - only this class and its children can access, public - anything can access. The final modifier is one without an explicit access modifier, and it is best thought of as package. This page describes these modifiers: http://docs.oracle.com/javase/tutori...sscontrol.html
    Note that the last line also indicates that you should not use public, even though most examples on the site do.

  • Users who have thanked Fou-Lu for this post:

    tomjas (08-16-2012)

  • #15
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks again for explanation. I have no idea where I got this notion from - that private fields become public in public methods, so they would be accessible. That's the whole misunderstanding. Thanks again. Going back to learning.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •