Tuesday, July 27, 2010

C# Tip - 7/26/2010

Make use of declarative programming when able to (use judiciously).  It will save time and allow for a clearer representation of your logic.

What is declarative programing?  It's when you define the behavior of the class using declarations instead of writing code.

Example:
[WebMethod]
public string HelloWorld()
{
  return "Hello World";
}

[WebMethod] <<< declarative programming

Another example is lambdas.  In the following example, retrieve all records that begin with "test":




            List lis = new List() { "test", "tests","unit","load" };
            List filteredList = lis.Where(l => l.StartsWith("test")).ToList();


Imperative example would be:

            List filteredList2 = new List();
            foreach (string list in lis)
                if (list.StartsWith("test"))
                    filteredList2.Add(list);


Monday, July 26, 2010

C# Tip - 7/25/2010

I am falling in love with events.

Events are implemented via delegates and are used for objects that communicate with multiple clients when a particular action occurs.

Scenario:  there's a soccer game between England and Mexico.  Both countries need to be informed when a goal was scored. 

Step 1: create a class for goal event data.

public class GoalEventArgs : EventArgs

{
  public readonly string Country;
  public readonly string Player;
  public readonly int minute;

  public GoalEventArgs(string country, string player, int minute)
  {
    this.Country = country;
    this.Player = player;
    this.minute = minute;
  }
}

Step 2: create a delegate for the event handler.
 
public delegate void AddGoalEventHandler(object sender, GoalEventArgs e);


Step 3: create the game class that will handle the event (make it static since only one game can be played at a time).

class Game
{
  public event AddGoalEventHandler GoalEventHandler;
  private static Game _instance = null;
  static Game()
  {
    _instance = new Game();
  }

  private Game() { }

  public static Game Singleton
  {
    get
    {
      return _instance;
    }
  }

  public void GoalScored(string country, string player, int minute)
  {
    AddGoalEventHandler g = GoalEventHandler;
    if (g != null)
      g(null, new GoalEventArgs(country, player, minute));
  }
}

Step 4: create a class for the Mexicans.
 
class Mexico
{
  private static Game game;

  public Mexico(Game g)
  {
    game = g;
    game.GoalEventHandler += new AddGoalEventHandler(game_GoalEventHandler);
  }
 
  void game_GoalEventHandler(object sender, GoalEventArgs e)
  {
    if (e.Country.ToUpper().Equals("ENGLAND"))
      Console.WriteLine("Ohh NO!!! ENGLAND JUST SCORED!!! That bastardo " + e.Player + " scored on minute " + e.minute.ToString());
    else
      Console.WriteLine("GOOOOAAAAALLLL!! VIVA MEXICO!!! " + e.Player + " has done it once again on minute " + e.minute.ToString());
  }
}

Step 5: create a class for the English.

class England
{
  private static Game game;

  public England(Game g)
  {
    game = g;
    game.GoalEventHandler += new AddGoalEventHandler(game_GoalEventHandler);
  }

  void game_GoalEventHandler(object sender, GoalEventArgs e)
  {
    if (e.Country.ToUpper().Equals("ENGLAND"))
      Console.WriteLine("ENGLAND JUST SCORED!!! That hero" + e.Player + " scored on minute " + e.minute.ToString());
    else
      Console.WriteLine("NOOOOO!!! " + e.Player + " has done the unthinkable and scored on minute " + e.minute.ToString());
  }
}

To test, add the following to your main method:

Game g = Game.Singleton;

Mexico mexico = new Mexico(g);
England england = new England(g);
g.GoalScored("england", "owen", 15);
g.GoalScored("mexico", "hernandez", 25);

Your console output will be the following after line 4 gets executed:
Your console output will be the following after line 5 gets executed:

As you can see, the possibilities with events are limitless!

Sunday, July 25, 2010

C# tip 7/25/2010

Implement interfaces versus overriding functions:

 
interface IBase
{
  void method();
}

 
class Base : IBase
{
  public void method()
  {
    Console.WriteLine("base implementation of method()");
  }
}

 
Console.WriteLine("first implementation:");
Console.WriteLine("call base");
Base b = new Base();
b.method();
Console.WriteLine("call ibase");
IBase i = b;
i.method();

 
This yields:
 
So far so good.  But what if you wanted to override the base method?

adding a new class throws a compiler error(class is below):

class Derived : Base
{
  public void method()
  {
    Console.WriteLine("derived implementation of method()");
  }
}

 
The error (actually a warning but you should treat all warnings as errors), is the following:

Error 1 Warning as Error: 'TipTester.Derived.method()' hides inherited member 'TipTester.Base.method()'. Use the new keyword if hiding was intended.


Solution is to add the new keyword to the derived method.
public new void method()

{
  Console.WriteLine("derived implementation of method()");
}

 
Modifying the main method to read the following:
Console.WriteLine("first implementation:");

Console.WriteLine("call derived");
Derived d = new Derived();
d.method();
Console.WriteLine("call base");
Base b = d;
b.method();
Console.WriteLine("call ibase");
IBase i = d;
i.method();
 

Yields the following:

Problem:  when calling the derived method directly, the right method is called; however, when casting the derived class to the base class or to the interface, the base class implementation is called.  This is because the class is not really inherited.

Solution:

1. For the interface: make the derived class implement the interface directly (this is going to get clumsy fast).  This solution also does not fix the base class problem.

2, Make the base class method virtual and the derived method override the base method.  This implementation fixes all the inheritance issues.  The new implementation of base and derived methods are the following:

                   public virtual void method()

                   {
                     Console.WriteLine("base implementation of method()");
                   }

 

                   public override void method()
                   {
                     Console.WriteLine("derivedbase implementation of method()");
                   } 

3. Best implementation, however, would be to make the base method abstract and force the derived methods to implement it. This might not be optimal for those situations where you might not want to implement the abstract method every time.

Thursday, July 22, 2010

Stock Update

Generated about 20 algorithms will results not faring as well as I had hoped.  Going in a different direction now (probably should have been going in that direction initially):
- Time Series Analysis
- Neural Networks.

Saturday, July 17, 2010

Front end

Stock application front end.  Added the tooltip and legend.  Perfect for comparing algorithms per stock symbol.

Tuesday, July 13, 2010

C# tip - 7/13/2010

This is one of the most critical tips:
- Prefer coding against interfaces and not abstract classes.

Reasons:

  • A way to design by contract.  This way developers will know exactly what the need to implement and consume.
  • A way to reuse code.  An object can implement a couple interfaces and the client can call any one of those interfaces to implement that object.
Example 1:

public interface IContact
{
  String name();
  String phoneNumber();
  int id();
}

public class Employee implements IContact
{
  private String name;
  private String phoneNumber;
  private int id;
  public String name(){ return this.name;}
  public String phoneNumber() {return this.phoneNumber}
  public int id() {return this.id;}
  public Employee(id) {this.id = id;}
  public Employee(id,name,phoneNumber)
  {
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
  }

  public void DoSomeStuffOnEmployee() {...}
}


public class Employer implements IContact
{
  private String name;
  private String phoneNumber;
  private int id;
  public String name(){ return this.name;}
  public String phoneNumber() {return this.phoneNumber}
  public int id() {return this.id;}
  public Employer(id) {this.id = id;}
  public Employer(id,name,phoneNumber)
  {
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
  }
  private int ReturnSomeValue() {...}
  public void DoSomeStuffOnEmployer() {...}
}

public class SomeImplementationClass
{
  public static void DoCrap(IContact contact)
  {
    String name = contact.name();
    String id = contact.id();
  }
}

to call stuff (SHOWS CODE REUSE and DESIGN BY CONTRACT):
public static void main(String[] args)
{
   SomeImplementationClass.DoCrap(new Employee(1));
   SomeImplementationClass.DoCrap(new Employer(5));
   
}
============================
Example 2.

public interface IContact
{
  String name();
  String phoneNumber();
  int id();
}

public interface ICompany
{
  String placeOfWork();
  String address();
}

