Thursday, April 19, 2012

London marathon will be last for Fauja Singh

101 years old!

Fauja Singh, who was born in India but moved to Britain in the 1960s, has completed eight marathons since taking up the sport at the age of 89.

http://www.bbc.co.uk/news/uk-17765170


I posted about him last October when he was younger

Friday, April 13, 2012

You are not authorised to run this application. ... illegal value.

"You are not authorised to run this application.
The administrator has set your shell to an illegal value."



Well this isn't good. I closed down all open applications, then tried again but nothing. (I was working in Xcode and iOS simulator plus the usual browsers etc.)
I rebooted, and it worked. Not sure why.
I googled it and the only references I found were for quite a few years ago. Two days ago I updated Xcode and I hope it isn't related to that. I've been waiting for the Xcode crashes but as yet they haven't visited which is a welcome surprise.

Getting started with DDD when surrounded by Legacy systems II, by Eric Evans


I got this email a month or so back. Not sure if I should re-post it or not.
It has two parts,
  1. It advertises the up coming DDD courses in NY, Denver and London. 
  2. Then Eric describes how to get started in a legacy environment - (part II).
The parent website is here: http://domainlanguage.com

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DDD IMMERSION

ENROLL EARLY FOR SUMMER CLASSES

GETTING STARTED WITH DDD WHEN SURROUNDED BY LEGACY SYSTEMS II

STRATEGY 2: AUTONOMOUS BUBBLE

by Eric Evans
  1. Cutting the umbilical
  2. The Synchronizing ACL
  3. Bubble vs. Autonomous Bubble

CUTTING THE UMBILICAL

In a previous newsletter I discussed the "Bubble Context" as a way to get started with DDD when there is not much organizational commitment. The bubble context is completely dependent on the parent context, drawing all its data through an anti-corruption layer (ACL) like an umbilical cord. You can use that strategy when little else might work. However, it has its limits.
Almost all software uses data that comes from other contexts. A lot of interesting domain logic revolves around combining data from different sources and reasoning about it. Even with one source, there may be a significantly new way of thinking about the data that is fundamental to the desired new functionality (a new way of abstracting the domain, i.e. a new domain model). Sometimes this is done in ways that tangle the systems together and prematurely limit design freedom. The bubble context is quite natural way to start with such an undertaking because the team can experiment with models and combinations in isolation from the legacy system, while the Umbilical ACL obtains and translates the data with minimal impact to existing systems.
The Autonomous Bubble is distinguished by the ability to run its software, for a time, cut off from other systems. Information may start to get stale, requests to external service requests start to queue up unfulfilled, but the internal behavior of the software continues to work. Whereas the Bubble Context obtains its data from another context when it is needed, via the umbilical ACL, the Autonomous Bubble typically has some data store of its own. The data store could be in-memory – the storage medium is irrelevant – but the data is in the form native to the context. This is not just a cache of frequently or recently used data. In fact, an umbilical ACL could cache data as a performance enhancement. The point of the local data store is that the overall evolution of the model and design in this context is much more loosely coupled to other contexts. It should be possible to test such a subsystem without mocks of other subsystems.

Main Characteristics of the Autonomous Bubble Strategy

  • Needs organization committed to significant new development with new design approach.
  • Allows new data to be collected and used without involving legacy.
  • Allows decoupled "product" to evolve.
  • May progress from Bubble Context as development is scaled up on a successful pilot project.

SYNCHRONIZING ANTICORRUPTION LAYER

An autonomous context has its own data, sufficient to its core functions, organized according to in its own abstractions. To enable this, the ACL takes on the responsibility of synchronization between data stores in two contexts, which do not depend directly on each other. This ACL activity is asynchronous with any activity in either context, with a service level agreement (SLA) regarding the freshness of the translated data.
Synchronizing ACL
Diagram of Synchronizing ACL
Compare this with the Umbilical ACL of the Bubble Context here

The Nightly Batch Script: Low-tech Synchronizing ACL

