Search code examples
javaobjectmethodsprivate

Passing objects from one private method to another


I have been programming for a little while now, and I have a question on the use of public methods. I am working on a vending machine program, and I have a private method setUpMachine() to initialize the game and set up the objects. I have another private method startMachine() that starts the game and prompts the user for input. It then passes the input to yet another private method checkInput() that checks to see if the input is valid... but this is where I run into not so much of a "problem", but a weird feeling of me not doing something correctly. I need access to the objects that are in my first method, setUpMachine() for my third method checkInput(). The problem is that I have many objects (candy, chips, soda, cookie), and passing them all to check perimeters just doesn't seem right. In other words, doing this:

checkInput(FoodType candy, FoodType chips, FoodType soda, FoodType cookie)

doesn't seem right. Does this mean, that if I use private methods, I have to pass objects every time I want to use them? I read that making public methods is bad practice.

An explanation on this would be nice, not so much an explanation telling me my coding is inefficient, but more an explanation describing when and how to use private methods, or if there is another way to go about doing this.


Solution

  • If you don't want to pass the objects around, you can configure them as instance variables:

    public class VendingMachine {
        private FoodType candy;
        private FoodType chips;
        private FoodType sodas;
        private FoodType cookies;
    
        private static String errorMessage = "A really bad error occurred.";
    
        public VendingMachine(){
            this.setupMachine();
        }
    
        private void setUpMachine(){
            this.candy = new FoodType();
            this.chips = new FoodType();
            this.sodas = new FoodType();
            this.cookies = new FoodType();
        }
    
        private boolean checkInput(){
            if (this.candy==null || this.chips==null || this.sodas==null || this.cookies==null)
                return false;
            else
                return true;
        }
    
        public void doSomething() throws Exception() {
            if (!this.checkInput()) throw new Exception(VendingMachine.errorMessage);
            // do things
        }
    }
    

    This class can then be called as

    VendingMachine vendingMachine = new VendingMachine();
    try {
        //vendingMachine.checkInput() is not available because it is private
        vendingMachine.doSomething(); // public method is available
    } catch (Exception e){
        // validation failed and threw an Exception
    }