Sunday, December 07, 2008

Case insensitive List

No you cant create a case insensitive list. However you can do a case insensitive Find in a list, heres how :

List myList = new List();
string colorToTest = "RED";
myList.AddRange(new string[] { "red", "blue", "green" });

bool colorPresent = myList.Contains(colorToTest); // returns false

colorPresent = myList.Exists(delegate(string str){
return str.Equals(colorToTest, StringComparison.OrdinalIgnoreCase);
}); // returns true


Maybe using extension methods i can provide a case insensitive Find to a List.

BTW, you can get a case insensitive Hashtable by passing StringComparer.Ordinal in its ctor.

Thursday, October 09, 2008

Delegates

Covariance : a method can return a type that is derived from the delegate's return type.

Contra-variance : a method can take a parameter that is a base of the delegate's parameter type.

ex. delegate object MyCallback(FileStream s);
can bound to string SomeMethod(Stream s);

Covariance and Contra-variance are supported only for reference types, not for value types or void.

Shortcuts while working with delegates:

  • If a function expects delegate, just pass function name.
  • use anonymous method to create delegate.
  • don't specify callback method parameters, if you don't need
  • delegate method can use local variables of the invoking method.

ex. We have a delegate as follows, and the function which accepts the delegate :

delegate void TheDelegate(object o);
static void ProcessFunction(TheDelegate d,object o)
{
  d(o);
}

int x = 0;
ProcessFunction(Foo, 5);
ProcessFunction(delegate(object o){
  Console.WriteLine("Anonymous method");}, 5);
ProcessFunction(delegate{
  Console.WriteLine("Simpler Anonymous method");}, 5);
ProcessFunction(delegate{
  Console.WriteLine("Modifying local x to 9"); x = 9;}, 5);
Console.WriteLine("Value of x : " + x);

Wednesday, October 08, 2008

OOP Basics

Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. Programming techniques may include features such as encapsulation, modularity, polymorphism, and inheritance.

Why OOP?

  • It bridges the gap between problem and solution domain.
  • Lets you decompose problem into smaller sub-problems that can be solved separately.  Modularity.
  • Enables reuse

Abstraction

  • Abstraction, as a process, denotes the extracting of the essential details about an item, or a group of items, while ignoring the inessential details.
  • Abstraction, as an entity, denotes focused representation for an actual item.

We can have varying degrees/levels of abstraction.
Abstraction is most often used as a complexity mastering technique.
As we move to higher levels of abstraction, we focus on the larger and more important pieces of information.

Encapsulation

  • Encapsulation, as a process, means the act of enclosing one or more items within a (physical or logical) container.
  • Encapsulation, as an entity, refers to a package or an enclosure that holds (contains, encloses) one or more items.

The walls of the enclosure may be "transparent," "translucent," or even "opaque.
Everything that is encapsulated is not hidden.

Abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden.
Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

Inheritance

Inheritance is a way to form new classes using classes that have already been defined. The new classes (derived classes), take over (or inherit) attributes and behavior of the pre-existing classes, which are referred to as base classes. It is intended to help reuse existing code with little or no modification.

Inheritance is also sometimes called generalization, because the is-a relationships represent a hierarchy between classes of objects.

If the derived class adds new interface elements to a derived type, it can still be substituted for the base type - but the substitution is not perfect. This can be described as an is-like-a relationship

We can have object of another class inside our new class, this concept is called composition/aggregation. Composition is often referred to as a "has-a" relationship.

Composition should be favored over inheritance.

Polymorphism

Polymorphism is the ability of objects belonging to different types to respond to method calls of the same name, each one according to an appropriate type-specific behavior. The exact behavior is determined at run time (this is called late binding or dynamic binding).

Compile time polymorphism : function and operator overloading.
Run time polymorphism : generics and overriding.

Templates

Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Thursday, October 02, 2008

