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

Tuesday, June 29, 2010

Data Access Layer

Data Access Layer created. Repository pattern:


Database objects:
  • Algorithm (immutable)
  • BoughtStock (immutable)
  • PlusMinus (enum)
  • CurrentStock (immutable)
  • StockHistory (immutable)
  • StockHistoryArchive (immutable)
  • StockTransaction (immutable)
  • Database (immutable)

Database repositories:
  • IRepository interface
  • Repository
    • Find
    • FindComplex
    • FindAll
    • FindAllComplex
    • Insert
    • InsertComplex
    • Save
    • Delete
  • IStatementFactory interface
Table specific repositories:
  • TableDeleteFactory implements IStatementFactory
  • TableInsertFactory implements IStatementFactory
  • TableSelectionFactory implements IStatementFactory
  • TableRepository extends Repository

Database factories:

  • IReaderFactory
    • ProcessList for retrieving lists
    • ProcessRecord for retrieving one record
  • TableFactory implements IReaderFactory
Example:
    public Algorithm FindById(int id, Database database)
    {
        Algorithm algorithm = new Algorithm();
        algorithm.setId(id);
        return Find(algorithm, new AlgorithmSelectionFactory(), new AlgorithmFactory(), database);
    }

C# tip - 6/29/2010

Initializing private variables in a class is good.  This practice will allow the object to never have nulls and not having to deal with NullPointerExceptions.  However, there are three reasons why you should not initialize the attributes:

  • initializing VALUE TYPES to NULL or 0 is redundant since these types are initialized to 0 at creation time.  
    • Int32 i; <== already initialized to 0.  
  • multiple initializations for the same object
public class Test
{
  private ArrayList t = new ArrayList();
  public Test(){}
  public Test(ArrayList l)
  {
    t = l;
  }
}
    • in this scenario, the ArrayList's initialization in the attribute is overriden by the initialization in the second constructor.  It's like initializing the same variable twice.  The following example is a better solution:
public class Test
{
  private ArrayList t;
  public Test()
  {
    Test(new ArrayList());
  }
  public Test(ArrayList l)
  {
    t = l;
  }
}
  • exception handling is impossible on attribute initialization.  If exception handling is necessary, initialize the attribute in the constructor.
When initially instantiating a type, here's the order of operations:
  1. Static variable storage is set to 0
  2. Static variable initializers execute
  3. Static constructors for the base class execute
  4. Static constructor executes
  5. Instance variable is set to 0
  6. Instance variable is initialized
  7. Base class instance constructors execute (for a specific constructor overload)
  8. Instance constructor executes

Monday, June 28, 2010

C# tip - 6/28/2010 (last one for today)

Use foreach loops.

Here's why:

  • efficiency => the compiler picks the most efficient loop implementation depending on the data collection being looped
  • ease of use => it's very simple to change the collection instantiation without changing the foreach loop.
private Square[] _board  = new Square[8];
foreach(Square _sq in _board);
===============================

private Square[] _board  = new Square[10];
foreach(Square _sq in _board);//will work without the need to change anything
===============================
private Square[,] _board = new Square[10,10];
foreach(Square _sq in _board);//will still work without the need to change anything
===============================
private Square[,,] _board = new Square[10,10,10];
foreach(Square _sq in _board);//will still work without the need to change anything



C# tip - 6/28/2010 (making up for the weekend)

Differences between four equality methods/operations:

  • public static bool ReferenceEquals(object, object)
    • returns true if objects refer to the same object.  It does not care about the object contents
Obj obj = new Obj();
Object.ReferenceEquals(obj,obj) returns true
Obj obj2 = obj;
Object.ReferenceEquals(obj,obj2) returns true
Obj obj3 = new Obj();
Object.ReferenceEquals(obj,obj3) returns false
Int32 i = 1;
Object.ReferenceEquals(i,i) returns false
Int32 i2 = i;
Object.ReferenceEquals(i,i2) returns false

  • public static bool Equals(object, object)
    • returns true if the objects are equal at runtime.  It uses the instance Equals methods to compare the objects if they are identical.