Asynchronous synchronization with an SLA sounds more daunting than it is. It can be quite low-tech and examples are all around us. A very familiar implementation of the Synchronizing ACL is the “nightly batch”.
Now a typical nightly batch script does all sorts of things, some of which include important business logic. But, in my observation, one thing most of them do is to update one data store based on another. This could involve importing data from a file. It could involve kicking off a SQL script taking data from one table and transforming it and inserting it into another. It takes many forms, but look at a nightly batch script and you’ll probably find a Synchronizing ACL mixed in there.
    Typical nightly batch script has:
  • SLA: Open of business, next business day
  • Unnecessary coupling: Synchronizing ACL mixed in with once-per-day business logic
  • Unnecessary coupling: Multiple ACLs to multiple contexts lumped together.
If you are trying to establish an autonomous bubble, and you think your translation could be handled as part of a nightly batch script, then make sure you isolate the data copying and translation for your particular context into modules (one per context you are drawing on) which can be kicked off by the script. Don't let it get tangled into the spagetti. You need a decoupled synchronized ACL to pull off an autonomous bubble.

Messaging and Domain Events: A Stylish Synchronizing ACL

A more flexible approach to synchronizing uses messages carrying Domain Events. This can be nicely integrated with other event-driven architectural patterns. This approach can support a range of SLAs, and can update a system while it is being used, while batch scripts typically run while systems are off-line.
People discuss the use of messages and events for integration quite often, but usually they don't talk explicitly enough about what happens when a message crosses a context boundary. Just remember, any information crossing a context boundary must be translated. Messages are not somehow neutral. They are always expressed in some language based on some system of abstractions (a model), and we should not let them enter a context that uses a different language and model.
ACL translating Domain Events
Diagram of Synchronizing ACL translating events from one context
            to another.
Many ways of implementing a Synchronizing ACL are in use and more will come in the future, so I won't try to catalog them. Any mechanism that can update a data store in one context based on data in another, translating along the way, and can do this asynchronously, and without introducing any dependency on it from either context, could be used to implement a Synchronizing ACL. You probably have Synchronizing ACLs in your system now, although they may be tangled with other responsibilities

BUBBLE VS. AUTONOMOUS BUBBLE

The first two strategies I've described each create a "bubble" context, and in this sense they are very similar, and resemble each other when looking inside the bubble. However, the difference in the relationship to the legacy contexts leads to a significant difference in the options for what you can do within the bubbles.
The "Umbilical ACL" from the first strategy gives us as little architectural overhead as possible, but allows no data to be used that can't be mapped from a context continuously attached. Any new information that does not already exist in the legacy system somewhere must be added to the legacy system somewhere, even though it will not be used there! Then it must be mapped into the bubble context, increasing the dependency between the two systems. Clearly this is not the strategy we want once we are introducing significant new information.
In contrast, the "Synchronizing ACL" gives more autonomy to the newly formed context. This autonomous bubble has its own data, some of which is mapped from another context, but it can also have data of its own. So development in the autonomous bubble is not so tightly bound to the older contexts. The model in this context can be more innovative and grow more freely, and a fresh new product can be created.

NEXT TIME: EVOLVING A MODEL IN A BUBBLE

Design freedom is the point of a bubble. The bubble context with an umbilical ACL gives a little freedom, while the Autonomous Bubble can give us a lot if properly managed. However, in the actual unfolding of a development project, there are many ways this can go wrong and bog down before the team has reached its goals. In my next article I'll give some guidelines for process and design that help the team retain and even increase their ability to change the model as the project goes along.

Tuesday, April 10, 2012

Objective C - Dot notation or Message (bracket) notation

Do I prefer the dot notation or the bracket notation. If you spend most of the time in languages like C# then switching to Objective C will definitely generate an opinion or two on the bracket notation. I think it's great sometimes, then I think it's not. What I do like is the way we are forced to think about messages rather than simply calling a method on an object. That is refreshing somehow.