Refactoring (Part 3)

  • Decompose/Consolidate Conditional
    You have a complicated conditional (if-then-else) statement - Extract methods from the condition : if and else parts
  • Consolidate Duplicate Conditional Fragments
    The same fragment of code is in all branches of a conditional expression - Move it outside of the expression.
  • Remove Control Flag
    You have a variable that is acting as a control flag for a series of boolean expressions - Use a break or return instead.
  • Replace Nested Conditional with Guard Clauses
    A method has conditional behavior that does not make clear the normal path of execution - Use guard clauses for all the special cases : The guard clause either returns, or throws an exception.
  • Replace Conditional with Polymorphism
    You have a conditional that chooses different behavior depending on the type of an object - Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract.
  • Introduce Null Object
    You have repeated check for a null value - Replace the null value with a null object.
  • Introduce Assertion
    Make the assumption explicit with an assertion.

Why access specifiers?

  • Without access specifiers, the client programmer can do anything with that class and there is no way to enforce rules
  • Library designers can change internal workings of the class without worrying about how it will affect the client programmer.

C++ uses three explicit keywords to set the boundaries in a class: public, private, and protected.

public means the following definitions are available to everyone. private means that no one can access those definitions except you, the creator of the type, inside member functions of that type. protected acts just like private, with the exception that an inheriting class has access to protected members, but not private members.

Monday, September 29, 2008

Refactoring (Part 2)

  • Introduce Foreign Method
    Create a method in the client class with an instance of the server class as its first argument.
  • Introduce Local Extension
    Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original.

    Organizing Data:
  • Replace Data Value with Object
    Turn the data item into an object - during initial stages of development, your data is simple. As development proceeds you realize that those simple items aren't so simple anymore - turn it into an object.
  • Duplicate Observed Data
    You have domain data available  only in a GUI control, and domain methods need access - Copy the data to a domain object. Set up an observer to synchronize the two pieces of data.
  • Change unidirectional Association to Bidirectional
    You have two classes that need to use each other's features, but there is only a one-way link - Add back pointers, and change modifiers to update both sets.
  • Replace Magic Number with Symbolic Constant

Sunday, September 28, 2008

Refactoring (Part 1)

  • Replace Temp with Query
    Extract the expression into a method. Replace all reference to the temp with the new method. The new method can then be used in other methods.
  • Introduce Explaining Variable
    Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.
  • Split Temporary Variable
    Do not reuse the same temp variable, make a separate temporary variable for each assignment.
  • Remove Assignments to Parameters
    Function arguments should not be re-assigned inside the function.
  • Replace Method with Method Object
    Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.
  • Substitute Algorithm
    Replace the body of the method with some new algorithm.

When to refactor

When you add a function
When you need to fix a bug
When you do a code review

The rule of 3 :
1st time you write some code
2nd time you do something similar, you sill do it
3rd time you do something similar, you refactor.

Wednesday, September 24, 2008

C# : events

Custom eventargs do not need to to use a new custom delegate, you can simply say

public event EventHandler<myEventArgs> NewData;

Why is sender of type object??

  1. if you inherit the event, you would still need to cast to the derived class, so might as well cast from object.
  2. delegate can be used by other types too.

all eventhandlers have return type as void, since there is no way to get the return values from all of the function registered.

The method to raise the event should be - protected virtual.

Use a temp variable to ensure type safety. i.e.

EventHandler<NewMailEventArgs> temp = NewMail;

if(temp !=null) temp(this,e);

You have System.Reflection.EventInfo

As long as an object has registered one of its methods with an event, the object cant be GCed, so unregister events in Dispose().

Registration or un-registration - only one should be executed at a time, so they are marked with [MethodImpl(MethodImplOptions.Synchronized)]. When MethodImpl attribute is applied to an instance method, the CLR uses the object itself as the thread-sync lock, this means that if a class is defines many events, all reg/un-reg methods use the same lock and this hurts scalability, if you have multiple threads reg/un-reg on different events simultaneously.

Thread-synchronization guidelines state that methods should not take a lock on the object itself because the lock is exposed publicly to any and all code. This means that anyone could write code that locks the object, potentially causing other threads to deadlock.

for robust implementation - explicitly control event reg/un-reg

