Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using a class as a struct bad practice in Java?

We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . Why is that ?

like image 768
Geo Avatar asked Nov 23 '08 18:11

Geo


2 Answers

There's an argument that classes should either be "data structures" (i.e., focus on storing data with no functionality) or "functionality oriented" (i.e., focus on performing certain actions while storing minimal state). If you follow that argument (which makes sense but isn't always easy to do) then there is nothing necessarily wrong with that.

In fact, one would argue that beans and entity beans are essentially that - data containers with getters and setters.

I have seen certain sources (e.g., the book "clean code") arguing that one should avoid methods with multiple parameters and instead pass them as a single object with getters and setters. This is also closer to the "smalltalk model" of named parameters where order does not matter.

So I think that when used appropriately, your design makes sense.

like image 116
Uri Avatar answered Oct 17 '22 19:10

Uri


Note that there are two separate issues here.

  1. Is a "struct-like" class sensible?

  2. Is creating a class to return multiple values from a method sensible?

Struct-like classes

An object class should -- for the most part -- represent a class of real-world objects. A passive, struct-like java bean (all getters and setters) may represent a real-world thing.

However, most real-world things have rules, constraints, behaviors, and basic verbs in which they engage. A struct-like class is rarely a good match for a real-world thing, it's usually some technical thing. That makes it less than ideal OO design.

Multiple returns from a method

While Python has this, Java doesn't. Multiple return values isn't an OO question, per se. It's a question of working through the language limitations.

Multiple return values may mean that an object has changed state. Perhaps one method changes the state and some group of getters return the values stemming from this state change.

like image 25
S.Lott Avatar answered Oct 17 '22 18:10

S.Lott