Obj obj = new Obj();
Object.Equals(obj,obj) returns true
Obj obj2 = obj;
Object.Equals(obj,obj2) returns true
Obj obj3 = new Obj();
Object.Equals(obj,obj3) returns false
Int32 i = 1;
Object.Equals(i,i) returns true
Int32 i2 = i;
Object.Equals(i,i2) returns true

  • public virtual bool Equals(object)
    • compares the object calling the method with the object passed in the method.  This is an overridable method.  The reason for that is because the default Equals method has to check for EVERY type possible since it doesn't know which type the object is until runtime.  One example is the ValueType, which is the base for all value types.  It will have to use reflection at runtime to get the runtime type of the object.  To improve the performance of this method, override it for your concrete class and only check for those conditions that you deem necessary.
    • To override the method properly, use the following pattern:
      1. check that the object parameter is not null (return false)
      2. check identity with ReferenceEquals method (return true if it is)
      3. check that the types are the same (return false)
      4. compare the objects' contents
    • do NOT throw exceptions out of this method
    • do NOT use as operation since that will incorrectly convert the object of subtype into a base type.
      • example: 
        • parameterObject is type BaseType, which SubyType extends
        • SubType test = parameterObject as SubType will always return NULL
        • parameterObject2 is type SubType
        • BaseType test = parameterObject2 as BaseType will return the object
      • use object.getType() instead
    • write the override for GetHashCode as well if this is done
  • public static bool operator ==(Class left, Class right)
    • override when dealing with value types


Stock code generator

Was able to successfully create a code generator in Ruby.  Currently, the generator creates 4 types of files:
- .JAVA files for each object in the following format:
package ;

public class {
  private _;

  public get(){
    return this._;
  }

  public void set( value){
    this._ = value;
  }
}

Due to the fact that some of the object will have to be immutable, some keys will have to be added to the code generator to validate that the correct object type is being generated.

- .SQL file for the DB creation
- .JAVA files for the repositories.
- ERD diagram view Ruby tK.