value types can have events - no synchronization.

Friday, September 19, 2008

Running C++ programs in VS2008

I wanted to brush up my C++ skills, write link list/tree programs, however I my simple hello world program was not compiling in VS2008 -- It kept saying iostream.h file not found.

Here's how I got it running :

After starting a new Win32 project, in the wizard, I unselected "Use Precompiled Header".

Now the following code compiles and runs.

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Hello World"<<endl;
return 0;
}



stdafx.h already includes stdio.h and tchar.h, so we can also move #include <iostream> to stdafx.h

Tuesday, September 16, 2008

C# : Strings (Part 1)

Strings are immutable, so to perform a lot of string manipulations efficiently, use the StringBuilder class.

Having strings as immutable means there are no threads synchronization issues.
Also CLR can share multiple identical String contents through a single String object - String interning

String class is sealed.

To compare string without culture information use :
StringComparision.Ordinal or StringComparision.OrdinalIgnoreCase -- fastest.

Instead of lowercase, convert strings to uppercase using ToUpperInvariant()
Microsoft has optimized the code for performing uppercase comparision. In fact, the FCL normalizes strings to uppercase prior to performing case-insensitive comparisions.

Your code will be easier to read and maintain it you always indicate how you want to perform your string comparisions.

Strings cannot actually be changed--only new ones can be created. Therefore, Replace will repeatedly create new strings. StringBuilder, however, can be changed internally and no new copies will be created on Replace or Insert, so if you need to replace or insert very often, use StringBuilder

Given two string variables, how can one get both string variables to point to the same memory location?

Sunday, September 14, 2008

C# : List<T> vs. ArrayList

The generic collection class offers many improvements over the non-generic equivalents.

1. API is clean and improved
2. Performance is greatly improved
3. Value Types need not be boxed when used with List - so no GC
4. Provides compile time safety

C# : Value Types

VT == ValueTypes
RT == ReferenceTypes

VT are simple types - they do not carry storage overheads -->this reduces the cost of creating a object since VT do not have object header, method invocation against a VT does not use virtual method dispatch - this helps performance but loses some flexibility.
VT dont have sync block index, so multiple threads cannot synchronize their access over a VT
VT have System.ValueType as base type.
VT are - structs,enum,bool,int family,etc
VT are marked as sealed and cannot be used as base type.
VT are allocated on stack and not heap,
VT cannot have finalizers
VT cannot have default constructors
VT can be boxed or unboxed, RT are always boxed
VT variables always contain a value of the underlying type - VT variable is never null
when you assign a VT to another, a field by field copy is made.
VT have a different .Equals and .GetHashCode method from RT.(overloaded by System.ValueType)

Defining custom VT - using enum or structs constructs

struct types -
cannot have explicit base class it is always System.ValueType
cannot declare struct as abstract or sealed, compiler implicitly adds sealed - cannot inherit from structs
has LayoutKind.Sequential attribute

When to declare types are VT
1. When the type is simple, that has no members that modify any of the type's instancec feilds, when a type offers no members that alter its fields, we say the type is immutable
2. The type doesn't need to inherit from any other type
3. the type wont have any other types derived from it.
4. Instances of the type are small (16 bytes or less)
5. Instances of the type are large(>16bytes) and are not passed as method parameters or returned from methods.

Saturday, September 13, 2008

C#: new vs. override (part 2)


Derived:Base
Base:BaseBase
BaseBase:BaseBasebase

Derived d = new Derived();
BaseBasebase bbb = d;
BaseBase bb = d;
Base b = d;

All these classes have functions as follows :

bbb - virtual public void FooChain()
bb - override public void FooChain()
b - virtual new public void FooChain()
d - override public void FooChain()

Then the result is as follows:

bbb.FooChain();//BaseBase FooChain
bb.FooChain(); //BaseBase FooChain
b.FooChain(); //Derived FooChain
d.FooChain(); //Derived FooChain