public class BasePerson implements IContact, ICompany
{
  protected String name;
  protected String phoneNumber;
  protected int id;
  protected String placeOfWork;
  protected String address;
  public String name(){ return this.name;}
  public String phoneNumber() {return this.phoneNumber}
  public String placeOfWork() {..};
  public String address() {..};
  public int id() {return this.id;}
  private Employee( {}

  //code reuse
  protected void DoSomeStuffOn() {...}
}

public class Employer extends BasePerson
{
  public Employer(id) {this.id = id;}
  public Employer(id,name,phoneNumber)
  {
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
  }
  private int ReturnSomeValue() {...}
  private void DoSomeStuffOnEmployer() 
  {
    this.DoSomeStuffOn();
  }
}

public class Employee extends BasePerson
{
  public Employee(id) {this.id = id;}
  public Employee(id,name,phoneNumber)
  {
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
  }
  private int ReturnSomeValue() {...}
  private void DoSomeStuffOnEmployer()
  {
    this.DoSomeStuffOn();
  }
}

public class SomeImplementationClass
{
  public static void DoCrap(IContact contact)
  {
    String name = contact.name();
    String id = contact.id();
  }
  public static void DoOtherCrap(ICompany contact)
  {
    String placeOfWork= contact.placeOfWork();
  }
}

to call stuff (SHOWS CODE REUSE and DESIGN BY CONTRACT):
public static void main(String[] args)
{
   SomeImplementationClass.DoCrap(new Employee(1));
   SomeImplementationClass.DoOtherCrap(new Employer(5));
   SomeImplementationClass.DoCrap(new Employer(11));
   SomeImplementationClass.DoOtherCrap(new Employee(55));
}

Monday, July 12, 2010

Stock algorithms

Ran stock algorithm comparison for the first 2 algorithms created (listed yesterday):

Algorithm Summary
Algorithm Name - Filter Start End Gain/Loss Currently Invested Total owned and invested
Simple Algorithm 1 - First 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -11.82 0 838.18 [25 buys and 25 sells]
Simple Algorithm 2 - First 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -29.55 93.42 943.45 [5 buys and 4 sells]
Simple Algorithm 1 - Second 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -46.19 760.85 779.81 [30 buys and 28 sells]
Simple Algorithm 2 - Second 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -18.38 0 939.62 [7 buys and 7 sells]
Simple Algorithm 1 - Third 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 109.90 382.40 992.90 [20 buys and 19 sells]
Simple Algorithm 2 - Third 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -81.82 206 855.18 [11 buys and 10 sells]
Simple Algorithm 1 - Fourth 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 74.02 0 954.02 [20 buys and 20 sells]
Simple Algorithm 2 - Fourth 10 stocks 2010-04-27 09:00:00 2010-06-05 16:00:00 -20.96 173 874.04 [18 buys and 17 sells]

Totals for Algorithm 1

  • Gained $125.91
  • Made 95 buys and 92 sells (187 transactions worth $561)
  • Total lost was $435.09
Totals for Algorithm 2
  • Lost $150.71
  • Made 41 buys and 38 sells (79 transactions worth $237)
  • Total lost was $387.71
Summary is that algorithm one made a lot more money (actually made money) but the amount of transactions to get to this point ended up way offsetting any profit.  Algorithm two lost money, but due to making twice as few transactions, the total amount of money lost is lower.

Lesson learned: optimized algorithm one to cut down on the amount of transactions.  Algorithm two seems to be a lost cause.

Sunday, July 11, 2010

Algorithms - Implementation and Testing

Simple Algorithm
  • If for the past 1/2 hour, the # of pluses is greater than minuses + 10, the last price is greater than the first price, and the date this stock was sold is not the same day as today ==> buy
  • If a different day and if the number of pluses is less than minuses and the last price is less than the first price ==> sell

Simple Algorithm 2
  • If the last one hour of stock date, pluses > minuses ==> buy
  • If the next day, minuses > pluses ==> sell
 Testing
  • JUNIT tests with a set of 10 stocks per month.  The end result is printed as the aggregate gainLoss and compared to other Algorithms for the same stocks.

Business Layer

Business Layer has the following projects:
  • Business.Workflow - Entry path to the layer.  This is where all of the workflows are designed.
    • AlgorithmWorkflow
      • RetrieveAllAlgorithms
      • RetrieveAlgorithmByName(String algorithmName)
      • ExecuteAlgorithm(Timestamp startTime, Timestamp endTime, List symbolList, int algorithmId, float availableBalance)
  • Business.Helpers - Static classes that perform certain operations
    • CalculateNumberOfSharesToBuy(StockHistoryArchive stock, float availableBalance)
  • Business.Helpers.Algorithms - All algorithms defined here
    • DimasTraderAlgorithm
      • CheckToBuy(StockHistoryArchive stock, int algorithmId, float availableBalance, Database database)
      • CheckToSell(StockHistoryArchive stock, BoughtStock boughtStock, int algorithmId, float availableBalance, Database database)
  • Business.Objects - Currently not implemented but am thinking this is where the business entities would reside
  • Business.Adapters - May be renamed to entity translators.  This is where the translation between business objects to data access objects.

Couple things that need refactored:
  • Currently, I did not implemented interface implementation between the business layer and the data access layer.  May be required to be redesigned.
  • May need to implement business entities.
  • May need to implement translation logic, which would be the dependency injection layer itself.

Saturday, July 10, 2010

Data Access Layer and unit testing

Finally completed.

Next up, the Business Layer and the Mail API.  More information on them coming later.

Unit testing is done with JUnit.  Code Coverage and unit tests listed below.




Sunday, July 4, 2010

Code tip - 7/4/2010

Well, I cannot remote into my home PC tonight so I decided to add another tip.  Something that is taught from the very beginning of software design; however, something that I see broken every day in all projects I have worked on:

Code against interfaces and not concrete classes:

