Design Patterns

Inputs: Google, C#3.0 design patters by Judith Bishop
Outputs: Below. This is how I understood design patterns... I try to put them in a abstract way... concisely...
Processor: Error prone... my brain!

A Design pattern is  general solution to commonly occurring problem in software design. In fact solutions to commonly occuring OOPS issues. One level down the Object Oriented Programming cannot support itself hence needs a design paradigm. Most of us will be using patterns even without knowing that we are using a pattern in many scenarios.

Structural patterns:

Decorator pattern: What it is: It can be simply said runtime subclassing. subclassing is extending the functionality of class at compile time itself. Whereas decorator pattern involves extending the functionality at runtime. It can be also said that adding functionality dynamically to an object is possible by decorator pattern. When to use: This pattern is fit if subclassing will lead to too many.

Proxy pattern: What it is: Proxy pattern implements call forwarding mechanism. It helps to create objects on demand wherever object creation is expensive. Good example is the world of DCOM and Remoting. Where proxies will be middle man and clients query them as local objects. The actual call will be executed in remote machine.When to use: If objects needs to be created on demand. If some misc activities needs to be performed when a call is made. Example for misc activities include authentication, authorization, licensing etc.,

Proxy vs Decorator: Do you think they can be compared?! May be in one aspect... that is the call forwarding aspect. They both forward calls. But proxies always forward call to the same object it creates. It is fixed at design time. But in case of decorator it is dynamic.Decorator objects can hold instance of any type of components or even to another decorator itself!

_cdecl vs _stdcall conventions:

_cdecl & _stdcall are two different calling conventions seen in pre .NET world. Here _cdecl is mostly used with C & C++ Environment. Here Calling function (caller) will be clearing the stack under the hood. This is default for CRT (C Runtime Library) environment.

Example:

void foo(int i) à _foo;

void foo(int i, int j) à _foo@8

Most of the Win32 (32 bit Windows OS) API’s will be of_stdcall type. Here called function (callee) will be doing the stack cleanup. Name decoration will be containing param count. Code foot print is small because clean-up code will be in only one place even there are multiple calls.

Example:

void foo(int i) à _foo@4 ; (An int param is 4 bytes in size!)

void foo(int i, int j) à _foo@8

Note: See the decorations that’s why they did not support optional params

Thoughts on FxCop (.NET)

FxCop is very useful tool for code review. I was doing a study on it, And some crazy thoughts raised on my mind... what will happen if FxCop is run on FxCop.exe...? FxCop came clean. No Active errors! But there were 135 errors but under "Excluded in source" section.

Then another crazy thought raised in my mind... what will happen if FxCop is run on .NET core dlls...Here FxCop came Nasty! There were thousands of Active errors! Why didn't Microsoft comply with FxCop?A fourm reply said "FxCop was designed and generated long after the original framework design was in place
"http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/5abda75d-1177-4a91-9b20-dd17c42d4567 Tidbit: How to mark a bug as “Excluded in source”? Code that causes the error should be marked with this C# attribute “CodeAnalysis.SuppressMessageAttribute” Example: [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] private void test() { string name; //unused variable // some code here } Please note that above exclusion will only work if “CODE_ANALYSIS” compiler directive is added to project properties.

Common crashes & compile errors (C++)

This topic I will cover some common compile errors encountered in C++...
1. Error C2243: 'type cast' : conversion from 'DerivedClassXXX *' to 'BaseClassXXX *' exists, but is inaccessible.
Resolution: Most common cause is when deriving from your base class acces specifier keyword "public" might be missing
//Here is the code change in Bold
class DerivedClass : public BaseClass
{
///your code goes here
}
The C# touch: The "public" keyword used here to fix this issue is not applicable in C# environment. And also inheritance is always public by default there.
2. Program crashes on reading params from main()
Make sure correct overload is called. Below is one correct overload.
int main( int argc, char *argv[])
{
}
First param supplies number of arguments, make sure to check this one first.
Note: argv[0] will contain program's name with it's path.
For more clarity check this link below:
3. fatal error C1010: "unexpected end of file while looking for precompiled header directive" when compiling your win32 dll or exe
It can be as simple as not including stdafx.h file in to your cpp class implementation files. Other reasons visit :-) http://support.microsoft.com/kb/815644

