0

According to Why define a Java object using interface (e.g. Map) rather than implementation (HashMap), I should declare the most abstract type as possible. However, in some cases I remember, especially for UI related codes, I can't declare the most abstract type because those UI object usually require to run some child class specific functions, consider Label is a subclass of View in some UI framework, eg:

//Label specific methods
Label* label=Label::create("myText");
label->setTextColor(255,0,0);
label->setTextSize(32);
//View methods
label->setViewPosition(400,300);
this->view->addChildView(label);

My question is, should I modify to:

View* label=[](){
    //Label specific methods
    Label* label=Label::create("myText");
    label->setTextColor(255,0,0);
    label->setTextSize(32);
    return label;
}();
//View methods
label->setViewPosition(400,300);
this->view->addChildView(label);

which wrap all child class specific function first, so that the declaration can be the most abstract type? Is it necessary or over-engineering?

1
  • If you require certain functionality declared at an intermediate level, then the topmost level is not the most abstract type possible, so the principle still holds. Commented Aug 22, 2023 at 9:59

1 Answer 1

6

Declaring objects at the most abstract type possible means that you should declare the type as the most abstract type that provides all the features you need to access.

In your example with a UI label, that most abstract type is actually Label and the way you use it in the first is perfectly fine. The guidance does not state that you must jump through hoops to use the most abstract type that could be used in a particular call. It is still perfectly fine to call methods that come from a superclass while you have a reference/pointer to a subclass.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.