I need a method to accept two types and do the same thing with them.
I know I could do:
public void myMethod(TextView tv, ReadableMap styles) {
if (styles.hasKey("fontFamily")) {
String font = "fonts/" + styles.getString("fontFamily") + ".ttf";
Typeface tf = Typeface.createFromAsset(context.getAssets(), font);
tv.setTypeface(tf);
}
if (styles.hasKey("fontSize")) {
tv.setTextSize(styles.getInt("fontSize"));
}
if (styles.hasKey("letterSpacing")) {
tv.setLetterSpacing(PixelUtil.toPixelFromDIP(styles.getInt("letterSpacing")));
}
}
public void myMethod(TextPaint tv, ReadableMap styles) {
// copy paste the **exact** same code
}
Both TextView
and TextPaint
have methods setTypeface(Typeface)
, setTextSize(float)
and setLetterSpacing(float)
, but the two classes do not have a shared supertype other than Object
. (Note that TextPaint
inherits the methods from Paint
.) These classes both separately declare these methods, with the same names and signatures.
So since I cannot cast one to another, I would like to know how to reduce this amount of duplicated code?