In what scenarios do you use encapsulation?

I would like to know in which scenarios you use encapsulation. The purpose of this issue is a joint one . Therefore, do not hesitate to share your experience when the object is encapsulated.

Some scenarios:

Computed Property

public class Order {

    private List<ListItem> listItems = new ArrayList<ListItem>();

    public double getTotal() {
        double total = 0;
        for(ListItem listItem: listItems)
            total += listItem.getQuantity() * listItem.getPropduct().getPrice();

        return total;
    }

}

Self-tuning domain objects

public class Person {

    private String name;

    public void setName(String name) {
        if(StringUtils.isBlank(name)) {
            throw new NotEmptyException("name", name);
        }

        this.name = name;
    }

}

Uses other class types for some special behavior.

public class Person {

    private MutableInt id = new MutableInt();

    /**
      * Integer itself is immutable
      */
    public Integer getId() {
        retur id.intValue();
    }

}

Conversion

public class Person {

     public String enabled;

     public boolean isEnabled() {
         return "Y".equals(enabled);
     }

}
+5
source share
2 answers

I just prefer to use strong encapsulation in all non-private APIs that I develop / implement.

, , private , ( ) , ersatz struct. , , .

(), . /, . , ...

+4

, , . , , , , , .

. , ( ), , , , Java ( , #).

- , , , .

0

All Articles