开发者

In which scenarios do you use encapsulation?

开发者 https://www.devze.com 2023-01-16 13:48 出处:网络
I would like to know in what scenarios you use encapsulation. The purpose of this question is collaborative. So feel free to share your own experience when the subject is encapsulation.

I would like to know in what scenarios you use encapsulation. The purpose of this question is collaborative. So feel free to share your own experience when the subject is encapsulation.

Some scenarios:

Calculated 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-validating domain objects

public class Person {

    private String name;

    public void setName(String name) {
        if(StringUtils.开发者_Go百科isBlank(name)) {
            throw new NotEmptyException("name", name);
        }

        this.name = name;
    }

}

Makes use of other kind of classes 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);
     }

}


Simply, I prefer to use strong encapsulation in all non-private APIs that I design/implement.

The only case where habitually don't use strong encapsulation is with private nested classes that are (and need to be) little more than ersatz struct declarations. My reasoning is that the private class is sufficiently encapsulated by being nested and private.

I am also prepared to relax encapsulation (a bit) if there are compelling performance reasons for doing this. This relaxation usually consists of leaking internal arrays / collections when the cost of copying them is prohibitive. And it always makes me feel uncomfortable doing this ...


I encapsulate when there is a scenario in which the user can screw it up. e.g., if I was writing a class that displayed text, I would not encapsulate the fact that I hold a string, because any string is valid for display.

Encapsulation exists for validation and interface change. If you have a parameter that needs no validation (and the interface is well-defined), there's no point in encapsulating it, especially if you use a language which doesn't come with any in-built tools for it, like Java (tools being, for example, C# properties).

Encapsulation is a tool like any other and should not be thrown all over everywhere just because you can.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号