Readability

I'm convinced that the readability of the .notation is somehow easier to read, but then I think it misses some of the action of what is going on. Objective C is about messages and in #2 the message sending seems more obvious.

1. [myObject.doSomething sendAMessage]
2. [[myObject doSomething] sendAMessage]

But is that important when reading someone else's code? Yes I think it is. If I stop looking at the code above as if it were mine, and instead think of it as someone else's, and if I imagine I'm not happy at having to look at this person's code, then #2 does seem easier. Weird.

Attributes and Properties

Well perhaps this is ok for dot notation. For properties it seems to be much better.

1. [display setText:digit]; 
2. display.text = digit;


Structs

You can't send a message to a struct so the dot notation is a simple way of telling the reader that the reference is actually a struct rather than an object. This is a good thing. But, should we really care when we are reading someone else's code. I think not, in general. I think worrying about types is secondary information when understanding code.

Conclusion

I'm probably a fan of Message Notation over Dot notation, but I'm not sure why.
Dot notation for properties, message notation for behaviour is the way to go.




Monday, April 9, 2012

Where is the add-in manager in Mono Develop OR, How to instal MonoMac


MonoMac, a new foundation for building Cocoa applications on OSX using Mono. It's page can be found here.

Well on the website it says to:
        1. Open the Add-in Manager from the Tools->Add-in Manager menu

Well not in my Mono. For me it's in the MonoDevelop menu drop down.


I think MonoMac is installed by default anyway, but if it isn't just go to the Add-in Manager.




Sunday, April 8, 2012

A Recursive Decent Parser in C# using BNF

Introduction

Carrying on from my last two posts I'll quickly take the Backus Naur Form, or the Extended Backus Naur Form and use that to create a simple Recursive Decent Parser.

A word of caution. My use of BNF is a bit loose. If you were to write a EBNF that was going to be machine read, or if you were working on some serious industrial strength domain language then this should be tight and rigorous so that everyone understood the BNF syntax. Mine is a bit loose, but is fine for holding the grammar and being used to write the parser.

My two previous posts have been on:


The project

This is a simple calculator. So simple that it only takes in single characters, 2+1, 9+5 are valid. 12 + 6 isn't. (12 has two digits).


The BNF for the grammar


<expression>  :=  <number>  |
                   "(" <expression> <operator> <expression> ")" 
                   
<operator>  :=  "+" | "-" | "*" | "/" 
<number> := '0' |'1' |'2' |'3' |'4' |'5' |'6' |'7' |'8' |'9' 


Notice that there are three "production rules", expression, operator and number.
This suggests that there will be tree main methods with the same (or similar names).

Notice that I have not used a termination character. No reason why.
Notice that I have used BNF for assignment ":=" rather than "=". Why? I just prefer it.


The code

I tend to avoid comments in code as I firmly believe that the code should comment itself. However, I have taken the BNF rules and placed them as comments above the methods that implement them.
Notice that <expression> has become a method whose name is ExpressionValue()

Take notice of the Exception class. This is a must have really.


using System;

