The Factual modeling language generates code with basic behavior (a constructor, field access, and query execution). We can add domain-specific behavior using partial classes.

In the log on unit tests, we wrote the same three lines of code several times.
User user = _community.AddFact(new User("alan1"));
Machine machine = _community.AddFact(new Machine());
LogOn logOn = _community.AddFact(new LogOn(user, machine));
The model would be better if we could simply write.
Machine machine = _community.AddFact(new Machine());
We can add the LogOnUser method in a partial class.

Add a class to Lesson.Model. Name it "Machine". Add the modifiers "public partial" to the class declaration. Then add the LogOnUser method.
public partial class Machine
    public LogOn LogOnUser(string userName)
        User user = Community.AddFact(new User(userName));
        return Community.AddFact(new LogOn(user, this));
The method has access to the private "Community" property. This exposes the operations that a model typically performs. The most common is "AddFact".

See what happens when you name the method "LogOn". The generated code gets confused. This is a limitation of the T4 template. It will likely be fixed in a future update.

Now you can refactor the test methods in LogOnTest to call LogOnUser. In most cases, you'll be able to delete the extraneous "new User("alan1")".

You might be concerned that the LogOnUser method is creating a new user for every call. Write a unit test to verify that it in fact does not.
public void UserIsIdentifiedByUserName()
    Machine machine = _community.AddFact(new Machine());
    LogOn logOn1 = machine.LogOnUser("alan1");
    LogOn logOn2 = machine.LogOnUser("alan1");

    Assert.AreSame(logOn1.User, logOn2.User);
Remember that a fact is identified by its key fields. There can be only one User with the userName "alan1". When you try to create a second one, you simply get back the first.

Next: Lesson 2b: View model

Last edited May 15, 2011 at 4:30 AM by MichaelLPerry1971, version 3


No comments yet.