Encapsulating Behavior in Objects.

Encapsulating Behavior in Objects.

Einar Landre's advice to "encapsulate behavior, not just state" is a crucial principle in systems theory and software engineering. In software development, containment or encapsulation is well understood and supported by language constructs such as classes, functions, and modules. However, developers often struggle to properly encapsulate classes, leading to large, unwieldy methods or classes with only set and get methods for primitive attributes.

Objects encapsulate both state and behavior, with the behavior defined by the actual state. For example, a door object has four states (closed, open, closing, opening) and provides two operations (open and close), with the open and close operations behaving differently depending on the state. This inherent property of objects simplifies the design process by allocating and delegating responsibility to different objects, including interobject interaction protocols.

Encapsulating behavior and state properly is illustrated through an example involving three classes: Customer, Order, and Item. In this example, a Customer object is the natural placeholder for credit limit and validation rules, and an Order object knows about its associated Customer. The addItem operation in Order delegates the actual credit check to the Customer object by calling customer.validateCredit(item.price()). If the postcondition fails, an exception can be thrown and the purchase aborted.

Inexperienced object-oriented developers may choose to wrap all business rules into an object, such as OrderManager or OrderService, treating Order, Customer, and Item as little more than record types. However, this approach breaks encapsulation and leads to large, procedural methods that are difficult to maintain. Therefore, it is crucial not to break encapsulation and to use the power of programming language constructs to maintain it.

#encapsulation #objectorienteddesign #softwareengineering #programminglanguages #behaviorencapsulation #stateencapsulation #systemstheory #ooparadigm #developerbestpractices #maintainablecode #responsibilitydelegation #interobjectinteraction #codequality

要查看或添加评论,请登录

Harshit Walia的更多文章

社区洞察

其他会员也浏览了