namespace RecursiveDecentParser
{
public class Calculator
{
private System.IO.StringReader _reader;
public Calculator (string text)
{
_reader = new System.IO.StringReader(text);
}
public double Calculate()
{
return ExpressionValue();
}
//<expression>  ::=  <number>  |
        //                   "(" <expression> <operator> <expression> ")" 
private double ExpressionValue()
{
SkipBlanks();
char ch = (char)_reader.Peek();
int num = -1;
bool chIsNumber = CharIsDigit(ch, out num);
if (chIsNumber)
{
_reader.Read();
return num;
}
else if(NextCharIsOpenBracket())
{
ConsumeNextChar();
double leftExpressionVal = ExpressionValue();
char op = GetOperator();
double rightExpressionVal = ExpressionValue();
SkipBlanks();
if(!NextCharIsClosingBracket())
{
throw new ParseException("Missing closing bracket.");
}
else
{
ConsumeNextChar();
return PerformOperation(leftExpressionVal, op, rightExpressionVal);
}
}
else
{
throw new ParseException("Unexpected character, \"" + _reader.Peek() + "\" in input.");
}
}
//BNF: <operator>  ::=  "+" | "-" | "*" | "/"
private char GetOperator()
{
SkipBlanks();
char op = (char)_reader.Peek();
if(op == '+' || op == '-' || op == '*' || op == '/')
{
_reader.Read();
return op;
}
else if (op == '\n')
throw new ParseException("Missing operator at end of line");
else 
throw new ParseException("Missing operator. Expected +, -, * or /" +
                        " Found " + op ); 
}
// BNF: <number> ::= '0' |'1' |'2' |'3' |'4' |'5' |'6' |'7' |'8' |'9'
// Yes! only one digit at the moment.
private int GetNumber()
{
SkipBlanks();
char ch = (char)_reader.Peek();
int num = -1;
//bool chIsNumber = int.TryParse(CharToString(ch), out num);
bool chIsNumber = CharIsDigit(ch, out num);
if(chIsNumber)
{
ConsumeNextChar();
return num;
}
else if (ch == '\n')
throw new ParseException("Missing operator at end of line");
else 
throw new ParseException("Missing operator. Expected +, -, * or /" +
                        " Found " + ch ); 
}
private double PerformOperation(double leftVal, char op, double rightVal)
{
double result = 0;
switch (op)
{
case '+':
result = leftVal + rightVal;
break;
case '-':
result = leftVal - rightVal;
break;
case '*':
result = leftVal * rightVal;
break;
case '/':
result = leftVal / rightVal;
break;
}
return result;
}
private bool CharIsDigit(char ch, out int num)
{
string s = CharToString(ch);
return int.TryParse(s, out num);
}
private bool NextCharIsOpenBracket()
{
bool res = false;
char ch = (char)_reader.Peek();
if (ch == '(')
res = true;
return res;
}
private bool NextCharIsClosingBracket()
{
bool res = false;
char ch = (char)_reader.Peek();
if (ch == ')')
res = true;
return res;
}
private void ConsumeNextChar()
{
_reader.Read();
}
private void SkipBlanks()
{
while(CharToString((char)_reader.Peek()) == " ")
ConsumeNextChar();
}
private string CharToString(char ch)
        {
            return new string(ch, 1);
        }
}


    [Serializable]
    public class ParseException : Exception
    {
        public ParseException() { }
        public ParseException(string message) : base(message) { }
        public ParseException(string message, Exception inner) : base(message, inner) { }

