Tuesday, September 30, 2008
Wrap finalizer code in appropriate try-catch block
An unhandled exception on the finalizer thread brings the complete process down. Consider wrapping the finalizer code into an appropriate try-catch block and let only the unavoidable exceptions to escape and bring the process down.
Monday, April 7, 2008
Solution to Programming Quiz: Populating stream with unique random numbers

Reader is requested to provide comment if it feels that the above can be made more efficient and has better algorithm than what is shown here.CodeProject
Programming Quiz: Populating stream with unique random numbers
Below are variables and should be the input to the algorithm:
stream: Stream
k: int
max: int
CodeProject
Thursday, March 20, 2008
Pseudo .Net Custom Attributes
Pseudo custom attributes are custom attributes but are treated by the compiler differently than other custom attributes. The storage and retrieval mechanism is different than the other custom attributes. This is done because the pseudo custom attributes are frequently used and it requires space-efficient storage and faster check at runtime. Below are some points which are worth understanding about pseudo attributes:
- Pseudo attributes are laid out in the assembly metadata differently than the other custom attributes. For e.g. Presence of [Serializable] attribute on a type is laid out in the assembly metadata by making a bit on or off. [Serializable] attribute is the one of the most common pseudo custom attributes and it is stored in this manner for the purpose of storage and retrieval efficiency. They are either laid out as bit field or a flag which is unlike other custom attributes that are laid out as blobs.
- Some of the Pseudo Custom attributes are not reported by the overloads of Type.GetCustomAttributes overloaded functions.
For e.g. Presence of [StructLayout] attribute is not reported by the GetCustomAttributes methods on the Type class.
The above points helps when you are developing an application which involves heavy reading of metadata using reflection.
CodeProject
Thursday, February 7, 2008
Dependency Injection
Instead of the serving component creating dependencies by its own, it is the caller or the IoC container which is responsible for creating those dependencies and injecting it into the component.
Ways of declaring dependencies
Component declares its dependencies using one or more of the methods of declaring dependencies. Below are the ways a component can declare its dependencies:
- Constructor Injection: The component declares the dependencies as a parameter to the constructor. All the mandatory dependencies can be captured in the constructor as read-only dependencies. Optional dependencies can be captured by providing the parameterized constructors.
- Parameter Injection: To provide dynamic configuration and modifications of dependencies at runtime, parameter injection can be used. Usually parameter injection is used for optional dependencies.
- Method Injection: If the dependency is required only for a limited scope i.e. only for a specific method in the component then method injection becomes an appropriate choice. In this type of injection, dependency is injected as a parameter of a method.
Benefits
- Interface Driven Development: Dependencies are declared using interfaces or abstract classes. Varying implementation of the interfaces can be used. This promotes extensible and flexible design.
- Loose Coupling: Loose coupling is achieved by dependency inversion. The component depends on the interface and any implementation of the interface can be substituted for the dependency.
- Parallel Development: The component does not require that its dependencies are already in place and implemented. It only requires an interface of the dependent component. Infrastructure team can publish well thought and properly designed interfaces to the application team. Application team can start developing business logic without waiting for the actual implementation of the dependency to available.
- Promotes Unit Testing: A UUT (Unit Under Test) should be isolated from the consequences its dependencies to get the maximum benefit of unit testing. Dependency Injection provides a way to isolate the unit under test by providing stubs or mocks for the dependencies.
- Configurability: Using IoC container declarative and programmatic configurability can be achieved. Declarative configuration supported by IoC container can be used to configure what dependencies get injected in the component. Application can be configured declaratively without the need for compilation.
- Adherence to Single Responsibility Principle: It smells of breaking a SRP (Single Responsibility Principle) when the component declares more than three mandatory dependencies. The smell may denote a problem where the component has more than multiple responsibilities or lack of cohesion. This type of smell can be mitigated by applying refactoring to introduce new type and moving some of the unrelated responsibility to new type.
Limitations
- Disclosing Internals: The component reveals its internals by declaring dependencies. The calling component has to have knowledge of creating the dependencies and injecting in the server component.
- Dependency on IoC Container: It creates a dependency on IoC container. It changes the way how you design your classes.
- Over Engineering: If not properly thought, Dependency Injection and use of IoC container may lead to designs which are over engineered. A judgment call is to be made whether such flexibility of declarative configurability is required or not.
Wednesday, January 23, 2008
Decorator Pattern in .Net Framework
Decorator pattern is used in .Net. The following collection classes are the decorators of the ArrayList class:
- SyncArrayList: This denotes a synchronized arraylist which can be used multithreading scenario. This arraylist is to be used when multiple threads are to modify a single instance of arraylist.
- FixedSizeArrayList: This denotes a fixed size arraylist. The size of the array list cannot be changed. Elements cannot be added and removed. Existing elements can be replaced.
- ReadOnlyArrayList: This denotes a read-only arraylist. Elements cannot be added and removed. Existing elements cannot be replaced.
All the above decorators are defined as following:
private class [Sync/Fixed/ReadOnly]ArrayList : ArrayList
{
internal [Sync/Fixed/ReadOnly]ArrayList(ArrayList arrayList) {...}
}
The above structure is the proof of all the aboved mentioned classes to be a deocorator of the ArrayList class.
All the above deocorators are private and can be instantiated using the static methods provided on ArrayList class:
All the decorators override appropriate virtual methods and adds the additional behavior. Below shows the sample code snippet for the Synchronized arraylist the decorators:
Similarly ReadOnlyArrayList overrides the virtual method of the ArrayList class and throws exception to restrict any modifications in the list.
In a similar manner FixedSizeArrayList overrides the virtual method of the ArrayList class and throws exception to restrict any changes to the size of the list.
This is how the decorator pattern is being used in .net framework. There are possibilities of decorator pattern being used at multiple places in the framework. It can be found out by studying the framework thoroughly and understanding the patterns used in the framework.
Monday, January 21, 2008
Guard Clause
Every method has some behavior or expectations to be fulfilled. The logic required to fulfill the expectations is called as the main flow of the method. Any deviation or exceptional case to the main flow can be represented as a guard clause. A guard clause is a condition and an action which is a deviation to the main flow of the method.
A deviation in a main flow of a method can be:
- Object State Check (Precondition Check)
- Parameter Check (Precondition Check)
- Range check (Precondition Check)
- Validity check (Precondition Check)
- Any logic which is part of the main flow but it is a distraction to the code readability
Guard clause can be used to separate the main flow from the distracted deviation in the main flow.
Below example shows how guard clause can be used to increase the readability of code
Before
DomainObject FetchObject(ObjectSpecification specification)
{
if (specification == null)
{
throw new ArgumentNullException("specification");
}
else
{
objectFetcher.Fetch(specification);
}
}
After
DomainObject FetchObject(ObjectSpecification specification)
{
if (specification == null)
throw new ArgumentNullException("specification");
objectFetcher.Fetch(specification);
}
Guard clause when applied properly can improve the readability of code. In fact it is one of the re-factoring techniques suggested by Martin Fowler. The name of the re-factoring technique suggested by martin fowler is ‘
CodeProject
Saturday, January 19, 2008
"Prevention is better than cure"
Fixing defects is not a cost free activity. Defect fixing is a costly activity. If the defect is found at the later stage of the software development, the greater the cost of fixing it. Hence it is always better to prevent the defects and also to fix it at the early stage of software development.
Below shows the tentative cost of fixing a bug at the respective stage of software development.
Phase - Relative Cost to Correct
Requirments - 1
High-Level Design - 2
Low-Level Design - 5
Coding - 10
Unit Testing - 15
Integration Testing - 20
System Testing - 50
Post-Release - 100+
Hence defect prevention should be given utmost important in the software development life cycle. Defect prevention can greatly reduce the cost and time to market of the software.
"Prevention of defects is better than fixing it"
Wednesday, January 9, 2008
Facade Pattern (Part 1): What? and When?
The dictionary meaning of facade is:
- "A face or front of a building"
- "A showy misrepresentation intended to conceal something unpleasant"
In our day to day life we come across architecturally sound buildings. Now a days the trend is to have the front or the face of the building made up of glasses which give an elegant look. But the internal architecture of the buildings are found to be complex and distracting.
Facade is used when you want to hide something complex behind a simple and unified interface.
For e.g.
Assume that you are a master of OCR technology and have developed some complex OCR sub-system or package or library. This sub-system consists of about 50 odd classes. This package is to be consumed by some application, which is being developed by the application developers. These application developers do not have much knowledge about OCR technology. They just want to perform an OCR on some images and generate a word document out of it.
In these days of RAD and competitive market it is not feasible to first learn the OCR technology and then understand the complete OCR sub-system and then start consuming it. It is always better if the simplified and unified interface for the complex sub-system exists so that RAD can be achieved.
Hence to support RAD and to hide the underlying complexity of the sub-system, Facade can be used. Here facade provides a simplified interface to accomplish trivial tasks. To accomplish difficult or non-trivial tasks, the application programmer has to rely on the sub-system.
The crux of the matter is "Facade hides the complexity of the sub-system from the consumer".
Tuesday, January 8, 2008
I became blogger
- Refactoring
- Code Cleaning
- Test Driven Development
- .Net & C#
- Puzzles
- Code Quiz
- Miscellaneous
I am planning to blog 4 entries per month.
The main aim behind this blog is to become a better developer and let other developers become better. The blog will deal mostly with the development (implementation) aspects of software development.
This blog is open for honest suggestions and feedback.
Happy Reading! Read it regularly and become a better developer.
Thanks, Andy
