SklogW
SklogW

Reputation: 849

How to treat methods which are only called by other methods from the same class but shouldn't be called by an instance?

I have the following situation:

public void method1()
{ 
    if(condition)
    {
        method2();

    }else
    {
        method3();
    }
}

method1() would be way too big, that's why I have split it into different methods.

Since method2() and method3() are only called by method1() it wouldn't make much sense if they would be visible outside the class.

My question: What is the proper design choice to make that happen ?

thank you

EDIT:

I've tried private and protected but the methods keep showing up.

e.g.:

Class class = new Class();

class.somePrivateOrProtectedMethod(Parameters...);

This is still possible.

Upvotes: 2

Views: 206

Answers (3)

abl
abl

Reputation: 5958

If the problem is that:

  • your class is very large

(which means that)

  • you find it difficult to keep track of the relationships between methods

(and therefore)

  • you want to make it really clear in your code that method2() and method3() shouldn't be called from anywhere else that method1()

... then you could put those three methods inside an inner class whose only purpose is to run method1(). All methods will still be accessible from the outer class, but the structure of the code will give a hint as to the expected usage.

class MyClass {

    ...

    private class ProcessDoer {

        public void doProcess() {
            if(condition) {
                method2();
            } else {
                method3();
            }
        }

        private void method2() {
            ...
        }

        private void method3() {
            ...
        }
    }
}

However in a lot of situations that would be overkill.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280011

If your question is whether there exists a language construct in Java that restricts calling a method to a single other method, the answer is no.

You really shouldn't worry about that. You're the owner of the source code. As long as you encapsulate those methods correctly, with private as Philipp pointed out, then you're protected from the outside. You have no reason to protect yourself from the inside.

Upvotes: 2

Philipp Wendler
Philipp Wendler

Reputation: 11433

Just declare them as private instead of public:

private void method2() { ... }

This will have the effect that they are not visible to anything outside of the same file.

They will still be visible to code inside the same file, however, even if it is in a different class in the same file.

In Java, it is also always possible to call private methods on different instances (other than this) from within the same file. There is no way to restrict the visibility to the same instance (only to the same class/file).

Upvotes: 2

Related Questions