Friday, January 6, 2017

Favor object composition over class inheritance in Java with Project Lombok Delegate annotation


Subject: Object composition in Java via Lombok @Delegate annotation

Problem Statement : One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods. In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only need to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class.

Solution: This drawback can be avoided by using traits, mixins, or protocol extensions. Some languages, such as Perl 6, provide a handles keyword to facilitate method forwarding. In Java, Project Lombok lets you implement delegation using a single @Delegate annotation on the field instead of copying and maintaining names and types of all methods from the delegated field


Code : For the ones who says - "No bullshit , just the code..." :))

import lombok.Data;
@Data
public class BasicStudent {
    private String name;

    public void writeYourNameOnTheBlackBoard (){
        System.out.println ("There is no He/she/it in turkish because we are not sexists :) ");
    }
}


import lombok.experimental.Delegate;
public class EnhancedStudent {

    @Delegate
    BasicStudent beaFeaturesCameHereWithAnnotation;

}

public class StudentProcessor {
    public static void main (String[] args) {
        EnhancedStudent enhancedStudent = new EnhancedStudent ();
        enhancedStudent.writeYourNameOnTheBlackBoard ();
    }
}


 -- for the memory of Christoph Portman

1 comment:

  1. Thanks for sharing, nice post! Post really provice useful information!

    An Thái Sơn chia sẻ trẻ sơ sinh nằm nôi điện có tốt không hay võng điện có tốt không và giải đáp cục điện đưa võng giá bao nhiêu cũng như mua máy đưa võng ở tphcm địa chỉ ở đâu uy tín.

    ReplyDelete