        protected ParseException(
            System.Runtime.Serialization.SerializationInfo info,
            System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }
}



Unit tests

Here are some tests that show it's limitations and workings.
Notice that a single digit input will work, if it is enclosed in brackets it will not. This is in line with the BNF grammar.
An expression such as 2+3 must be enclosed in brackets.
As you can see, I have not tested the code for missing brackets, spaces in strange places, odd characters


[TestFixture]
public class SimpleInputTests
{
[Test]
[ExpectedException (typeof(ParseException))]
public void Exception_if_empty()
{
Calculator calculator = new Calculator("");
calculator.Calculate();
}
[Test]
[ExpectedException (typeof(ParseException))]
public void Simple_bracket_and_one_digit()
{
Calculator calculator = new Calculator("(2)");
calculator.Calculate();
}
[Test]
public void Simple_addition_with_brackets()
{
Calculator calculator = new Calculator("(2+2)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(4, answer);
}
[Test]
public void No_brackets_and_single_input_digit()
{
Calculator calculator = new Calculator("2");
Assert.AreEqual(2, calculator.Calculate());
}
[Test]
public void Simple_multiplication_with_brackets()
{
Calculator calculator = new Calculator("(2*5)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(10, answer);
}
[Test]
public void Simple_division_with_brackets()
{
Calculator calculator = new Calculator("(8/4)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(2, answer);
}
[Test]
public void Simple_subtraction_with_brackets()
{
Calculator calculator = new Calculator("(8-5)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(3, answer);
}
[Test]
public void Single_digit_add_bracketed_addition_clause()
{
Calculator calculator = new Calculator("(3 + (4+1))");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(8, answer);
}
[Test]
public void Bracketed_addition_clause_add_single_digit()
{
Calculator calculator = new Calculator("((4+1) + 3)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(8, answer);
}
[Test]
public void Random_complex_sum()
{
Calculator calculator = new Calculator("((4+(5-4)) + 2)");
double answer = 0;
answer = calculator.Calculate();
Assert.AreEqual(7, answer);
}
}
}



Saturday, April 7, 2012

EBNF - Extended Backus Naur Form

The next step on my way to write a parser. As mentioned in my previous post, I thought I needed a parser, then realised I didn't, and now think that I might like to re-learn the decent parser because it might come in handy - probably won't but it's fun.  Link to my post on BNF.

Why EBNF

EBNF makes BNF easier to understand. (Debatable)

The trouble with EBNF, and BNF, is that there are quite a few ways to use it. ISO has a notation and it's final draft can be found here. It is a good read and worth it if you're interested. You can skip the Forward and Introduction and jump to page 1 if you're short of patience.

EBNF includes regular expressions that can make the specification more compact.

Everything in EBNF can be represented in BNF.


Characters representing operators

These are listed in order of precedence.

*    repetition symbol
-    except symbol
,    concatenate symbol
|    definition separator symbol
=    defining symbol
;    terminator symbol

The specification gives alternative characters also, e.g. Table 2 in the ISO spec gives alternative terminal characters.

Precedence can be overridden using the following brackets.

'    first quote symbol       first quote symbol          '
"    second quote symbol      second quote symbol         "
(*   start comment symbol     end comment symbol         *)
(    start group symbol       end group symbol            )
[    start option symbol      end option symbol           ]
{    start repeat symbol      end repeat symbol           }
?    special sequence symbol  end special sequence symbol ?


Examples

See here for the C language in EBNF.



Another example:

number       = digit+ .
identifier   = letter (letter | digit)* .
functioncall = functionname "(" parameterlist? ")" .
+   - repeat 1 or more times
*   - repeat 0 or more times
?   - optional item

And another:

Here's some EBNF for  a simple calculator (unfinished - I'll do this in another post): 
calculator   = line (newline | line)* .
newline      = '\n' | '\r' | '\r\n' .
assignment   = identifier '=' expression .
sum          = 
identifier   = 
expression   = 
number       = ( '+' | '-')? digit+ .
digit        = '0' |'1' |'2' |'3' |'4' |'5' |'6' |'7' |'8' |'9' . 

BNF - Backus Naur Form

Miranda and mum

Such fun.

I've just started an interesting personal project that has some fun bits to it. Yesterday I wrote a simple tokenizer that looks quite neat and tidy, so I may post that soon. But today I felt I needed a parser. Then I realised that I didn't actually need a parser, but it would be fun to write one again after all these years. But I couldn't remember Backus Naur Form or, Recursive Decent parsers... it's all a blur. So I thought I'd make some notes on BNF, then I might look at the Recursive Decent Parser, or perhaps look at EBNF before that, then see why BNF is no use representing HTML.

So I dug out my old notes and it explained who Backus was, who Naur was (or "is" perhaps). And when the BNF was made and why. Wikipedia is the place for that info.

What is Backus Naur Form (Backus Normal Form)

BNF is used to define the grammar of language. It is not the only way, but it is a good and unambiguous way. Once defined, the grammar can be taken and used to create a complier. I only ever looked at Recursive decent parsers and that was many years back. There some pretty neat advances now and modern compilers don't tend to use this method now. But it's great if you need to create your own local language. Not many of us do, but I wish I did need to.

Rules

BNF has rules. You define the rules. These can be called production rules.

symbol := alternative1 | alternative2

This means, the symbol on the LHS must be replaced by one of the alternatives on the RHS

Some examples use, ::= instead of :=
I'm not sure which is more prevalent or better. I use :=

Terminals and Symbols

We say symbols in the the previous section. Terminals are the bits of the string that are not symbols. Terminals do not have productions rules. They terminate production.

Limitation and use

It is interesting to realise that BNF cannot express all of the syntax rules. It will not state that a variable needs to be defined before it can be used, for example. It also will not be able to describe semantic meaning. All it will do, is define the structure of the language, the framework.

The first example:

<number> := <digit> | <number> <digit>
<digit>  := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

I think the first tricky thing, or the only tricky thing, is the reading of the <number> <digit> rule.
Basically, this says that:
" a number is a digit, or a number which is followed by a digit."the second rule says, "a digit is a single character from 0, 1, 2 ... 9"

There are many other variations on the above example, here are a few:

<number> := <digit> | <number> <digit> .
<digit> := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 .

or,

<number> := <digit> 
         | <number> <digit>
         .
<digit>  := 0 
         | 1 
         | 2 
         | 3 
         | 4 
         | 5 
         | 6 
         | 7 
         | 8 
         | 9 
         .

or perhaps

number ::= digit | number digit .
digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 .



If you think of developing this, or even understanding this, you see that "a number can be a digit" OR, "a number can be a number followed by a digit". So, in code you would have to recursively call the number function again.

Full-on example of BNF - C syntax

The C language syntax in BNF can be found here: http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf
It is a bit intimidating at first.


translation_unit : external_decl
   | translation_unit external_decl
   ;
external_decl  : function_definition
   | decl
   ;
function_definition : decl_specs declarator decl_list compound_stat
   |  declarator decl_list compound_stat
   | decl_specs declarator  compound_stat
   |  declarator  compound_stat
   ;
decl   : decl_specs init_declarator_list ';'
   | decl_specs   ';'
   ;
decl_list  : decl
   | decl_list decl
   ;


Other posts:
Link to a post on using BNF to create a Recursive Decent Parser
Link to a post on EBNF

Thursday, April 5, 2012

The nature of deliberation and its objects: choice is the deliberate desire of things in our own power.

We deliberate not about ends but about means. For a doctor does not deliberate whether he shall heal, nor an orator whether he shall persuade, nor a statesman whether he shall produce law and order, nor does any one else deliberate about his end. They assume the end and consider how and by what means it is to be attained; and if it seems to be produced by several means they consider by which it is most easily and best produced, while if it is achieved by one only they consider how it will be achieved by this and by what means this will be achieved, till they come to the first cause, which in the order of discovery is last. For the person who deliberates seems to investigate and analyse in the way described as though he were analysing a geometrical construction (not all investigation appears to be deliberation--for instance mathematical investigations--but all deliberation is investigation), and what is last in the order of analysis seems to be first in the order of becoming. And if we come on an impossibility, we give up the search, e.g. if we need money and this cannot be got; but if a thing appears possible we try to do it. By 'possible' things I mean things that might be brought about by our own efforts; and these in a sense include things that can be brought about by the efforts of our friends, since the moving principle is in ourselves. The subject of investigation is sometimes the instruments, sometimes the use of them; and similarly in the other cases--sometimes the means, sometimes the mode of using it or the means of bringing it about. It seems, then, as has been said, that man is a moving principle of actions; now deliberation is about the things to be done by the agent himself, and actions are for the sake of things other than themselves. For the end cannot be a subject of deliberation, but only the means; nor indeed can the particular facts be a subject of it, as whether this is bread or has been baked as it should; for these are matters of perception. If we are to be always deliberating, we shall have to go on to infinity.



Book III: Moral Virtue, Chapter 3,
The Nicomachean Ethics of Aristotle
translated by William David Ross, 1908


The full text can be found here:
http://www.sacred-texts.com/cla/ari/nico/nico025.htm