Include Guard in C++

Include guards prevent multiple includes of the same file in C++, MFC.

They are preprocessor directives. Pre-processor directives will be also called as compiler directives. These are instructions that will not be part of the executable/object file instead commands to the compiler when it generates the executable!

When you require include guards?

When you get “redefinition; different storage class” errors in your visual studio it means that same header file is included twice somewhere directly or indirectly. This will be difficult to find in complex code. So easy option is to provide include guard for your most used header files. Syntax given below…

#ifndef YOURFILENAME_H

#DEFINE YOURFILENAME_H

//YOUR HEADER FILE CODE GOES HERE

#endif

A view on C# Generics

.NET Generics has wide vareity of applications, from generic collection classes to custom user created collection classes.
An object based collection has boxing/unboxing overhead for value types, casting overhead for reference type this means type safety can be compromised & may be runtime exceptions will happen. Writing a collection class for every type will lead to lesser productivity. In Non-generic list value types needs to be boxed & reference types needs to be casted hitting performance. Also accidentallly unwarranted type can enter in to list throwing runtime exception because weekly typed it is. A generic class can defer specification of one more types until it is instantiated. (For example a generic type T may be an int or string)

Generics after compiling in CIL it will contain only type value parameters. But during compilation by CLR to create instance of generic class, the handling is different for value type and reference type. For value type for every distinct type T a generic specialized class will be created with proper substitutions. For example for int & long, separately substituted two generic specialized class will be created. For reference types things are different. On encountering usage of first reference type a single specialized generic type will be created substituting object pointers. For example customer, order classes will be instances of same substituted specialized generic type. This reduces code bloating instead of a class for every Type, same generalized substituted Type class is re-used.

Default keyword will be used like default for returning 0 for value & null for reference types. “where” keyword limits use of specific generic placeholders on a generic type. A constraint specified with ‘where’ keyword can limit what could be the generic Type T can be. For example it can limit that to MyClass, so only many code logic (like comparisons or operator overload) will work on it.

Good book on COM

I am reading Don's book Essential COM. Preface is fairly intresting.
The author argues on the definition of object orientedness.
C++ => OO => (some) Encapsulation + (some)Polymorphism + (some)Late Binding + Implementation Inheritance
COM => OO => (Real)Encapsulation + (Real) Polymorphism + (Really)Late Binding + Interface Inheritance

Eagle's eye on view datastructures

A data structure is collection of organized data and appropriate functions to operate on that data. STL offers many of common data structures in C++. System.Collections & System.Collections.Generic is the nearest C# equivalent. Stack is one of the simplest data structure based on Last in first out concept (LIFO). Queue is another one based on First in first out concept(FIFO). Stacks & Queue in general are based on arrays so of fixed size. This is the reason where linked list comes into play. Again in general the above data structures did not deal with any relationships between them, that is why Trees are there. They can represent data relationships hierarchically.

Tid bits with C++

one common interview question is difference between overloading & overriding. The correct answer is overloading is compile time polymorphism. While overriding is runtime poly morphism.

Tid bits Windows with VC++

SendMessage & Postmessage API are essentially same, but big difference is SendMessage blocks, while PostMessage returns immediately

In C# to draw Control.CreateGraphics() is called to get a Graphics obj. Finally Dispose() needs to be called on this Graphics object. In MFC you can call GetDC() or CClientDC dc(this) to get DC... In former case ReleaseDC(CDC *p) needs to be called. Other DC's are CWindowDC, CPaintDC...

UpdateData(false) updates data in variable to control while param true does in reverse.

GetDlgItem(ID) returns a CWnd ptr. GetDlgCtrlID(CWnd*) returns ID of control

Diamond Problem

