Sonntag, 8. August 2010

Simpler Java #8: Control the scope of statefuls

Prelude: This is a follow up both on the command/query, the functional methods and the immutable articles. It takes all of them to show a pattern to make it easy to control the scope of your states.

This is where I wanted to go, exactly: I summed up all the information below for one single task: Postphoning a simple, yet very rigid design principle for all kind of OO:

All stateful object operations (the states) must all happen in the same scope. It is not allowed for any object to execute commands on objects they do not own. Likewise, no object may reveal its inner stateful objects to the outer world. If they want to, they have to provide copies. No singleton or global object is allowed to exist which maintains ANY kind of state.

Lets start with a simple example what this means: I got an kind of stateful object which i mostly use for random-access reading. Say its a "DbClient". The client has countless "read" operations, and some commands to actually write values (which will change its states) and the close operation. In that particular usecase, it must be ensured that all write operations run over the scope of the holder of the db-object, while all "read" operations are freely allowed in any context.

Achieving this aim is after all simpler than it seems: After all, all you need to do is separate between read and write access. Recommended would be a design in which all queries are contained in its own interface, and likewise, the write operations are contained in its own interface as well (the commands), which extends the read interface. Then, define a class which inherits from the write interface and ensure that in all calls, the read interface is given, and the write interface is only used internally in the class.

Actually, its quite obvious that this approach will have countless flaws and will never be a well-defined design priniciple.. After all, there will always be situations, where this design does not work. However, I guess that:
1. These situations are rare and
2. Possibly these are exactly those situations which WILL prove to be problematic at run time, after all.

I guess that most of the so called "needed" global stateful objects with write access are in fact just an example of bad design. To be more precisely: I still believe that its possible by rigid use of immutables, to ALWAYS lock down mutable objects and resources into a more limited scope than the public one.

Trust me: All I want to achieve is the problematic scenario of these "god" objects, which are just maintainance nightmares, and at the lowest level, EVERY mutable object has the potential to screw the advantages of encapsulation if it contains even a single-lined command.

Keine Kommentare:

Kommentar veröffentlichen