Is “Wrap child class operation into a function, then return the object, in order to declare most abstract type” necessary or over-engineering?

  softwareengineering

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

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.

LEAVE A COMMENT