  • Interfaces give an ability to design by contract
  • Interfaces give an ability to reuse code from unrelated types (as long as they implement the same interface)
  • Interfaces are easier for developers to implement instead of deriving from base class
Plus for abstract classes:
  • Any method that's added is automatically implemented by derived classes
  • Any added method does not have to be implemented by derived class, unlike an interface

C# tip - 7/3/2010 (2)

This tip goes along with the previous tip for today:  implement Dispose pattern with those object that need resource cleanup.


  1. Root base class implements IDisposable interface
    • Add a finalizer as a defensive mechanism (this will keep resources longer in memory if Dispose is not called but will dispose of resources in time)
    • Both Dispose and finalizer should be virtual methods for derived classes to override
  2. Derived class must have a finalizer as a defensive mechanism (this will keep resources longer in memory if Dispose is not called but will dispose of resources in time)
  3. Implement IDisposable, which requires you to implement Dispose method, which does the following:
    1. frees unmanaged resources
    2. frees all managed resources
    3. sets flag indicating that the object has been disposed
    4. suppress finalization
    5. call base class to clean up all of its resources
      • this can be done by implementing virtual Dispose(bool) method that allows factoring out common tasks between Dispose and finalize and call the base classes
    6. only release resources in Dispose and finalize methods.  Do not do anything else in those methods since you may unintentionally "revive" the object again, preventing it from being garbage collected.
    class Base : IDisposable
    {
        private bool _alreadyDisposed = false;


        ~Base()
        {
            Dispose(false);
        }


        public int Age { get; set; }


        #region IDisposable Members


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }


        protected virtual void Dispose(bool isDisposing)
        {
            if (_alreadyDisposed)
                return;
            if (isDisposing)
            {
                //free managed resources
            }
            //free unmanaged resources
            _alreadyDisposed = true;
        }


        #endregion
    }



    class Derived :Base
    {
        private bool _disposed = false;
        public int Time { get; set; }
        public void PrintStuff()
        {
            Console.WriteLine(this.GetType());
        }




        ~Derived()
        {
            Dispose(false);
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (_disposed)
                return;
            if (isDisposing)
            {
                //free managed resources
            }
            //free unmanaged resources
            //call base class here
            base.Dispose(isDisposing);
            _disposed = true;
        }


    }

Saturday, July 3, 2010

C# tip - 7/3/2010 (1)

Had a weekend full of fun and relaxation and also read some cool tips about managing system resources in C#.


  1. For types that implement IDisposable, use the using.
  2. For rest of the types (think about implementing IDisposable for them if they are custom), use try/finally and call Dispose method in the finally block.
  3. Difference between calling the Close method for those types that implement it and Dispose is that the Close method does not call GC.SuppressFinalize() and therefore leaves the objects in memory longer (until finalizers are called).  Use Dispose when you can.
  4. Minimize garbage collection with the following:
    • if you are creating the same object with the same settings in a method frequently, see if you can create an attribute (member variable) and initialize it with a constructor instead (do not forget to implement IDisposable on the class and dispose of this variable when the object is destroyed).
before:
void TestMethod()
{
  using(MyObject obj = new MyObject(CONST_ONE))
  {
    DoStuff(obj);
  }
after:
private readonly MyObject obj = new MyObject(CONST_ONE);
void TestMethod()
{
  DoStuff(obj);
}
    • see if you can create static member variable as well.  
class MyObject
{
  private static MyObject _objOne;
  public static MyObject ObjOne 
  {
    get
    {
      if(_objOne == null) _objOne = new MyObject(CONST_ONE);
        return _objOne
    }
  }
  private static MyObject _objTwo;
  public static MyObject ObjTwo 
  {
    get
    {
      if(_objTwo == null) _objTwo = new MyObject(CONST_TWO);
        return _objTwo
    }
  }
}
before:
void TestMethod()
{
  using(MyObject obj = new MyObject(CONST_ONE))
  {
    DoStuff(obj);
  }
after:
void TestMethod()
{
  DoStuff(MyObject.ObjOne);
}
    • see if you can implement a Builder pattern on one of these member variable objects

Labels