In a hierarchy when we use new(as in Base class), it breaks the chain, so now, when bbb.FooChain() is called, the type is BBB, and as per our rule "overide execuetes derived" and FooChain() in the actual object of D is overridden, we get the most derived FooChain() which is not a "new" Function, so we get "BaseBase FooChain".

C# : Initializers and Constructors

When ctor is executed, it is executed as follows :
ctor
{
initializers;
base();
code of current ctor();
}
Hence, when you have a long hierarchy of classes, you see that initializers run from D -> B and constructors run from B -> D.
Okay, now thats a fact, but why does this happen? --> Derived ctor may rely on state initialized by base ctor... how? --> base may contain a variable which is initialized in base ctor, and dervied ctor might be using that variable.

You should avoid virtual method calls in a ctor of a non sealed type why? --> If a base type ctor causes a virtual method call to be invoked, the most derived type's method will be dispatched even though the derived type's ctor has not completed execution. And so there might be null ref exceptions or unpredictable results.

C# : new vs. override

new:

  • just to be sure that you intentionally want to hide the base method
  • no base method - derived used new --> compiler warning Warning 1 'Types.Derived.Foo()' hides inherited member 'Types.Base.()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
override:
  • derived has to explicitly override that base method.
  • base has Foo(int) and derived overrides, then if base changes the signature to Foo(long) then derived no longer overriders it, it has its own function. Error 2 'Types.Derived.FooNotInBase()': no suitable method found to override.

If you upcast, then "new" executes base and "override" executes derived.

Base b = new Derived();
Derived d = new Derived();
b.FooWithNew(); //Base FooWithNew
b.FooWithOverride(); //Derived FooWithOverride
d.FooWithNew(); //Derived FooWithNew
d.FooWithOverride(); //Derived FooWithOverride

In C#, functions are overloads are impemented as "hide by signature", so if base has Foo(int) and Foo(long) and Derived as Foo(int) then Foo(long) from base is not hidden.

Sunday, June 08, 2008

Definition of Programming

Programming is all about knowing when to boil the orange sponge donkey across the phillipines with an orangutang gorilla crossed with a ham sandwich to the fourth power of twelve across the nile with an awful headache from the previous night when all of alfred's naughty jalapeno peppers frog-marched the nordic elves across the loom-lined geronimo induced swamp donkey over and above the fortran fortified kilomanjaro fence past the meticulously crafted anti disgusting sponge cake scenario where all the hats doth quoteth the milk which is not unlike the super werewolf from the infinite realm of ninja-step. it's hard to define, really.

Something I found on a blog.... I don't have any comments for this one...hehe

Monday, June 02, 2008

Memory allocation in C++

All I had to do was read some content from Registry, but it was not all that simple, I had to read 1 registry, then use the content to read another string and then use it.

While doing all this, I didn't want to use static size buffers, so I started doing malloc(), but guess what malloc just refused to allocate 104 TCHARs, hmm then I tried HeapAlloc() and that was able to allocate the memory.

Different ways to allocate/de-allocate memory:

malloc HeapAlloc HeapCreate
calloc GlobalAlloc GetProcessHeap
realloc LocalAlloc HeapFree
new   HeapDestroy
    VirtualAlloc

small amount of memory should be allocated through malloc family. For bigger size user HeapAlloc, GlobalAlloc and LocalAlloc are available only for backward compatibility, so should not be used.

For more detail information on Managing Heap Memory in Win32, refer : http://msdn.microsoft.com/en-us/library/ms810603.aspx

Sunday, May 11, 2008

Why write Unit tests

One of the reasons we don't refactor our code is that we are afraid that it might break something. But, if you have unit tests in place then, every time you change something, you have your unit test to rely on. It not only saves your time to verify the output, but it also assures you that nothing is broken.

Saturday, May 10, 2008

char and its relatives

In C, I was used to saying

char *psz = "This is some string";

here's what changes in VC++ :

VC++ has the ability to use multibyte characters and Unicode characters - this can be set using IDE options.

Between multibyte character system (MBCS) and Unicode, Unicode has greater acceptance, so we usually program in Unicode. Now to do that first all the string should be defined like this :