Diamond problem occurs with multiple inheritance where a derived class derives from two intermediate base classes whereas those base classes have a common base class. When compiled a common method in super base class call will resolve to ambiguity and throw an compiler error. This can be solved by adding virtual keyword in both of the base classes which creates separate vtables. By using these vtables runtime binding is resolved. (In other words both vtables of intermediate base classes will be referencing to the address of function in super base class)

In C# this problem is solved my completely blocking multiple inheritance. Only multi-level implementation is permitted in C#. Also note that multiple interface implementation is supported in C#. The reason is multiple inheritance leads to more complexity. (only one of which is diamon problem) So the .NET architects kept away from it.

Agile Vs Scrum

Agile:
Iterative & Incremental
Delivery of working software in short intervals
Continuous customer involvement
Cross-functional team

Waterfall:
Requirements, detailed schedule upfront
Linear phase by phase
Every phase done by specialist programmers
Feedback only at end.

Agile Merits:
Customer involvement
Early testing

Waterfall Merits:
Detailed plan including cost & estimation
Every phase proceeds to next with proper sign off & checklist

Agile Demerits:
Feature creep.
Compromise quality to meet sprint delivery.


Waterfall Demerits:
Oversights in requirements/design only visible at end.
Testing done at end so quality might end bad

Tit Bits .NET General concepts

Startup:

What is .NET framework:
.NET framework comprises CLR and Class libraries. Code that targets CLR is managed code. CLR aka Common Language runtime is the execution environment for managed code. It provides Garbage collection, JIT Compilation, Code Execution, code access security, interop, diagnostics, type safety & many services. Base class library is the set of class libraries that expose many .net services for all clr compliant languages.

Cold Startup: This happens when .NET runtime as well as application code were not in memory.
Warm Startup: This is faster. This happens when application is re-launched.

Thread.Suspend vs Thread.Sleep
Sleep() immediately puts the thread to sleep. While suspend() clr takes care to suspend after finding a safepoint to do so. Suspend() is not safe deadlocks can happen if the thread suspends with access to a resource that another thread is waiting for. Suspend()/Resume() deprecated functions from 2.0

Lock is a language construct that wraps Monitor.Enter & Monitor.Exit Both of them are basic synchronization objects. But Monitor class offers Wait & Pulse methods. But these are unsafe because if an thread enters wait after a pulse was issued it will result in deadlock. So for synchronization & communication between threads AutoResetEvent is the good construct.
Locks, Monitors & Mutexes are mutually exclusive. Semaphore is not mutually exclusive. Both semaphores & Mutexes derive from WaitHandle OS construct. Mutexes & semaphores can work across processes.

Software Patterns

Software patterns fall in to Architectural patterns, Design patterns and Idiomatic patterns. Architectural patterns: It defines the fundamental structure of the whole software system.
(Layered systems, MVC)
Design patterns: It organizes functionality between subsystems in a domain independent way.
(Abstract factory, template methods, singleton)
Idiomatic patterns: Low level patterns to solve particular implementation problems.
(singleton pattern implementation specific for .net)

Design Principles

Many people don't follow any principles in living... Many don't know about them and many laugh about such thing... Same applies to software design principles also... Let us join the few who cares about design principles...
Open close principle (OCP)
This is known as open for extension and closed for modifications. A class can be better implemented as abstract & derived forms so that if any changes needs to be made it can be made to the derived functionality instead of changing core base class. A bad implementation example is Shape class that draws rectangles, ellipses, circles. If it needs to draw a square then a new drawSquare() function needs to be added. This is bad design because as the class is changed all of it needs to be unit tested again, if this is imagined as big class there are problems with multiple developers working simultaneously needs to integrate it and a change might break the code somewhere. A good design is splitting the shape in to one Shape base class with abstract drawShpe() and multiple derived classes like Ellipse, Circle, Rectangles overriding implementation which fits in to OCP...

Dependency Inversion Principle

Content in development..............................



WARNING: ALL CONTENTS HERE ARE MY PERSONAL INTERPRETATIONS. THERE IS NO WARRANTY GUARANTY ABOUT RELIABILITY OF CONCERNED MATTER