tag:blogger.com,1999:blog-31334114722293370082024-02-20T07:33:01.683-08:00Half-baked software ... and methodscan methods be "fuzzy"?Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.comBlogger8125tag:blogger.com,1999:blog-3133411472229337008.post-79699917990542946292048-02-18T08:50:00.000-08:002008-02-20T06:47:13.675-08:00The hunt for the dangling Iterator (part 1)<div style="text-align: justify;">Why start a blog on "fuzzy methods" with specialised technical considerations on java programming?
</div>
<div style="text-align: justify;">More on this later! (but if you are not familiar with java programming better skip those initial blog entries).
</div>
<div style="text-align: justify;">If you are already familiar with discussions on Iterators you can also skip this introduction:
</div>
<div style="text-align: justify;"><TT>Iterator</TT> is an interesting feature: it enables a "client code" to pilot a service requested from an implementing code. Usually when you request a service from another class you have something that looks like:</div>
<PRE class="displaycode">
Result res = implementor.doIt() ;
</PRE>
<div style="text-align: justify;">Control is transfered to implementor: once the implementor's code is finished control is transfered again to the caller's code.</div>
<div style="text-align: justify;">Using an <TT>Iterator</TT> is having a different cooperation between implementor and client code. once you write :</div>
<PRE class="displaycode">
Iterator iter = implementor.iterator() ;
</PRE>
<div style="text-align: justify;">The client code collaborates with the implementor code through subsequent calls to the <TT>hasNext()</TT>, <TT>next()</TT> calls.</div>
<div style="text-align: justify;">Now suppose you have a code that wants to retrieve a list of Objects from a <TT>Catalog</TT>. You can have different ways to specify the service:</DIV>
<PRE class="displaycode">
Thing[] get(request) ;
</PRE>
or
<PRE class="displaycode">
List<Thing> get(request) ;
</PRE>
or
<PRE class="displaycode">
Iterator<Thing> get(request) ;
</PRE>
<div style="text-align: justify;">The choice depends on realistic expectations about the number of <TT>Thing</TT>s you will get and how long it will take to retrieve those things.</div>
<div style="text-align: justify;">Using an <TT>Iterator</TT> will enable the client code to "pump" results as needed by the client code. So , for instance, if you inadvertently issue a request that could generate thousands of results you may rapidly give up and, if your request chain of code is well built, it is pumping only a limited numbers of objects in a cache (from a database for instance).</DIV>
<div style="text-align: justify;">Once you think you need an <TT>Iterator</TT> another question is raised: when does the interaction between "partner" objects end? For instance: you use a database and once you have finished pumping results you need to close the interaction with the database. </DIV>
<div style="text-align: justify;">This is annoying because the implementing object wants to be sure that the client code explicitly ends the interaction ... but how could it be sure? (programmers are so absent-minded you know...)</DIV>
<H3>END INTRODUCTION</H3>
<div style="text-align: justify;">Now the story of my different tries to solve this problem.</DIV>
<div style="text-align: justify;">Fist idea: declare a <TT>Closeable</TT> Iterator</div>
<PRE class="displaycode">
public interface CloseableIterator<X> extends Iterator<X> {
public void close() ; //
}
</PRE>
<div style="text-align: justify;">Note that <TT>close</TT> does not throw any exception (this relates to other points when considering Iterators).</DIV>
<div style="text-align: justify;">So the <TT>Catalog<X></TT> could declare :</DIV>
<PRE class="displaycode">
public CloseableIterator<X> get(Request<X> req) ;
</PRE>
<div style="text-align: justify;">Now the problem is not solved because the implementing code is not sure that the calling code will actually call <TT>close()</TT>.</DIV>
<div style="text-align: justify;">Step 2 : while investigating the closure proposals for java 1.7 I started designing those codes (see <A HREF=http://tronicek.blogspot.com/> for a lesson on closures</A>) :</DIV>
<PRE class="displaycode">
public interface Iterant<X > {
public <throws E > void forEach({X => boolean throws E} code) throws E;
}
</PRE>
<div style="text-align: justify;">and wrote an implementation that did:</DIV>
<PRE class="displaycode">
private CloseableIterator<X> iter ; //initialised by constructor
private boolean closed = false ; // should be volatile
public <throws E> void forEach({X => boolean throws E} f ) throws E {
try {
while(iter.hasNext() ) {
X val = iter.next() ;
// this will normally be treated differently with break/continue
// of the proposed "for" modifier
if (! f.invoke(val)) {
break ;
}
}
}finally {
this.theEnd() ;
}
}
protected synchronized void theEnd() {// see comment later on why "synchronized"
if(!closed) {
closed = true ;
iter.close() ;// normaly close should be idempotent
}
}
</PRE>
<div style="text-align: justify;">Well it appeared that the code was a bit specific to the notion of CloseableIterator and could be abstracted a triffle more :</DIV>
<PRE class="displaycode">
private Iterator<X> iter ;
private {=> void } exit ;
public IterantWithExit(Iterator<X> it, {=> void} exitCode) {
// test if it is not null !
this.iter = it ;
this.exit = exitCode ;
}
private AtomicBoolean exited = new AtomicBoolean(false) ;
private AtomicBoolean called = new AtomicBoolean(false) ;
public <throws E > void forEach({X => boolean throws E} f ) throws E {
if(called.getAndSet(true)) {
throw new IllegalStateException("forEach already called");
}
try {
while(iter.hasNext() ) {
X val = iter.next() ;
if (! f.invoke(val)) {
break ;
}
}
}finally {
this.theEnd() ;
}
}
private void theEnd() {
if( ! exited.getAndSet(true)) {
if(exit != null) exit.invoke() ;
}
}
</PRE>
<div style="text-align: justify;">So now we do not need anymore to create a <TT>CloseableIterator</TT> since any code to call after exit could be designed by the implementing code.</DIV>
<div style="text-align: justify;">Are we sure that the exit code will be always called? no! the code provided by the client could stop the loop (waiting -for a GUI event for instance-) and a "dangling iterator" could be left.</DIV>
<div style="text-align: justify;">ok we could add this to the code:</DIV>
<PRE class="displaycode">
protected void finalize() {
this.theEnd() ;
} // BTW explains why code dealing with concurrent access
</PRE>
<div style="text-align: justify;">That is: if there is a dangling object the close operation will be called when the object is reclaimed by the garbage collector.</DIV>
<div style="text-align: justify;">Is this enough? it depends of the importance of the close code. It depends if you tolerate that the close may not be called when the JVM terminates. If you want to be <B>DAMN SURE</B> it is called (except in case of cataclysmic termination) you may add this code :</DIV>
<PRE class="displaycode">
protected static final WeakHashMap<IterantWithExit, {=> void}> SURVIVORS =
new WeakHashMap<IterantWithExit, {=> void}>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
for(IterantWithExit iterEx : SURVIVORS.keySet()) {
iterEx.theEnd() ;
}
}
});
}
</PRE>
<div style="text-align: justify;">This is heavy artillery but if you need it ....</DIV>
<div style="text-align: justify;">I was not yet satisfied with this code so during the night this came to my mind:</DIV>
<PRE class="displaycode">
public interface Capsule<X> {
<R, throws E> R exec({X => R throws E} code)throws E ;
}
</PRE>
and implementation looking like :
<PRE class="displaycode">
public class ExitCapsule<X> implements Capsule<X> {
// SURVIVORS initialisation
private {=> void } exit ;
private X val ;
public <R, throws E > R exec({X => R throws E} f ) throws E {
try {
return f.invoke(val) ;
}finally {
this.theEnd() ;
}
}
public ExitCapsule(X vl, {=> void} exitCode) {
this.val = vl ;
this.exit = exitCode ;
SURVIVORS.put(this,exitCode);
}
protected void finalize() {
this.theEnd() ;
}
// the End code + volatile test for execution
}
</PRE>
<div style="text-align: justify;">THAT looked like some very abstract thing! (may be I was influenced by my desperate tries at understanding the fpl library of my friend <A HREF=http://lucdup.blogspot.com>Luc Duponcheel</A> ;-)) </DIV>
<div style="text-align: justify;">In that case the client code is going to handle a <TT>Capsule<Iterator<Thing>></TT> and iterates as needed ... bleech ... </DIV>
<div style="text-align: justify;">Frankly the little demon that supervises my sleep did not like this option so he came up with another solution .... </DIV>
more to come ....Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com1tag:blogger.com,1999:blog-3133411472229337008.post-13001357045509995712048-02-18T05:05:00.000-08:002008-02-19T02:17:43.022-08:00The hunt for the dangling Iterator (part 2)<div style="text-align: justify;">Our quest was: how to be sure that a client code using an <TT>Iterator</TT> is calling a close code when the interaction with the implementing code is finished?</div>
<div style="text-align: justify;">This code popped up:</div>
<PRE class="displaycode">
public class ExitIterator<X> implements Iterator<X> {
// if requested: create weak map SURVIVORS
private {=> void } exit ;
private Iterator<X> iterator ;
private AtomicBoolean exited = new AtomicBoolean(false) ;
public boolean hasNext(){
boolean ok = false ;
try {
ok = iterator.hasNext();
}finally {
if( ! ok) {
this.theEnd() ;
}
}
return ok ;
}
public X next() {
boolean ok = false ;
X res = null ;
try {
res = iterator.next() ;
ok = true ;
}finally {
if( ! ok) {
this.theEnd() ;
}
}
return res ;
}
public void remove() {
iterator.remove() ;
}
private void theEnd() {
if( ! exited.getAndSet(true)) {
if(exit != null) exit.invoke() ;
}
}
public ExitIterator(Iterator<X> it, {=> void} exitCode) {
// should check if iterator is null !
this.iterator = it ;
this.exit = exitCode ;
// SURVIVORS.put(this,exitCode);
}
protected void finalize() {
this.theEnd() ;
}
}
</PRE>
<div style="text-align: justify;">This code may exist in different flavours</div>
<UL>
<LI> "as is" if you reasonnably want the close operation to be invoked when the application is running </LI>
<LI> with a SURVIVORS <TT>WeakHashMap</TT> (see previous blog entry) if you want to be <B>damn sure</B> the close operation is invoked</LI>
<LI> a "belt and suspenders" option with a timeout that calls the exit code if the <TT>Iterator</TT> has not been used for a certain amount of time</LI>
</UL>
<div style="text-align: justify;">Now :</div>
<UL>
<LI> what qualifies this code for being considered a "solution" ?</LI>
<LI> what can we say about the path that lead us here? </LI>
</UL>
<HR>
<H2> A solution ? </H2>
<div style="text-align: justify;">Well there is a moment where you'll have to stop searching for an even better solution. So what qualifies this code for being landmarked so we can deal with other problems?</div>
<div style="text-align: justify;">I feel that it nicely fits into existing code:</div>
<UL>
<LI> A client code that already uses an <TT>Iterator</TT> is not to be modified: it's up to the implementing code to act</LI>
<LI> An implementing code that already produces an <TT>Iterator</TT> is to be only slightly modified since we need to slip an <TT>ExitIterator</TT> with proper exit code in between. So code modifications are minimal.
</UL>
<div style="text-align: justify;">The code is not perfect and may need further refinements ... but this is for further versions:</div>
<UL>
<LI> Why is there a <TT>WeakHashMap<Iterator<?>, {=> void}></TT> in the first place? (overkill?)</LI>
<LI>Could we quantify the performance penalty for using this new <TT>Iterator</TT>? (probably not that big an issue) </LI>
<LI> ... (please add your own critics here) </LI>
</UL>
<div style="text-align: justify;">The goal of this discussion is to deal with methods: when do you think you should stop/suspend your design errands?</div>
<H2>The path </H2>
<div style="text-align: justify;">One may wonder why I didn't come with the <TT>ExitIterator</TT> solution directly since constraints such as not meddling with client code could have been guessed in the first place!!!</div>
<div style="text-align: justify;">Well ladies and gentlemen let me state this: almost everything is obvious .... <U>AFTER</U>! (the Magnus Ridolph principle)</div>
<div style="text-align: justify;">I would even say that trying to focus on a limited set of hypothesis and reinjecting prerequisites later is stuff for an efficient search for a solution! This looks like a paradox but in practice it <B>IS</B> a practical behaviour</div>
<div style="text-align: justify;">I'll have to confess: I am not a genius! I need strategies to deal with complex problems and come with palatable solutions. My experience with different design activities (remember: I have been an architect!) is that they share a similar look and feel: we start an errand on different paths and the complex solutions are the first to come. We need to be stubborn and not to stop too hastily and we need an attitude to try to distill (slowly!) new structures and solutions.... This goes through sharing (<I>brainstorming</I>) and structural esthetical sense (?)</div>
<div style="text-align: justify;"> Looking for a design and freezing the state of our quest is the stuff about "fuzzy" inductive design methods (as opposed to "hard" deductive methods)</div>
More about this later ....Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-15002814295771473372048-02-15T03:02:00.000-08:002008-02-25T03:17:23.990-08:00Those elusive design patterns (part 1)<div style="text-align: justify;">When I was teaching maths (a long time ago!) I tried to infuse consideration towards well built coherent demonstrations.
</div><br>
<div style="text-align: justify;">Then one day a student asked a question about a theorem: "Clever! but how am I supposed to discover the solution to such a thing?"
</div><br>
<div style="text-align: justify;">I realised I had to teach that a demonstration was the final stage of a complex quest. During that search one had to mix deductive stages ("X implies Y") and inductive stages where the mind wandered in search of clues, paths, dead ends, magical inspirations ...
</div><br>
Can this design process be taught to be more efficient?
<br>
- Yes!
<br>
Then does the use of such methods guarantees a result?
<br>
- No!
<br>
<div style="text-align: justify;">Transposing this to information technology can lead to very pessimistic conclusions. When designing a software:
</div>
<ul><li style="text-align: justify;"> you are not sure your hypothesis are 100% valid, you are not sure that you are aware of all hypothesis, hypothesis may change during the life cycle!</li><li style="text-align: justify;"> we are not sure that the final stage (the software product) is coherent, reliable and even meets expectations.</li><li style="text-align: justify;"> the overall process by which we create this product is blurry: many methods compete for our attention. Some are as "hard" as possible (could be likened to deductive processes), some are more oriented towards behavioural patterns for the programming team.</li></ul>
<div style="text-align: justify;">In this blog I will use a gross approximation which is to qualify "soft" methods (methods not based on proofs) of being "fuzzy". Being rational beings we need rules even if these are rules of thumb or if the theoretical foundations for those rules are unsteady.
</div><br>
<div style="text-align: justify;">Those methods are useful but have a disturbing property: their relevance should be continuously re-evaluated. This is paradoxical: one works on methods to establish a process that will enable further economies of thought ... then we need to constantly review this process. So where is the economy?
</div><br>
In software engineering the paucity of meta-methods practices is dangerous.
<br>
<br>
<div style="text-align: justify;">I have been working in a corporation using "extreme waterfall" methods : for every step there is an extensive list of prerequisite documents and a list of mandatory documents to be supplied for the next step. I have no clue of wether this is justified without a context for my judgement, but my question is: is there an evaluation for the overhead generated by the procedure itself?
</div><br>
<div style="text-align: justify;">At the other end of the development spectrum "agile" methods have an empirical approach recognising that problems cannot be fully understood. Some rules state that distracting influences of things not being directly focused on the current goal should be eliminated. This rule has also limits: in some case it is extremely important and profitable to let someone wander off. So without an evaluation of the violation of rules we miss something!
</div><br>
<div style="text-align: justify;">So, roughly, every method should carry its rationale, critics and evaluation practices. This is obvious but frequently overlooked.
</div><br>
<div style="text-align: justify;">Let's have a look on programming design patterns and how those patterns should constanly be re-evaluated.
</div><br>
<div style="text-align: justify;">At this stage it is important to remind that the recognition of the "design pattern" notion has been inspired by architecture (Ch. Alexander) -though I.M.H.O the first precise description I know of dates back to Clausewitz and dealt with military strategy-.
</div><br>
<div style="text-align: justify;">-those of you who are not familiar with Java programming may skip the following entries of the blog-
</div><br>Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-12890299159878277742048-02-15T02:58:00.000-08:002008-02-26T08:29:06.431-08:00Those elusive design patterns (part 2)<div style="text-align: justify;">It may sound strange to talk about programming design patterns in a "fuzzy" methods context.
</div>
There are two reasons for that:
<ul><li style="text-align: justify;">- Though the inner mechanisms of programming patterns are well described their scope must be subject of very thorough discussions. In that sense I often say that design patterns are more "inspirational paths" than precise recipes. </li>
<li>- This notion of a structure that guides a search path has wider applications.</li>
</ul>
<div style="text-align: justify;">The initial descriptions of design patterns are accompanied by rationales and precise guidelines about their use and limits. Funnily if you browse the web those discussions tend to disappear: while focusing on the essence of the pattern most descriptions tend to forget those guidelines! The result is that we tend to be lazy or, even worse, use code generators once we have identified a pattern. As we profit from the work of our elders we forget about the precautions for use, we forget about re-enacting the logical build of the pattern. I am not talking about reinventing the wheel every time but about quickly following their path and profit from their experience ... which is different from applying indiscriminately a recipe.
</div>
Let's revisit a well known pattern which is Observer.
<div style="text-align: justify;">I have not found in line the precise description as in GOF (so for the moment just a concise description <a href="http://www.developer.com/design/article.php/10925_1502691_4">here </a>)
</div>
<div style="text-align: justify;">Now compare the GOF description with the Java implementation of <tt>Observer/Observable</tt>:
</div>
<pre class="displaycode">
public class Observable { // the "subject"
// details skipped here
// including interesting case of setChanged()
public void addObserver(Observer o) { .....
public void notifyObservers(Object arg) { ....
public interface Observer {
public void update(Observable o, Object arg) ;
}
</pre>
<div style="text-align: justify;">Though many people argued against <tt>Observable</tt> being a class (and not an interface) I would rather focus on other additional remarks here :
</div>
<ul><li style="text-align: justify;">- Java has opted for a "push" option : the <tt>Observer</tt> does not have to go after the subject to request state information. The notification object could be anything (including something that may enable the Observer to request back some state information!).</li>
<li style="text-align: justify;">- Implicitly the Observer here can register itself to different subjects. Other implementation of this pattern may skip this ability.</li>
<li style="text-align: justify;">- The "contract" for an actual <tt>Observer</tt> should specify more contraints. A common example is that each update method should terminate as quickly as possible to avoid blocking further notifications to other Observers. One could implement a different set of Observer/Observable where there is a different Thread to handle each notification (or anything that could make the notification asynchronous -we are here slipping towards a publish/subscribe pattern-). Note that abnormal termination of update should also be handled gracefully (that is: if a <tt>Throwable</tt> is creeping up the stack the Subject should not crash).</li>
<li style="text-align: justify;">- Another twist to the story is illustrated by the event mechanism in AWT: when notifications are fired in rapid bursts there could be a merging of events in an event queue.</li>
<li style="text-align: justify;">- The fact that <tt>Observer</tt> is an interface is an illustration of the decoupling principle. This can be illustrated with the example of the call-back pattern: Object of type <tt style="font-weight: bold;">O</tt> is registering itself with object of type <tt style="font-weight: bold;">S</tt> that will call back later. Since <tt style="font-weight: bold;">O</tt> "knows" <tt style="font-weight: bold;">S</tt> and <tt style="font-weight: bold;">S</tt> keeps a reference to <tt style="font-weight: bold;">O</tt> there would be a cyclic dependency of types if <tt><span style="font-weight: bold;">O</span> </tt>were not an interface. This pattern can be considered as a simplified <tt>Observer</tt> case: there is only one Observer. </li>
</ul>
<div style="text-align: justify;">Let's have a look at a use of this simplified pattern ... this will lead us to further versions of the Observer:
</div>
<div style="text-align: justify;">Suppose we are desiging a GUI where there is a Component that helps the user to choose an <tt>Item</tt> and another Component which is able to show the details of the <tt>Item</tt>.
</div>
<pre class="displaycode">
public class ShowItem extends Panel {
.....
public void show(Item choosen) { ....
}
</pre>
Then the <tt>ItemChooser</tt> Component:
<pre class="displaycode">
public class ItemChooser extends Panel {
....
public ItemChooser(ItemCatalog catalog, ItemSelector selector) { ...
}
</pre>
<div style="text-align: justify;">When the user picks up an <tt>Item</tt> with the help of the <tt>ItemChooser</tt> then another code will be notified. The reference to this code (<tt>ItemSelector</tt>) should be an interface, then
</div>
<pre class="displaycode">
public class Pilot extends Panel implements ItemSelector {
// this component has a Controler role
// create subComponents of type ItemChooser and ShowItem
private ShowItem presenter;
private ItemChooser chooser ;
public Pilot(ItemCatalog catalog) {
chooser = new ItemChooser(catalog, this) ;
presenter = new ShowItem() ;
...
}
// the contract of ItemSelector
public void select(Item choice) {
presenter.show(choice) ;
}
...
}
</pre>
<div style="text-align: justify;">Here we could not design an <tt>ItemChooser(ItemCatalog, Pilot)</tt> otherwise we will get a strong coupling between the <tt>Pilot</tt> and <tt>ItemChooser</tt> classes.
</div>
<div style="text-align: justify;">This said the <tt>ItemSelector</tt> definition is slightly contrived: can we make it more general, more "pattern like"? This will lead us to reconsider the more general Observer pattern.
</div>
More to come ....Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-46855187549269078182048-02-15T02:16:00.000-08:002008-02-26T06:16:15.794-08:00Those elusive design patterns (part 3)(continuation of part 2)
<div style="text-align: justify;">In our previous example I thought that the definition of <tt>ItemSelector</tt> was slightly contrived. Could we make it more general?
</div>
<BR>
<pre class="displaycode">
public interface Selector<X> {
public void select(X select) ;
}
</pre>
<BR>
In that case the <tt>ItemChooser</tt> could look like :
<BR>
<pre class="displaycode">
public class ItemChooser extends Panel {
....
public ItemChooser(ItemCatalog catalog, Selector<Item> selector) { ...
</pre>
<BR>
We could even try more parameterised code ... but this is beyond the point :
<BR>
<pre class="displaycode">
public <X extends Item> ItemChooser(Catalog<X> catalog, Selector<? super X> selector) { ...
</pre>
<BR>
So this may lead to consider parameterised code for the Observer pattern :
<BR>
<pre class="displaycode">
public interface Observer<X> {
public void update(X arg) ;
}
</pre>
<BR>
Then one could create either parameterised Subject :
<BR><pre class="displaycode">
public void notifyObservers(X changed) ;
</pre>
<BR>
or "ad hoc" subjects pushing different data types :
<BR><pre class="displaycode">
public void addThingObserver(Observer<Thing> obs)
public void addItemObserver (Observer<Item> obs)
</pre>
<BR>
<div style="text-align: justify;">It's a choice: by controling more closely the type of the notification object we also loose generality.
</div>
<BR>But let's go back to our callback example. In the <tt>Pilot</tt> code :
<pre class="displaycode">
public class Pilot extends Panel implements Selector<Item> {
</pre>
<BR>
<div style="text-align: justify;">We still expose publicly some internal behaviour of <tt>Pilot</tt> which is it responds to a choice made by an inner component. We could hide this by creating an inner class implementing the <tt>Selector</tt> contract (or many inner classes implementing different <tt>Selector</tt> contracts) but the closure features enable somthing which is closer to the callBack notion:
</div> <BR>
<pre class="displaycode">
public class Pilot {
private ShowItem presenter= new ShowItem() ;
private ItemChooser chooser ;
....
public Pilot (Catalog <? extends Item> cat) {
chooser = new ItemChooser(cat, {Item item => presenter.show(item); });
}
</pre>
<BR>
and <tt>ItemChooser</tt> having :
<BR><pre class="displaycode">
public ItemChooser(Catalog <? extends Item> catalog,
{Item => void} action ) { ...
</pre>
<BR>
<div style="text-align: justify;">or some parameterised variant of it. Note that the decoupling is still better since the code which has the initiative of the call does not even need to know the name/purpose of the called method.
</div>
<BR>Now how about a Subject defined thus:
<BR>
<pre class="displaycode">
public class Dispatcher<X> {
private ArrayList<{ X=> void}> actions = new ArrayList<{X=>void}>() ;
public void addAction({X => void} action) {
actions.add(action);
}
public void fire(X event) {
for( {X=> void } func : actions) {
func.invoke(event);
}
}
}
</pre>
<BR>
<div style="text-align: justify;">A funny twist could be added by making sure that every Observer code gets a different object as the result of the event! This could be through a <tt>Dispatcher<{=>Thing}> </tt> and it that case it's up to each observer to call the method that generates each distinct object. (another example: <tt>Dispatcher<{=>Iterator<Double>}></tt>
</div>
<BR><div style="text-align: justify;">It could be also through a method that guarantees that the generating method is called by the subject before any transfer to the observer:
</div>
<pre class="displaycode">
public void mapFire( {=>X } generator) {
for( {X=> void } func : actions) {
func.invoke(generator.invoke());
}
}
</pre>
<BR>
<h3> conclusions </h3>
<ul><li style="text-align: justify;">- Revisiting the pros and cons of a pattern, browsing through the possible options and weighing the implementation choices will help both to match the implementation to your needs AND to reconsider your analysis through the light shed by the pattern's options . This a two ways process!</li>
<BR>
<li style="text-align: justify;">- Compare the initial UML schema and the latest codes for <tt>Dispatcher</tt>. This is to illustrate a principle: a design is not independent of the implementation language. Though we may try to design at a higher level of abstraction (and not deal with those pesky details of implementation) the paradigms of the implementation are still reflected at a higher level. You just can't have strategic thinking if you do not have some feedback from the field!
<BR> (note : I even suspect some design patterns to be inherently implementable with interpreted languages -primary suspect: Visitor-) </li></ul>
<BR>
<BR>(feb. 26 2008).Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-77323719925138137252048-02-12T07:11:00.000-08:002008-02-27T08:33:29.042-08:00Recreational lab: recreate your command patternGoing on vacation tomorrow so here is a lab:
<BR>
Let's suppose you have an application where two J.V.M. cooperate across the wire (using some serialization).
<BR>
Now consider things such as :
<BR>
<TT>interface XY_R<X,Y,R> extends {X, Y => R} , Serializable {} </TT>
<BR>
Some code using this (<TT>oos</TT> is an <TT>ObjectOutputStream</TT> and the code is in a static main) :
<BR>
<PRE>
XY_R<Double,Double, Double> func = { Double x, Double y => x+y } ;
oos.writeObject(func);
Double db = new Double(3.14);
XY_R<Double,Double, Double> func2 = { Double x, Double y => x+y*db } ;
oos.writeObject(func2);
</PRE>
<BR>
<ul><li> Experiment with more complex closures (embarking instance data)</li>
<BR>
<li> Rewrite a command pattern with that (so one J.V.M can send a command to be executed by the other J.V.M) .</li>
<BR>
</ul>
Have fun !
<BR>
....
<BR>
.....
<BR>
Sad note: though this looks fun, deployment problems are tricky (unless you download dynamically the anonymous inner classes from the JVM which initiates ) ... so it's not such a good idea after all!
<BR>
....
<BR>
.....
<BR>
Plus: since generics are a compile-time thing it does not make much sense here in a dynamic context so better stick to <TT>interface MyCommand extends {LocalContext => Result } , Serializable {} </TT>
<BR>
<BR>
.... I <B>need</B> vacations ....Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-85502916650567283102048-02-04T09:24:00.000-08:002008-03-27T06:49:31.266-07:00Code speed-reading<div style="text-align: justify;">When dealing with lot of codes from other programmers you are obliged to learn to "speed read".</DIV>
<BR>
<div style="text-align: justify;">As with any speed reading technique you need to learn to quickly spot structures and anomalies in a code which is supposed to have been compiled and so is syntactically correct. The first step is to refuse to read code which is not properly indented and/or does not follow the "etiquete" of the language (such as the standard naming conventions in Java). </DIV>
<BR>
<div style="text-align: justify;">This said not all programming languages are created equals when it comes to ease of quick-reading. Designers of new languages have so many things to do that I wonder if the ergonomy of the syntax is top priority and is based on behavioural studies. But when a new syntactic feature is proposed there are numerous comments and wars of religion on this very problem: is this syntax felt as "programmer friendly"?.</DIV>
<BR>
<div style="text-align: justify;">This looks as a very subjective topic; everyone is influenced by his handling of other programming languages and "gut feelings". This is typically a DESIGN problem: we know there is something to do but the constraints appear fuzzy.</DIV>
<BR>
<div style="text-align: justify;">Since I am not presently trying to write a strict PhD thesis on the subject I will try a more "impressionist" approach by putting forward some considerations , subjective judgments and half-baked ideas (and hope more rationality could emerge from ensuing comments).</DIV>
<BR>
<div style="text-align: justify;">First remember that some "barbaric" syntactic features become "idioms" everybody can read once we are accustomed to them : remember that one in C ?</DIV>
<BR>
<PRE class="displaycode">
while(*ptdest++ = *ptorigin++) ;
</PRE>
<BR>
<div style="text-align: justify;">Then remember that the devil is in the details: for instance in Java it is a really bad thing that the same notation (<TT>+ * / - % </TT>) is used for arithmetic operations wether the operation is on integer or floating point types. You may think it is a minor glitch but I tested it thoroughly with hundreds of students: after warning them I have them perform a lab wih a simple calculation ... 98% of them get it wrong and write code that is not going to work properly! So here the conclusions are not that intuitive.</DIV>
<BR>
<div style="text-align: justify;">Let's try to describe some problems that slow my code reading:</DIV>
<UL>
<LI> Having a symbol both in a parenthesis-like fashion and as a "single occurence" : in java we use "<" as an operator and in expression like <TT>ArrayList<Thing></TT>. Hey there is not a single case of syntactic ambiguity! Yes but I am talking about your quick eyes movements that scan the code. </LI>
</UL>
<BR>
Not convinced? let's try something else:
<UL>
<LI> Having keywords or symbols with a different meaning according to the context? Primary culprits: <TT>< ? extends Iterable></TT> - here I feel bad about <TT> extends </TT> but not about "<TT>?</TT>" how is this possible?- Same for <TT>< ? extends Thing & Closeable></TT> : I feel bad for the "<TT>&</TT>" not for the "<TT>?</TT>". </LI>
</UL>
<BR>
<div style="text-align: justify;">Do you feel similar problems? They may be just "similar" not "the same" so I would be curious for a real scientific screening of quick code reading.</DIV>
<BR>
How about the wonderful things the code editor of your IDE will do for you?
<BR>
<div style="text-align: justify;">Well the problem is that coloring keywords or types is not the way to go.
An horror museum of code coloring <A HREF=http://www.gnu.org/software/src-highlite/style_examples.html> HERE </A>.
The basic rules of visual design should stop programmers to use flickering effects when showing code. </DIV>
<BR>
<div style="text-align: justify;">At first glance we need to get the structure of the code: where is this variable, method, constructor defined? Where are we in the code? Those structures that help us navigate are somewhat different from the syntactic features: too bad! </DIV>
<BR>
<div style="text-align: justify;">Why don't we get languages where keywords, symbols, different flavors of variables (such as local or members), different methods and named blocks of code could be spotted at once because their definition and their use have distinct syntactic features? In a language where a keyword could never be mistaken with a variable name you are free to augment the language with any new keyword!</DIV>
<BR>
<div style="text-align: justify;">Another point: we still use text-based language. I am not advocating a new APL but a distinction between the source code that is compiled and the source code that is handled by the programmer. Why not imagine "three dimensional" languages with different clear views handled by an I.D.E
That could rely on a more obscure two dimensional text formalism (not handled by the programmer)?</DIV>
<BR>
<div style="text-align: justify;">Easier said than done: syntax-guided editors look like a good idea but have failed to deliver
(our mind likes to wander and hates being too much guided by a hierarchy).
.... We need something which should be both loose (where you can freely type as your thoughts flow) and structurable on demand : programming objects can be handled globally, annotated with anything we need (including formalisms alien to the language)...
A simple example: when writing Java code with Netbeans I would gladly like to have different colours in the background to mark code executed by different threads!</DIV>
<BR>
<div style="text-align: justify;">Conclusion: languages rely on complex studies but ergonomy of the code should be a subject by itself. Thanks for any hint or link to studies on this.</DIV>
(March 14 2008)
<BR>
<BR>
<hr>
<H3> suggestion about netbeans </H3>
(added March 26 2008)
<BR>
<div style="text-align: justify;"> Since there is a contest about netbeans <A HREF=http://www.netbeans.org/competition/blog-contest.html?cid=923686> HERE </A>
I will suggest some enhancements to the code editor</DIV>
<BR>
<div style="text-align: justify;">A programmer should be able to add his own formatting to a code to help better code-reading.</DIV>
<div style="text-align: justify;">At low level this could be implemented with special comments that could be kept in the code. </DIV>
<BR>
Suppose you create a syntax more or less like this:
<PRE>
// special comments at the beginning of the source define tags
/*#def DownLoadThread BgColor(10,34,120) Visible*/
// means that the tag will be used to delimit a zone with a background Color
// and that the tag will be shown as a special comment
.... //code
// use
/*#DownloadThread*/
// code of this Thread
/*#/DownloadThread*/
// other codes
</PRE>
<div style="text-align: justify;">Again the idea is to let the programmer deal
with more formatting than the automatic formatting of the editor.</DIV>Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com0tag:blogger.com,1999:blog-3133411472229337008.post-74887152908974960562048-02-01T06:01:00.000-08:002008-04-10T09:45:21.139-07:00May happen! ..... So what? (over-engineering qualms)<div style="text-align: justify;">Common wisdom amongst software developpers: if something bad may happen then it will happen! So if your design is left with gapping holes be sure someone will fall into those! But if you happen to know about those "holes" there is another nagging question: is it possible or economically sound to fill in those gaps?</DIV>
<BR>
<div style="text-align: justify;">That happened to me a long time ago: I implemented a SQL interpreter and realised that some properties of my code may lead to hog the runtime , or even crash it. As I was worried by that I talked with other developpers and one came with this startling assertion: those conditions are simply not going to be met in "real life"! </DIV>
<BR>
<div style="text-align: justify;">We were stuck in a dilemna: we had no proof that it could not happen but trying to fill in the gaps would cost a lot in terms of work and performance. So we decided to hide the gaps and wait: the intuition that nothing was going to happen there has been proved to be practically right during all the product's life.</DIV>
<BR>
<div style="text-align: justify;">This example could barely be used for other developpers: it is an anguishing situation to know that something MAY be wrong! This said overanguished developpers may also be fighting windmills: this may happen ... but will it happen? The best thing to do is to prove that it could happen or not... but are we able to provide this proof?</DIV>
<BR>
<div style="text-align: justify;">Happily it is sometimes possible to question defensive programming with arguments (provided we do not stick to the rules just to relieve our anguishes).</DIV>
<BR>
<div style="text-align: justify;">Though this is a far from perfect illustration I would like jump at the opportunity to emphasize the importance of questionning engineering decisions that could stem from sheer habits.</DIV>
<BR>
So again java code:
<BR>
More or less a typical example about the Singleton pattern :
<BR>
<PRE class="displaycode">
public class ASingleton {
// a private constructor
private ASingleton() { .....}
// a static instance (could be initialised lazily or in a static block)
private static ASingleton INSTANCE = ..... ;
// factory method
public static ASingleton getInstance() {
// returns INSTANCE one way or another
}
}
</PRE>
<BR>
<div style="text-align: justify;">A rule of thumb is that if <TT>ASingleton</TT> is <TT>Serializable</TT> then one should provide :</DIV>
<BR>
<PRE class="displaycode">
private Object readResolve() {
// returns INSTANCE one way or another
}
</PRE>
<BR>
<div style="text-align: justify;">This last code should be discussed: the idea of <TT>readResolve</TT> is that if your read an instance from an <TT>ObjectStream</TT> then you may end up with different instances of the Singleton! So a good defensive practice is to make sure there is only one instance of the singleton ....</DIV>
<BR>
This may happen .... So what?
<BR>
<div style="text-align: justify;">This should be discussed and we need to go a bit further than the constraint "one instance":</DIV>
<BR>
<H3>Point 1 : we may need only one state ... but we do not necessarily need one instance!</H3>
<BR>
How about a singleton written that way:
<BR>
<PRE class="displaycode">
public class Service {
// could be from a private inner class
private static ServiceImplementor INSTANCE = .... ;
// a constructor!
public Service() {}
// every method is delegated to a static service
public Thing method() { return INSTANCE.method() ; }
// may be override some methods from class Object
}
</PRE>
<BR>
In that case:
<BR>
<UL>
<LI> <div style="text-align: justify;">the client code is not necessarily aware that it is using a singleton (this property is hidden to client code) </DIV>
<BR>
</LI>
<LI> <div style="text-align: justify;">the unicity of the service is nonetheless fulfilled! This, by the way, is coherent with the definition of an object as a device that do something: client code is not supposed to know how it is done.</DIV>
<BR>
</LI>
<LI> <div style="text-align: justify;"> if the client code wants to use the object for its monitor (synchronization, wait/notify) or wants to use the <TT>==</TT> operator, it is not going to be possible ... hey! wait a minute: the client code is not supposed to <U>know</U> that it is using a Singleton.</DIV>
<BR>
</LI>
</UL>
<H3> Point 2: most singletons are about a context!</H3>
<UL>
<LI>
<div style="text-align: justify;">Most singletons represent something which is external and bound to a context (a System, a spool, a configuration) and the question is: to what context are we bound? a J.V.M? a <TT>ClassLoader</TT>? a Thread (<TT>ThreadLocal</TT> objects)? So it is not that uncommon to get different instances representing the context service (even unwillingly: in the case of <TT>ASingleton</TT> above you may get different instances in a J.V.M if different <TT>ClassLoader</TT>s are involved).</DIV>
<BR>
</LI>
<LI>
<div style="text-align: justify;">When representing services bound to a context then those singletons are either not serializable or their instance is a representation of a remote context. That is: if JVM1 is sending an instance to JVM2then this instance is representing the context of JVM1 on JVM2 (a remote reference to a service). In that case there could be two different references on JVM2: one of the local context and one of a remote context.</DIV>
<BR>
<div style="text-align: justify;">One could argue that something like a printing service should be accessed locally! But in that case the request for the service should be local (method call) and there is no reason to send an instance!
(Only possible exceptions are those of point 3).</DIV>
<BR>
<div style="text-align: justify;">Note: the class <TT>Service</TT> above is not suited for this remote reference passing since it will get its behaviour only from the static context of the class. (But you can design hybrid codes with local <U>and</U> remote data).</DIV>
<BR>
</LI>
</UL>
<H3>Point 3: singletons as special instances of a service </H3>
<div style="text-align: justify;">An example of this is <TT>Collections.EMPTY_LIST</TT> we have a singleton that implements the
<TT>List</TT> services. In fact this looks like an <TT>enum</TT> with a single value.</DIV>
<BR>
<div style="text-align: justify;">Since those could be elements in a structure (an object has a reference to a <TT>List</TT> which happens to be an <TT>EMPTY_LIST</TT>) they should be serialised.</DIV>
<BR>
<div style="text-align: justify;">Then if you want to use checks such as <TT>node == EMPTY_LIST</TT> then the unicity of the instance is required (and <TT>readResolve</TT> used).</DIV>
<BR>
<H3>May happen! ..... so what?</H3>
<div style="text-align: justify;">In my humble opinion the systematic use of <TT>readResolve</TT> is over-engineering: we are afraid of instance duplication .... should we be afraid of that?</DIV>
<BR>
<div style="text-align: justify;">For sure I am interested in examples of singletons that do not match the abovementioned points
that will show that it is hard to prove a general point and when confronted with a suspicion of over-engineering there are decisions that rely on risk analysis (we do not have an expert at hand everytime).</DIV>
<BR>
(Again the example is a bit far-fetched: there is no big risk involved here).
<BR>
<HR>
A side note: this blog entry was written in response to
<A HREF=http://blogs.sun.com/JavaFundamentals/entry/using_enhanced_for_loops_with> this blog </A> but the editorial process there failed to register a link to this response ... so ?Bernard AMADEhttp://www.blogger.com/profile/09173861180363920565noreply@blogger.com1