wschar_t *buff = L"This is some string";

here, the prefix L tells the compiler that the string is made up of Unicode chars and since char represents a 8 bit character, we need another datatype to represent Unicode char, so we have wschar_t (16 bit Unicode)

However, you might need to switch between ANSI string and unicode strings, to support such a situation, VC++ gives us  a macro TCHAR. It expands to wschar_t  if Unicode is defined else to char.

similarly, instead of harcoding "L" prefix, we again have an option in MFC to use a macro "_T"

We can write the macro ourselves in SDK as follows or include tchar.h

#ifdef UNICODE
#define _T(x) L##x
#else
#define _T(x) ##x
#endif

so now we can write

TCHAR *psz = _T("This is some string");

Modal vs Modeless Dialogs

Modal Modeless
Application control is lost is not lost
DialogBox API is used CreateDialog API is used
EndDialog is used to destory it DestroyWindow is used
Implements it own message loop uses application's message loop
behaves like a synchronous call behaves asynchronously

Calling conventions for functions

Finally I got to know what WINAPI is :)

it is a calling convention.

When a function call is made, you have a choice on how to pass function variables to the stack, they can be passed right to left or left to right, also there is a choice on whether the caller or the callee should clear the stack.

Based on these choices and some other things, we have different calling conventions :

__stdcall or CALLBACK or WINAPI,__cdecl,__fastcall,__thiscall

Check out the following links for details:

http://msdn.microsoft.com/en-us/library/984x0h58.aspx

http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

http://www.cs.cornell.edu/courses/cs412/2001sp/resources/microsoft-calling-conventions.html

Wednesday, January 16, 2008

Cross Thread operations

For quiet some time now I have been using random ways to doing begin invoke. Here is a good pattern for it.

   1: public partial class Form1 : Form
   2: {
   3:     public Form1()
   4:     {
   5:         InitializeComponent();
   6:     }
   7:  
   8:     private void Form1_Load(object sender, EventArgs e)
   9:     {
  10:         ControlsHelper.SafeGui(this, delegate()
  11:         {
  12:             textBox1.Text = "using ControlsHelper on UI thread"; // this succeeds
  13:         });
  14:         Thread t = new Thread(new ThreadStart(WorkOnNewThread));
  15:         t.Start();
  16:     }
  17:     private void WorkOnNewThread()
  18:     {
  19:         ControlsHelper.SafeGui(this, delegate()
  20:         {
  21:             textBox1.Text = "using ControlsHelper"; // this succeeds
  22:         });
  23:  
  24:         textBox1.Text = "direct"; // this fails
  25:     }
  26: }
  27:  
  28: public static class ControlsHelper
  29: {
  30:     public static void SafeGui(Control control, MethodInvoker invoker)
  31:     {
  32:         if (null == invoker) return;
  33:         if (control != null)
  34:         {
  35:             if (control.InvokeRequired)
  36:                 control.BeginInvoke(invoker, null);
  37:             else
  38:                 invoker();
  39:         }
  40:         else
  41:             invoker();
  42:     }
  43: }

Saturday, January 05, 2008

Language Recognition

A friend recently had to work with expressions, and he was looking around for some existing libraries which would let him do this. That's when he found ANTLR (http://www.antlr.org).

From the website :

ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages. ANTLR provides excellent support for tree construction, tree walking, translation, error recovery, and error reporting.

I tried to work with it ANTLR today and I think it is pretty good. One good thing about it is that it also has a GUI to write the grammar, once your grammar is ready, you can generate code in a number of languages.

My primary development language is C# so I was very happy to see that they have also explained how to tweak .csproj and compile the grammar in a visual studio project.

Lazy me

One whole week has gone by... and I have still not started "A pattern a week". I read a bit of  "Elements of Reusable Object-Oriented Software" and it has list of some simplest and most common patterns which one should start of with. They are :

  • Abstract Factory
  • Adapter
  • Composite
  • Decorator
  • Factory Method
  • Observer
  • Strategy
  • Template Method

    So for this week it is Abstract Factory.