It has been a struggle learning Ruby.  If I had to go back and recreate all of my code, I would probably pick a language I already know (JAVA, C#, PHP, etc.) and use that language for my generator.  That's not to say that Ruby is a bad language; however, I am more of a traditional learner and "learning by doing" did not work out for me too well.

Now, onto developing the framework for the app, and starting tomorrow, starting my "one algorithm per day" development.

C# tip - 6/28/2010

Consider using immutable types when creating objects.

If your object is only considered to be a storage place where every set of data is linked to the rest of the object, consider not only using Struct, but also making the entire object immutable (and maybe even using static factory methods to populate the object itself).

An example would be a stock information.  The stock object would have NAME and SYMBOL as its attributes.  If you change NAME, you will have to also change the SYMBOL.  For example:

Stock stock = new Stock("MSFT", "Microsoft Corporation");
stock.setSymbol("GOOG");
- now, the stock object has the SYMBOL as GOOG and NAME as Microsoft Corporation, which is obviously wrong.

The best way to implement this is:

  • create the object as a struct
  • make all private attribute be readonly
  • implement only private setters and public getters
  • consider implementing static factory methods.
  • consider implementing the Builder pattern to create these objects if you have more than a couple attributes to set
Issues arising from using immutable types are the same that are listed in the Builder Pattern tip.

Thursday, June 24, 2010

C# tip - 6/24/2010

Value types versus Reference types:

  • structs
    • created on the stack
    • not polymorphic
    • memory efficient
    • not inheritable
    • used mostly for data storage
  • classes
    • created references on the heap
    • polymorphic
    • inheritable
    • define behavior
Use structs for simple objects that are just data containers.
Use classes for any objects that perform work.

Tuesday, June 22, 2010

Data Model

The below XML is a representation for the Data Model for the Stock application.  This XML will be used to create the following:

  • Data Access Objects
  • Repositories
  • ERD (for documentation purposes)
  • Create/update databases themselves
<?xml version="1.0" encoding="UTF-8"?>
<database name="Stock">
  <table name="current_stock" engine="Innodb">
    <column>
      <name>id</name>
      <type>int</type>
      <isNull>false</isNull>
      <key>PRIMARY</key>
      <autoIncrement>true</autoIncrement>
    </column>
    <column>
      <name>stock_symbol</name>
      <type>varchar(5)</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>last_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>ask_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>bid_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>change_from_close</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>open_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>close_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>change_from_previous</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>stock_timestamp</name>
      <type>datetime</type>
      <isNull>true</isNull>
    </column>
  </table>
  <table name="stock_history" engine="Innodb">
    <column>
      <name>id</name>
      <type>bigint</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>stock_symbol</name>
      <type>varchar(5)</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>last_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>plus_minus</name>
      <type>enum</type>
      <values>
        <value>PLUS</value>
        <value>MINUS</value>
        <value>SAME</value>
      </values>
      <isNull>true</isNull>
    </column>
    <column>
      <name>percent_change</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>date_inserted</name>
      <type>timestamp</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>stock_timestamp</name>
      <type>timestamp</type>
      <isNull>false</isNull>
      <default>CURRENT_TIMESTAMP</default>
    </column>
  </table>
  <table name="stock_history_archive" engine="Innodb">
    <column>
      <name>id</name>
      <type>bigint</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>stock_symbol</name>
      <type>varchar(5)</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>last_price</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>plus_minus</name>
      <type>enum</type>
      <values>
        <value>PLUS</value>
        <value>MINUS</value>
        <value>SAME</value>
      </values>
      <isNull>true</isNull>
    </column>
    <column>
      <name>percent_change</name>
      <type>float</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>date_inserted</name>
      <type>timestamp</type>
      <isNull>true</isNull>
    </column>
    <column>
      <name>stock_timestamp</name>
      <type>timestamp</type>
      <isNull>false</isNull>
      <default>CURRENT_TIMESTAMP</default>
    </column>
  </table>
  <table name="stock_transaction" engine="Innodb">
    <column>
      <name>id</name>
      <type>bigint</type>
      <isNull>false</isNull>
      <key>PRIMARY</key>
      <autoIncrement>true</autoIncrement>
    </column>
    <column>
      <name>stock_symbol</name>
      <type>varchar(5)</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>number_of_shares</name>
      <type>smallint</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>bought_price</name>
      <type>float</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>sold_price</name>
      <type>float</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>investment</name>
      <type>float</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>gain_loss</name>
      <type>float</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>bought_stock_timestamp</name>
      <type>timestamp</type>
      <isNull>false</isNull>
      <default>CURRENT_TIMESTAMP</default>
    </column>
    <column>
      <name>sold_stock_timestamp</name>
      <type>timestamp</type>
      <isNull>false</isNull>
      <default>CURRENT_TIMESTAMP</default>
    </column>
    <column>
      <name>algorithm_id</name>
      <type>tinyint</type>
      <isNull>false</isNull>
    </column>
  </table>
  <table name="bought_stock" engine="Innodb">
    <column>
      <name>id</name>
      <type>bigint</type>
      <isNull>false</isNull>
      <key>PRIMARY</key>
      <autoIncrement>true</autoIncrement>
    </column>
    <column>
      <name>stock_symbol</name>
      <type>varchar(5)</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>number_of_shares</name>
      <type>smallint</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>price_bought</name>
      <type>float</type>
      <isNull>false</isNull>
    </column>
    <column>
      <name>stock_timestamp</name>
      <type>timestamp</type>
      <isNull>false</isNull>
      <default>CURRENT_TIMESTAMP</default>
    </column>
    <column>
      <name>algorithm_id</name>
      <type>tinyint</type>
      <isNull>true</isNull>
    </column>
  </table>
</database>

Stock application frontend

The user interface for this application is fairly straight forward.  I want to see the following things initially:

  • stock history
    • include ranges to see certain sections
    • way to graph the history
  • way to execute algorithms
    • ability to select a set of stocks
    • ability to select date ranges
    • ability to select an algorithm
  • way to view stock summary
    • show for each algorithm:
      • price bought and sold
      • date bought and sold
      • initial investment
      • gain/loss
The technology used will be JSP with JQuery (Flot and DataTables plugins).  Each of the main bullets is its own tab:


C# tip - 6/22/2010

Advantages and disadvantages of is, as, and cast operations.

is - used to checked whether an object is a specific type
Object t;
if(t is SomeType){...}
  • Advantages
    • checks an object without an overhead of a try/catch block
  • Disadvantages
    • doesn't actually cast anything
as - used to cast reference objects from one type to another
Object t;
t as SomeType
if(t != null) {...}
  • Advantages
    • casts an object without an overhead of a try/catch block (returns null if cast fails)
  • Disadvantages
    • cannot be used on value types
cast - used to cast values from one type to another
  • Advantages
    • can be used to cast any types of values, whether reference or value.  Used in foreach loops for that reason (since collections could have either type)
    • ability to fail out of the class when casting an unexpected object is attempted 
  • Disadvantages
    • try/catch overhead
    • may force to insert business logic into the catch block

Monday, June 21, 2010

C# tip - 6/21/2010

Couldn't wait until tomorrow for this one.  Difference between const and readonly.

readonly is resolved at run time.  const is resolved at compile time.  Use readonly when you don't know the value until you have to use it.  Use const when the value is known and will never change throughout the lifecycle of the system.

Examples:
public class ConstExample
{
  public const int example = 1;
  public const String anotherExample = 2; //will fail compilation
}


System.out.println(ConstExample.example);
System.out.println(ConstExample.anotherExample);


public class ReadonlyExample
{
  public readonly int example = 1;
  public readonly int anotherExample;


  public ReadonlyExample(String value)
  {
    anotherExample = Int.parse(value);//if value is not an int, this will not throw an error until runtime
  }
}


System.out.println(ReadonlyExample.example);//prints 1

System.out.println(new ReadonlyExample("x").anotherExample);//won't fail until compile time
System.out.println(new ReadonlyExample("5").anotherExample);//will run fine


Advantages and disadvantages are very clear:

  • For readonly
    • Value can be set at runtime so a developer does not have to worry about knowing the real value ahead of time
    • Can be used for mutable objects
    • More flexibility
    • Can be have different values for each instantiation of the class
    • const can only be used for int and String types
  • For const
    • Performance
    • Maintenance (much easier to make a mistake with readonly if the attribute gets an unexpected value set at runtime)
    • Must be used with enums

Stock algorithm generation using DSL

Best way that I could figure out to create algorithms would be to have a utility where I specify the algorithm in a simple language, and upon running this query, it will end up being compiled as part of the algorithm project.

The simple example would look like the following:

CREATE ALGORITHM SimpleAlgorithm
LOAD STOCK HISTORIES FOR stock_symbol FROM dateOne TO dateTwo
IF stock_symbol IS NOT OWNED AND SOLD DATE IS NOT THE SAME AS TODAY
  LOAD STOCK HISTORIES FOR stock_symbol LAST 60 plus_minus ENTRIES
  CHECK 
   IF SUM OF stock_plus IS GREATER THAN SUM OF stock_minus
     AND LAST price IS GREATER THAN FIRST price
     BUY STOCK
     ALERT USER
IF stock_symbol IS OWNED AND BOUGHT DATE IS NOT THE SAME AS TODAY
  RETRIEVE LAST 60 ENTRIES FOR stock_symbol
  CHECK 
   IF SUM OF stock_minus IS GREATER THAN SUM OF stock_plus
     AND LAST price IS LESS THAN FIRST price
     SELL STOCK
     ALERT USER

The above code will generate a Java class that will extend PredictiveAlgorithm abstract class.  The generation will be implemented in Ruby and the code will be posted sometime next month.  This implementation makes it a lot easier to generate many algorithm and not have to worry about Java syntax.  The 17 lines above would generate quite a few lines of OO code.

Code Tip - 6/21/2010

If you want to create an immutable object but want to make sure that you don't have to create a different constructor for every combination of parameters, a consistent state, and readability, use the Builder pattern.

For an example, in my Stock application, I will have a Stock object that will not change throughout algorithm run.  It will always have the same name, description, dates, current price, and symbol.  The Stock object will always have a symbol but may not have some or all of the other parameters (or some combination of).  Here's the builder pattern implementation to create this object:

public class Stock
{
  private final int id;
  private final String stockName;
  private final String description;
  private final String symbol;
  private final float price;
  private final Date date;


  public static class StockBuilder
  {
    private final int id;
    private final String symbol;



    private String stockName;
    private String description;
    private float price;
    private Date date;



    public StockBuilder(int id, String symbol)
    {
      this.id = id;
      this.symbol = symbol;
    }


    public StockBuilder StockName(String name)
    {
      this.stockName = name;
      return this;
    }





    public StockBuilder Description(String description)
    {
      this.description= description;


      return this;
    }





    public StockBuilder Price(float price)
    {
      this.price= price;


      return this;
    }


    public StockBuilder StockName(String name)
    {
      this.stockName = name;
      return this;
    }


    public StockBuilder StockDate(Date date)
    {
      this.date= date;
      return this;
    }

    public StockBuilder Build()
    {
      return new Stock(this);
    }
  }


  private Stock(StockBuilder builder)
  {



    this.id = builder.id;
    this.symbol = builder.symbol;


    this.stockName = builder.stockName;
    this.description = builder.description;
    this.price = builder.price;
    this.date = builder.date;



  }


And now to initialize the Stock object:


Stock stock = new Stock.StockBuilder(5,"GOOG").StockName("Google").Price(500).Build();


Stock nextStock = new Stock.StockBuilder(5,"MSFT").Price(70.5).Description("Microsoft corporation description").Build();

Labels