Jump to content

State and Behavior


G+_Lee Crocker
 Share

Recommended Posts

State and Behavior

 

Another cool episode with Smitty, but I think Lou and Padre's opening bit about structures and objects was more confusing than useful. In particular, they make it sound like a matter of choice. Apparently it is if you're using C#--I'll take Lou's word for that. For the other 95% of programmers, the choice is easy: in C++, use structs to interface with C code, otherwise use classes. In every other programming language in the world, use the one your language has.

 

Lou also emphasized the value of information hiding, which is indeed a benefit of OO design, but not what I'd call it's defining characteristic. Padre got this one right: what makes objects different from structures is behavior. That is, object have methods as well as data, and because they do, they can have data that is private to those methods.

 

The more general question of why to use either one was never really answered clearly, but the answer is quite simple: computer programs model parts of the world, and structures are ways to encapsulate the representation of complex things. Things in the world have state, which is to say more-or-less static (but perhaps changeable) properties: a car has a make, model, color, location, direction, occupants, and so on. You might be able to come up with many such properties. Which ones you choose to track is a matter of what you need your program to do, but collecting them into a structure of some type makes it clear that they belong to a single thing, and simplifies dealing with those things. Things also have behavior, which is what they do, or what can be done to them, and how they interact with other things (drive, paint, sell. etc.)

 

Structures in programming languages collect into one place the state of something. Objects collect both state and behavior. Some languages (Java, Go, ...) have collections of behavior only, called "interfaces". Classes are a further way to organize and, well, classify, different kinds of objects. Some languages (JavaScript, Lua, ...) have objects, but not classes. To further complicate things, languages use all kinds of different terms for these things: "records" (Pascal...), "tuples" (Erlang...), etc. Go calls its objects "structures". :-)

 

But it's all about state and behavior: what are the "things" in your program, how do you describe and differentiate them, and what do they do?

Link to comment
Share on other sites

 Share

×
×
  • Create New...