0

I am developing one SDK in Android and all good. But I got stuck in a point, How can I hide the implementation from the user. For example, if I am exposing a method calcualteSum() to user shouldn't be able to see the operations happening in the background. Please refer the below code. This is currently I'm hiding the operation from the user. Is there any better way to do this?

public class MathCalulate {
    
    //user will be able to access this method.
    public int calculateSum(int a, int b){
        return MyMath.sum(a,b);
    }

} 

Implementation class which will be hidden from the customer:

private class MyMath {

    //user will not be able to access this method.
    private int sum(int a, int b){
        return  a+b;
    }

}

2 Answers 2

2

You can provide an interface for your function and provide a package private default implementation for that.

example:

public interface MathCalculate {
   int calculateSum(int a, int b);
}

and its implementation:

class MathCalcualteImpl implements MathCalculate {

 @Override
 public int calculateSum(int a, int b){
   return a+b;
 }
}

this way, the users who access your library, will/can import MathCalculate and just use the functions you have provided in the interface.

But be careful, the users can also override their functionality, and provide their own implementation for your interface.

Sign up to request clarification or add additional context in comments.

Comments

0

On top of above @Kapil answer you need to obfuscate your classes using dexguard / proguard /R8. This will make it hard for developers to understand your code.

2 Comments

Of course, we are using pro-guard. But you know right if we are applying proguard to the user exposed methods/class they can't access it properly.
Yes.. For sure. So do not obfuscate these interface classes. As below: -keep class <Fully Qualified ClassName>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.