in

 

Blog of Posting +1

Granting bonuses to saving throws vs inanity
  • Procedural LOLCoding

    Recently I had the great pleasure to be introduced to LOLCode. It's an idiomatic syntax based on a series of images found at LOLCat and ICanHasCheezeBurger. In any event, currently LOLCode syntax is at specification 1.2. There are several compilers including a LOLCode.NET compiler. I gave it a try, but as of the time of this posting, it didn't seem to be able to handle if statements too well.Currently in specification 1.2, everything is still procedural, though there are proposals for OOP LOLCode in the proposed 1.3 specification. I thought for fun I'd post up some LOLCode snippets from a tic tac toe program I wrote in LOLCode to see if I could get it to work.

    HOW DUZ I CheckForWinningMatch YR index1 AN YR index2 AN YR index3 AN YR array

                   BOTH SAEM array!!index1 AN array!!index2, O RLY?
                           YA RLY
                                   BOTH SAEM array!!index1 AN array!!index3, O RLY?
                                           YA RLY
                                                   BOTH SAEM array!!index1 AN "X", O RLY?
                                                           YA RLY
                                                                   FOUND YR WIN

                                                           MEBBE BOTH SAEM array!!index1 AN "O"
                                                                   FOUND YR WIN
                                                           OIC
                                           OIC
                           OIC


                   FOUND YR FAIL

           IF U SAY SO

    The above code snippet checks a one dimensional array (I don't think it supports multidimensional arrays yet, though I could be wrong) for combinations of the letters X and O for any sort of winning combination. Some of LOLCode syntax includes:
    • Functions declarations in LOLCode start with "HOW DUZ I" and end with "IF YOU SAY SO".
    • IF statements are equivilent to "O RLY?" and and equivilency is expressed as "BOTH SAEM".
    • "YA RLY" indicates a positive match, and "NO WAI" indicates a negative match on the condition.
    • "MEBBE" corresponds to "else if"
    • If statements are closed with "OIC" (oh, I see)
    • Return statements are expressed as either "FOUND YR", followed by a value, or as "GTFO" which returns a void
    • The !! operator acts as an indexer, though my understanding is that in OOP LOLCode it may be used to access properties and methods as well
    • The TROOF data type (boolean), is expressed as either WIN (true) and FAIL (false)\
    • Other data types include BUKKIT (array), NOOB (null), NUMBAR (float), NUMBR (int), YARN (string)
    • The SMOOSH keyword handles string concatenation
    • Programs start with HAI and end with KTHXBYE

    Here is my "main" method's code.

    HAI

           I HAS A array ITZ A BUKKIT
           I HAS A char ITZ "X"

           DrawTicTacToe array
           

           IM IN YR LOOP

                   BOTH SAEM
    GetWinningCombination array AN WIN, O RLY?
                   YA RLY
                           VISIBLE SMOOSH char " is winnar!!"
                           
    GTFO
                   OIC

                   GetUserInput char array

                   DrawTicTacToe array

                   
    BOTH SAEM char AN "X", O RLY?
                           YA RLY
                                   char R "O"
                           NO WAI
                                   char R "X"
                   OIC

           IM OUTTA YR LOOP


    KTHXBYE

    I grabbed a java compiler from the LOLCode website that appears to have support for the proposed 1.3 specs.

    OOP LOLCode, here I come!

     
  • Aspect-oriented approaches to software development

    A while back, I wrote a little post alluding to ways to reuse certain processes that are duplicated in code throughout any given system (event logging, in my example). In this post, I'd like to show you how I implemented a possible solution using aspect oriented programming.

    What is Aspect Oriented Programming?

    Basically, the idea that there are types of processes that occur in multiple places in a system, commonly referred to as "cross-cutting concerns". Aspects are implementations of these concerns, written so that they can be reused in a system. In the logging example, the need to log exceptions is a concern, and the aspect is a piece of code that fulfills this need. The idea behind aspect oriented programming is to identify these cross-cutting concerns, create aspects to manage them, and introduce their behaviors into the points of a system that their behavior needs to govern. In my example, I will accomplish this by creating some custom attributes and aspects as well as decorating classes and methods. As these objects are instantiated and their methods are invoked, I will be intercepting messages and injecting the behavior defined by my aspect.

    A Consumer's View

    Here is my simplistic implementation: 

    public class HelloWorld
    {
        
    public void SendGreeting()
         {
               
    Messenger messenger = new Messenger();
                messenger.SendMessage(
    "Hello World!");
         }
    }

    Running this code produces the following "logged" output:

     

    Attempting connection...
    Logging Exception: A problem occurred!

     

    All right, so how does this work? Here's my messenger class.

    [Loggable]
    public class Messenger : ContextBoundObject
    {
         [
    LogException]
        
    public void SendMessage(string message)
         {
             
    Console.WriteLine("Attempting Connection...");
             
    throw new Exception("A problem occurred!");
         }
    }

    First thing you might notice is that it inherits from a class called ContextBoundObject. By inheriting from this class, we will recieve the context needed from the runtime and intercept messages in order to extend the invocation of SendMessage to include the behavior defined by our aspect. Also, there are two different types of attributes being used here... [Loggable] and [LogException].

    [Loggable]

    The [Loggable] attribute is a context attribute used to associate our Aspect into the message chain. Below is the source code.

    [AttributeUsage(AttributeTargets.Class)]
    public class LoggableAttribute : ContextAttribute, IContributeObjectSink
    {
         
    public LoggableAttribute() : base("Loggable") { }

         
    public override void GetPropertiesForNewContext(IConstructionCallMessage msg)
          {
                msg.ContextProperties.Add(
    this);
          }

          public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
          {
               
    return new LogExceptionAspect(nextSink);
          }
    }

    The implementation here is fairly straight-forward. The attribute can only be used with classes and when it is instantiated, it will add itself to the message's context and add our aspect to the message chain for execution. Also, when instantiating LogExceptionAspect, we give it a reference to the next message sink in the chain, allowing us to insert our aspect as a link in the chain.

    [LogException]

    The [LogException] attribute is a simple attribute that houses our logging code, and can only be used on methods.

    [AttributeUsage(AttributeTargets.Method)]
    public class LogExceptionAttribute : Attribute
    {
        
    public void Process(string message)
         {
             
    new EventLogger().LogMessage(message);
         }
    }

    LogExceptionAspect

    The LogExceptionAspect class, which is part of the [Loggable] context attribute's implementation, is a message sink. When the chain of message sinks is being processed, the runtime will get a reference to this class and invoke IMessage.SyncProcessMessage. This function will house code related to our logging process.

    public class LogExceptionAspect : IMessageSink
    {
          
    private readonly IMessageSink nextMessageSink;

          
    public IMessageSink NextSink
           {
               
    get { return this.nextMessageSink; }
           }

           public LogExceptionAspect(IMessageSink nextMessageSink)
           {
               
    this.nextMessageSink = nextMessageSink;
           }

           public IMessage SyncProcessMessage(IMessage msg)
           {
                
    MethodBase method = RemotingServices.GetMethodBaseFromMethodMessage((IMethodMessage)msg);
               
               
    FormatExceptionAttribute formatException = (FormatExceptionAttribute)Attribute.GetCustomAttribute(method, typeof(FormatExceptionAttribute));
                
    LogExceptionAttribute logException = (LogExceptionAttribute)Attribute.GetCustomAttribute(method, typeof(LogExceptionAttribute));
                  ReturnMessage response = (ReturnMessage)this.nextMessageSink.SyncProcessMessage(msg);

                if (response.Exception == null) return response;

                string message = response.Exception.Message;

                if (formatException != null) message = formatException.FormatException(response.Exception);
                if (logException != null) logException.Process(message);

                return response;
          }

          public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
          {
               
    return this.nextMessageSink.AsyncProcessMessage(msg, replySink);
          }
    }

    As you can see, in this aspect, we get a reference to the method and check for possible attributes ([LogException] and [FormatException]) and run the rest of the chain. At this point in execution, exceptions do not get thrown, so there is no need for any try/catch constructs. Simply check the resulting message for exceptions, and if any are detected, format and log the exception if the function has been decorated with attributes directing the aspect to do so.

    As you can see in the above example, I have introduced another attribute called [FormatException]. This is simply to illustrate that multiple attributes can be associated with the aspect and you can decorate your functions as desired with one, both or neither directives for the aspect to adhere to. Here is the definition for [FormatException]:

    public class FormatExceptionAttribute : Attribute
    {
        
    public string FormatException(Exception exception)
         {
            
    return new EventFormatter().FormatException(exception);
         }
    }

    and the definitions for the logger and event formatter:

    public class EventLogger
    {
        
    public void LogMessage(string message)
         {
            
    Console.WriteLine("Logging exception: " + message);
         }
    }

    public class EventFormatter
    {
         
    public string FormatException(Exception exception)
         {
             
    return "Formatted Exception: " + exception.Message;
         }
    }

    If I add [FormatException] in my Messenger class, the output changes to:

    Attempting connection...
    Logging Exception: Formatted Exception: A problem occurred!


    In Closing

    I see some nice benefits and some unfortunate drawbacks to the way .NET handles this. The need to inherit from ContextBoundObject is something I really don't like and causes me to be hesitant in trying to implement something like this. Additionally, it would require a certain level of competancy for anyone that wants to maintain this code. However, this does prevent a lot of try/catch/log exception/throw; code repetition and could be altered to allow one to easily inject whatever sort of logging/formatting mechanisms they want to use, or even actions they want to take based on type of exception. Furthermore, it allows developers to write try/catch statements only in cases where they want to handle exceptions and resolve them, and it allows developers that use it to focus on writing code to accomplish the task at hand instead of writing code (yet again) to log exceptions that arise in the system.
  • What does that function do, really?

    Recently, I had the chance to read a blog by one of my former coworkers on the topic of code duplication and functional programming. I found the ideas there interesting; in many applications that I deal with there are certain repeated processes. For example, functions try a certain statement, catch a possible exception and log the information to the event log. Pretty standard process. So in reading this blog I came to a simple conclusion. There are at least two types of code that are duplicated: Functional Code and Procedural Code (not to be confused with functions and procedures). One of them is often refactored and reused... one of them is not. Take the following code example:

    public class DataManager 
    {

          public
     void SaveData()
          {
                try
                {
                      //Do something
                 }
                 catch(Exception ex)
                 {           
                       EventLogger logger = new EventLogger();
                       logger.LogException(ex);

                 }
           }
    }

    Functional Code

    Functional code is code that accomplishes a certain task. In this example, I have intercepted an exception in the system and I am going to log it to the event log. So I write a class with a method that takes messages in and inserts them into the event log. This code fulfills a function in this system -- it ensures that messages it receives are persisted in the designated medium (the event log, in this case). Duplicate code here is easily refactored into an object that provides an interface to the event log, with methods for managing events and it acts as an application boundary for the system. The segments of code within the try, and within the catch are functional code segments.

    Procedural Code

    Procedural code is code that governs how your functional code is implemented. This code fulfills a process of the system -- it ensures that when an exception occurs, the appropriate piece of functional code is executed. In the above example, this is the code that manages when your event logging class is used -- it is the code that tries a statement, catches some exception, and invokes the logger.  It's something seen repeated in a lot of functions in a lot of applications.

    Reading the above blog, I thought it was a neat way to refactor this into a reusable process. But, I felt that while the procedural code had been abstracted a bit, calls to it would still be scattered through my systems, and I was hoping to remove it from my implementation all together.

    So why is this important? By refactoring functional code into reusable objects, you can change the internal implementation of that object without impacting the rest of your system. But what about the steps your system takes in order to fulfill that function? What if you want to amend that process to do additional steps before logging that exception?

    Often times this sort of code is placed upon the object that is performing the function itself. Let's amend my original example of event logging to include message formatting. In our modified example, the object's behavior is defined as accepting a message, formatting that message, and then logging it. While the formatting of the message is clearly procedural -- it is a step the system takes to prepare for logging -- many people will dump it with functional code. Take for example, the following sample:

    public class EventLogger
    {
          public
    void LogException(Exception exception)
          {
                string 
    message =  new ExceptionFormatter().FormatExceptionMessage(exception);
                this.
    WriteToEventLog(message);
          }
    }

    Alternatively, you could pass the appropriate formatter to the function:

    public class EventLogger
    {
          public void LogException(Exception exception, IExceptionFormatter formatter)
          {
                string 
    message =  formatter.FormatExceptionMessage(exception);
                this.
    WriteToEventLog(message);
          }
    }

    This intially seems to make sense to do. The first example reduces code duplication because the presumption is that all error messages will need to be formatted before being logged. However, from the standpoint of the consumer of this class, one would expect this method to take an exception and send it to the event log. One would not be aware that formatting would be occuring on the message. This design produces unexpected behavior from the standpoint of the consumer and becomes an implicit and non self-documenting aspect of the object. Although it clearly logs messages to the event log, it also has unclear additional behavior. Furthermore, if a developer implements the second sample, the consumer also has to be aware of exception formatting in order to log messages, resulting in a more difficultly consumed interface. One could simply rename the method in either sample to "FormatAndLogMessage", but honestly this addresses the symptom of the problem, and not the problem itself.

    The Seperation of Concerns

    What I'm getting around to is that there is a clear seperation of concerns here. Event Logging should not be concerned with Message Formatting. These are seperate concerns and the functional code to fulfill each concern should be ignorant of the other. This would imply that the procedural code in first sample should somehow be amended in the try/catch to perform message formatting before logging. If logging were performed like this throughout the system, this approach would actually increase code duplication instead of solve it! Furthermore, one would expect a function like SaveData() would simply do as it says -- save the data. However in our above sample, the seperation of concerns is apparently violated by the fact that SaveData() not only saves information, it logs exceptions to the event log!

    Fortunately, there is a way to resolve this issue in a relatively simple manner, reducing procedural code duplication and seperating concerns within our functional code segments while producing a readable, self-documenting interface. This can be accomplished declaratively by use of attributes.

    [Loggable] and [LogException]

    Assume for a moment that the above scenario could be implemented in this fashion:

    [Loggable] 
    public class DataManager 
    {
          [LogException]

          public void SaveData()
          {
                 //Do something
     
         }
    }

    This implementation is a much simpler, more elegant way to address the problem. In this example, there is no procedural code within SaveData(), only functional code. Exception logging has been abstracted away from our codebase and reclassified as a system concern. This is a good thing -- it allows our code to focus purely on the needs of the business instead of having to also manage the needs of the system. In this implementation we have extended the way in which the system is expected to address exceptions during execution declaratively, augmenting the way in which our code executes without affecting the way our code is implemented.

    So what about exception formatting? Using this approach, we should easily be able to extend our design to address this concern as well.

    [Loggable] 
    public class DataManager 
    {
          [FormatException, LogException]

          public void SaveData()
          {
                 //Do something
     
         }
    }

    or, if you prefer to use more than one formatter:

    [Loggable] 
    public class DataManager 
    {
          [FormatException(typeof(ExceptionFormatter)), LogException]

          public void SaveData()
          {
                 //Do something
     
         }
    }

    This allows us to identify both exception message formatting and exception logging as procedural aspects of our system and abstract those concepts away from our functional code declaratively, producing less code to maintain through code reuse and more readable code by focusing our written code on what is important -- the functionality.

    So how useful is this? Fairly useful, in my opinion. It would allow developers to draw clear distinctions declaratively between system needs and business needs. Operations like event logging, operation retrying and using transactions are some easy examples of where this could be implemented to reduce code duplication. The key is knowing when and what types of procedural code make good candidates for this sort of approach.

    In my next post, I will show how the procedural code in our first sample is abstracted into attribute usage and implemented in .NET to produce the final examples, touching on something I came across while trying to figure out how to accomplish this -- Aspect Oriented Programming.

Copyright Los Techies 2007. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems