Primary focus technology and software development related topics which I learn and keep here for self reference.
Translate
Friday, January 31, 2014
Tuesday, December 24, 2013
WCF Extensibility
Behaviors
Enter WCF
extensibility points.
What is
covered:
-
Service
description vs Runtime
-
Behavior
Interfaces
-
Runtime
Extensibility
o
Interceptors
o
Formatters
o
Instancing
o
Error
Handling
o
Some
Others
-
Metadata
Extensibility
-
Serialization
Extensibility
-
WCF
Channel Programming Model
What is
not covered:
-
Some
lesser-used interfaces
-
Security
Service description vs Runtime
-
Service (client) Description
o
All
the things needed to start the service (client)
o
Ednpoints
(Address/Binding/Contract)
o
Local
Behaviors
-
Before “Open”
o
Description
can be changes at will
o
Service
not “running”
-
After “Open”
o
Runtime
is initialized
o
Description
is immutable
o
Listeners
are started
o
The
Service is started
-
WCF
provides 4 interfaces to interact with the Service or Client descriptions
o
Service
o
Endpoint
o
Contract
o
operation
-
Each
Interface has 4 methods which follow the same pattern.
-
public
interface I[Service/Contract/Endpoint/Operation]Behavior
o
void
validate(Description) : Prevent host or client from opening if it finds
something invalid in the service description
o
void
AddBindingParameters(Description, BindingParameterCollection): This gives an
opportunity to the behavior to add more information to the Binding channels.
o
void
ApplyDispatchBehavior(Description, Runtime):
This is the place where the behavior gets hooked up to the runtime in the corresponding scope.
o
void
ApplyClientBehavior(Description, Runtime) * {This is only client side}
-
Called
during Open (Be it at the service side or the client side)
-
Ordering
o
Validate
à
AddBindingParameters à
Apply[Client/Dispatch]Behavior
o
Serviceà
Contract à Endpoint à Operation
-
Service Behavior
o
Service-wide
operations
§ Metadata : Validation of the
metadata exchange across the communication
§ Throttling
§ Debug
o
Public
interface IServiceBehavior
§ Validate
§ AddBindingParameters
§ ApplyDispatchBehavior
o
Added
via code, configuration, attributes
WCF Runtime
WCF is a
message stack with many message blocks from client calling the operation to the
service call getting executed on the server.
We will see
the most used blocks through which the messages pass.
·
WCF
Runtime
·
Message
Object
·
Message
Inspectors
·
Parameter
Inspector
·
Message
Formatters
Client Proxy Call à Parameter Inspector à Fomatter à Message Inspector à WCF stack à Message Inspector à Formatter à Parameter Inspector à Service Operation
First question is what is a Message, what is
the structure and Characteristics of the message.?
·
·
System.ServiceModel.Channel.Message
à
Abstract Class
·
SOAP/XML
·
Parts
o
Header
– Buffered
o
Body
o
Properties
: Dictionary not part of SOAP specification
·
Single-use
: Once the message is used and read then it cannot be used any more. One can manipulate
message headers at will.
·
Message
Versions: different versions of SOAP
protocol which are envelopes like SOAP 1.1, 1.2 or none (message is not SOAP
message but POX- Plain old XML)
·
XML
Message
Inspectors :
Most used
WCF extension from the WCF Runtime.
·
Usage:
inspect, modify, replace messages
·
Scenarios:
Logging, custom auth, tweaking messages, correlation between request and
response
·
Server Side
o
MessageInspector
is represented by the Interface: IDispatchMessageInspector
§ AfterReceiveRequest
§ BeforeSendReply
o
Dispatch
behaviors are typically added as endpoint behavior as a part of
ApplyDispatchBehavior to the DispatchRuntime object.
·
ClientSide
o
MessageInspector
is represented by the Interface: IClientMessageInspector
§ BeforeSendRequest
§ AfterReceiveReply
o
MessageInspectores
are added as a part of service endpoint to the clientRuntime object.
o
Correlation object Used as correlation so that
request can be set with something specific after the prior reply is received.
Parameter
Inspector
Parameter
inspectors are same as message inspectors but they are called on CLR objects not
the message objects. They are easier to use as they do not require any
knowledge about messages. Unlike Message inspector they are less powerful as
they have less access to message itself.
·
Usage:
Inspect and Modify operations inputs and outputs.
o
Return
value cannot be modified
·
Scenarios:
logging, parameter validation.
·
Same
Interface for Client and Server : IParameterInspector
o
IParameterInspector
§ BeforeCall
§ AfterCall
·
Adding
parameter inspectors often done in OperationBehavior
o
Server:
DispatchOperation
o
Client:
ClientOperation
·
Like
MessageInspector ParameterInspector has a Correlation object is returned by
BeforeCall and Passed to AfterCAll.
Message
Formatters
Message
formatters are the gateway between WCF messages and world of CLR objects.
·
Usage:
convert between CLR objects and Message
·
Unlike
Inspectors MessageFormatters are not optional but each operation has one and
only one instance MessageFormatter.
·
Scenarios:
supporting different formats, like passing some information as a part of
httpHeaders.
·
Server Side
o
MessageFormatter
is represented by the interface: IDispatchMessageFormatter
§ DeserializeRequest
§ SerializeReply
o
Message
formatters can be accessed using the DispatchOperation in the Endpoint and
operation behavior.
·
Client Side
o
MessageFormatter
is represented by the interface: IClientMessageFormatter
§ DeserializeRequest
§ SerializeReply
o
Message
formatters can be accessed using the ClientOperation in the Endpoint and
operation behavior.
·
One
difference between Inspectors and formatters is that it does not provide the Correlation object between request and
reply.
Wednesday, November 13, 2013
Monday, September 30, 2013
Monday, September 23, 2013
Design Pattern Notes
I have been going through the Design Patterns Library course hosted by Pluralsight. Below is a small descriptions and a note to understand various patterns.
Prototype Pattern:
--------------------------------------
- Overview of the Prototype PAttern
- SPecify the kinds of objects to create using a prototypical instance and create new objects by
copying this prototype --> Cloning or Making a copy instead of newing the object up
- Its easier to make a copy of the object than going through the whole construction process this is why
this pattern is used.
- Problem 1: COnstruction cost of an object is expensive
- Problem 2: State is important copy the state.
- Problem 3: Hiding the constructor
- Prototype design --> Just implement a Icloneable Interface and while implementing Clone method return
MemberwiseClone()
- You can do a deep copy and shallow copy --> MemberwiseClone does only shallow copy is specified only at one
level
- Examples are present in javascript, javascript is a prototypical language. --> Structuring Javascript is a
course on pluralsight.
I hope that I should be able to cover all the patterns as the list of patterns are quite extensive and I recommend all of you to get a license of Pluralsight so that you can be exposed to the sea of courses they have.
(Excuse me upfront for the typos as the notes were taken in notepad++ while I was going through the patterns, once I finish the important patterns I intent to reformat this post and make it more pleasant for all of us)
Adapter Pattern:
--------------------------------------
- The Adapter Pattern is used to wrap a needed class with one that implements a required interface.
- By writing client classes so that they depend on adapters, we future proof these classes, ensuring
they can be made to work with as-yet-unwritten implementation libraries.
Related PAtterns to the AdapterPattern:
- Repository Pattern
- The repository pattern is a verfy common use of Adapter Pattern
- Strategy Pattern
- The adapter pattern is often passsed into a class that depends on it, thus implementing the strategy pattern.
- Facade Pattern
- Adapter and facade pattern are both wrappers. The facade pattern attempts to simplyfy the interface and often wraps many classes, while the Adapter
typically wraps a single Adaptee, and is not generally concerned with simplyfying the interface.
Bridge Pattern:
--------------------------------------
DEcouple an abstraction from its implementation so that 2 can vary independently. Abstractions and implemenation are decoupled.
Abstract one more level of interface so that 1st level of abstraction is dependent on the 2nd level of abstraction
This abstraction is going to use one more level of Abstraction as its implementation.\
Abstraction -> Abstraction -> Implementation
For one level of abstraction there's no need of Bridge pattern.
Common usgaes of bridge pattern:
- User Interfaqce
- Neat explanantion of the pattern is also given at: http://www.oodesign.com/bridge-pattern.html
Builder Pattern:
--------------------------------------
Problem 1: too Many paramteres
Problem 2: Order Dependent
Problem 3: Different Constructions
Spearates the construction of a complex object from its representation so that same construction process can create different representations.
Construction of the object is a process OR logic.
Representation of the object is data.
Separate logic from data, reuse the logic to produce different data.
Instead of telling the subway guy on what all you need after asking for each ingredient you are going to give him an list of ingredients so that the conversation is
much shorter.
Chain of Responsibility Pattern:
--------------------------------------
Provides a simple mechanism of decoupling the sender of the message from the receiver
Ordered list of methods
Sender --> Receiver1 --> Receiver2 --> Receiver3
Lets say in the above scenario the message sent by the sender is handled by the Receiver2 and so the receiver 3 is not needed.
Sender only is exposed to the Receiver1 and so is the Receiver2 knows only about Receiver3. This brings us to the traits of Chain of Responsibility.
- Sender is aware of only one receiver
- Each receiver is only aware of the next receiver
- Receivers process the message or just send it down the chain
- The sender does not know who received the message.
- The first receiver to handler the message terminates the chain
- The orcer of the receiver list matters
Command Pattern:
--------------------------------------
- A command line order management system
- A system in which you pass in a command to be done.
- In such systems we should be wary of a very big switch case statements which decide what to do based on the input passed.
Intent of the PAttern:
- Represent an action (piece of logic) as an object
- DEcouples the clients that execute command from the details and dependencies of the command logic
- Enables delayed execution
- Can queue command for later execution
- If command objects are also persistent, can delay acrosds the process restarts
Also knows as Action OR Transaction PAttern
Applicable on
- Logging the actions
- Validation
- Undo functionality in the website
Client --> Command { Validate(), Execute(), Undo()} --> (dependencies)
--> (dependencies)
- Key notion of command pattern is that somebody can call a method without dealing with any extra data.
- There is no parameter to be passed which makes it different from the Strategy pattern (here execution path is defined based on the parameter passed)
- COmmands must be completely self contained
- The client does not pass in any argumemnts, the context from the caller is not required
- Easy to add new commands (open/closed principal)
Related Patterns:
- Factory pattern : Factories are ofyten useful to construct the command objects
- Null Objects: Often times returning a "null command" can be useful instead of retuning a null
- Composite Command: Command with child commands
http://www.oodesign.com/command-pattern.html
Composite Pattern:
--------------------------------------
- Compose objects into tree structures to represent part-whole hierarchies.
- Composite lets clients treat indivisual objects and compositions of objects uniformly. (GOF)
- If you are sending emails to individuals instead of using the group aliases then you need to apply composite pattern to your life.
- Using group aliases is the live example of using the composite pattern, the sends just sends an email to the group and the e-mail has the logic to iterate over the
members of group and make sure that email is individually sent to each of the member.
When to Use Composite Pattern:
- When you have groups and collections
- Can you add an Interface
- trees
- Distribution
Basic is to define an interface (component) and have a leaf (simple object implement it) and then create a composite object which implements the interface and also has
a property which is of the type of component.
Decorator Pattern:
--------------------------------------
Structural Pattern : DEcorator object is used without touching the existing class.
Small Pizza company: Large, Medium and Small Pizza deriving from Base class Pizza.
Problem is when toppings are introduced: Cheese, Ham and Peppers
Now with 3 Pizzas we have 3 toppings each combination is a unique pizza.
This will result in class explosion and will become very hard to maintain.
Intent:
- Add functionality to existing objects dynamically at runtime without effecting the other classes.
- Alternative approach to sub classing
- Inheritance based design leads to an explosion of the classes.
- Flexible design
- Support Open Close Principle --> Open for extension but closed for modification
Applicability
- Legacy systems
- Add functionality to controls.
- Sealed Classs
IExtenderProvider interface uses decorator pattern, for more info on the interface below are the links:
http://www.codeproject.com/aspnet/FixingIExtenderProvider.asp
http://www.codeproject.com/aspnet/ExtenderProviderComponent.asp
How does it work:
- It wraps the object -- Also known as wrapper object
Lazy LOad Pattern:
--------------------------------------
Lazy Initialization Pattern :
- Simplest approach
- Every property checks to see if its backing firlds has been initialized
- If so it calculates or fetches the value for the field before retunung.
- Violates don't repeat yourself principle
- Requires all access to tge value ti go through the property
- Within the class nothing but the property should access the field.
- Requires knowledge of whether the fields has been calculated
- Typically check if the field is null
- If null is a legal value then another approach is required, like using the flag if the value is populated or not.
Virtual Proxy Pattern:
- Proxy looks like real object
- Creates Indentity problem in the application
- Proxy isn't the real object
- OverRide the equality method (Equals)
- Proxy Design PAttern
- May need to create many virtual proxies
- Best done via some kind of code generation
- MAny OR/M tools create dynamic proxies at runtime (nHibernate, Entity Framework)
Virtual Proxy Consequences:
- Managing Identities can present Challenges --> Overriding GetEquals and GetHashCode
- Need to create many virtual proxies, one for each class that is proxied
- Above stated points are not present for collections:
- Collections are value objects and do not have an identity.
- Typically there are fewer collections than objects
- Collections typically provide largest performance benefit from the lazy loading.
Value Holder LAzy Load PAttern:
--> No need to use this if we are using .Net 4.0 if .Net 4.0 is in use then directly use Lazy
- Provides lazy load functionality without encapsulation which means the client knows about the lazy loading.
- Calling code knows it is working with a Value Holder type
- Requires creating several new Types:
- Value Holder
- IValueHolder
- Factory or MapperClasses
- Value Holder uses IValueHolder via Strategy Pattern to load value when accessed.
- ValueHolder and IValueHolder are resuable
- ValueHolder is similar to Lazy and IValueHolder is similar to the lambda expression which is passed which knows how to load the lazy type.
- ValueHolder and IValueLoader are resuable.
Ghosts Pattern:
- A ghost is a real object in a partial state.
- An object which knows about its own state.
- Intially ghost contains its Id.
- Whenever any property is accessed, the ghost class loads all of its state from persistence.
- Essentially, the object is its own virtual proxy
- Avoids identity concerns of its own virtual proxy,
- This violates the Single responsibility cause the object is needed for self loading and plus loading the state of its own properties.
Mediator PAttern:
--------------------------------------
Motivating Example
- When you have many objects of a similar typpe that need to communicate with each other
- The communication between objects is complex
Definition:
- Define an object that encapsulates how a set of objects interacts. Mediator promotes loose coupling by keeping objects from referring to each other explicitly,
and it lets you vary their interaction independently.
Components in Mediator Pattern:
- Colleagues
- Individual compnents that need to communicate with each other Airbus, Fighter
- Implement the same base type(abstract class or interface)
- HAve a knowledge of the Mediator component rather than knowing of each other.
- Mediator
- Single centralized component that managed communication between the colleague components
- abstraction of mediator is necessary so that the colleagues work with the abstracted mediator rather than concrete one.
Advantages:
- Hides all the coordination between colleagues
- Decoupled colleagues
- Mediator's one to many relationship with colleague is preferred to colleagues relating in a many-to-many fashion.
Disadvantage:
- The mediator can become very large and very complicated as more colleagues are handled.
Overall mediator enhances decoupling
Memento Pattern:
--------------------------------------
Undo and Redo functionality
Motivating Example:
- It would be useful to rollback one or more objects within your application to previous state(for example, to implement Undo)
- Providing undo functionality within one or more calsses would violate the single responsibility principle
- Providing full access to objects internal state violates the encapsulation principle
- The Memento pattern describes a way to capture the objects internal state without violating encapsulation or SRP.
Intent:
- Without violating the encapsulation, capture and externalize an objects internal state so that the object can be restored to this state later.
- The memento pattern involves 2 objects : originator and caretaker. Thr originator represents object whose state is being tracked.
The care taker performs the operation on the originator but needs to be able to undo operations.
Applicability: When to use the Memento Pattern:
- in case of an application whose state needs to be tracked, you need to be able to track the state of an object or your application and restire previous states as
needed.
- You want to abstract and reuse the Undo/Redo functionality
- Follow SRP and Don't repeat yourself
- You do not wish to break encapsulation and expose your classes internal state globally
How the memento is used:
- Memento itself holds the state of the originator
- Ideally ony the originator should have access to the internal details of its state within the Memento
- The caretakers interface to Memento should not allow it to access the internal state of the Originator
- The originator can create Mementos or restore its given state given a Memento
- The care taker maintains the memento objects without operating on their contents.
Common Usage of Memento is Undo and Redo functionality:
- Multiple Undo/Redo is often implemented using a stack
- When a change is performed:
- A memento containing the current state is added to the Undo stack
- When an undo operation is performed:
- the current state is replaced with the state of the memento removed from the Undo stack
- If Redo is implemented, the current state is stored in a Redo stack.
- When a Redo operation is performed
- The current state is replaced with the state of the memento removed from the Redo stack
- The current state is stored in the Undo stack.
Collaboration:
- Whenever a change is made from the requested state, A care taker requests a Memento from the Originator
- The caretaker stores one or more Mementos until they are needed.
- If or when requred the Caretaker passes the Memento back to the originator
- It may be possible that Memento stored by caretaker may not be used if there is no redo or undo functionality
- Mementos should be value objects, holding state but no behavior.
- Only the originator which created a memento should be able to assign or retreive its state.
Model View Presenter Pattern:
--------------------------------------
Model View View Model Pattern:
--------------------------------------
- a set of guidelines to code for an application
- Where did MVVM come from?
- What is MVVM?
- Components of MVVM ?
History:
- 2004 Martin Fowler - Presentation Model
- Separates a view from it's state and behavior
- Not dependent on specific UI Framework
- 2005 John Gossman unveiled the MVVM pattern
- Tailored for WPF and Silverlight platforms
Intent:
- Separate Concerns
- View
- View's state and Behavior
- Data
- Unit testing and UI testing
- Maintenance
- Extensibility
- Enables designer/developer workflow
- Take advantage of WPF/silverlight databinding --> Also supports input validation
Structure:
- View
- ViewModel
- Model
- Model :
- HAs no reference to the View or ViewModel
- Model can be represented by Domain specific objects
- Model can be represented as Data centric object (model is XML or data access layer)
- Model's purpose is to represent Data points
- ITs single purpose is to represnt datapoint
- View :
- May or Maynot have a reference to the ViewModel
- Doesnot have a reference to the Model
- It consists of only visual elements of display like buttons windowns and everything
- Responsible for showing and collection data to and from user.
- in silver light the data bindings are specified but the details are hidden from the UI.
- Binding the viewModel set by DataContext
- The ViewModel:
- Has a reference to the Model
- May or may not have a reference to the view
- Contains properties and commands and other abstratctions to make the communication easy between the view and the model.
- At minimum the view should implement the INotifyChanged interface because the ViewModel is bound to notify the view of a change.
- Although the ViewModel contains the state and the data for the UI is should have a UI control as a base object.
To Create the connection between the view and viewModel (Binding the view to ViewModel):
- Declaratively in XAML --> View first approach --> ViewModel as a resource --> Static resource on the View
- Cannot control instantiation
- Cannot pass parameter
- Imperatively in code
- The view model is assigned in the views code behing after the Initialization method
- View Model Locator --> Service Locator renamed for MVVM
- DataTemplates
- Inversion of Control
- Factory with Inversion of Control
- and more ..
Communication:
- Events
- Commands
- Execute
- CanExecute
Consequences
- Pro:
- Reduce Code behind
- Model doesnot need to change to support a view
- Designers design and coders code
- Reduces development time
- Multitargeting and project linking
-Con:
- Create more files
- Simple tasks can be complicated
- Lack of standardization
= Specific to WPF and Silverlight platforms
--------------------------------------
- a set of guidelines to code for an application
- Where did MVVM come from?
- What is MVVM?
- Components of MVVM ?
History:
- 2004 Martin Fowler - Presentation Model
- Separates a view from it's state and behavior
- Not dependent on specific UI Framework
- 2005 John Gossman unveiled the MVVM pattern
- Tailored for WPF and Silverlight platforms
Intent:
- Separate Concerns
- View
- View's state and Behavior
- Data
- Unit testing and UI testing
- Maintenance
- Extensibility
- Enables designer/developer workflow
- Take advantage of WPF/silverlight databinding --> Also supports input validation
Structure:
- View
- ViewModel
- Model
- Model :
- HAs no reference to the View or ViewModel
- Model can be represented by Domain specific objects
- Model can be represented as Data centric object (model is XML or data access layer)
- Model's purpose is to represent Data points
- ITs single purpose is to represnt datapoint
- View :
- May or Maynot have a reference to the ViewModel
- Doesnot have a reference to the Model
- It consists of only visual elements of display like buttons windowns and everything
- Responsible for showing and collection data to and from user.
- in silver light the data bindings are specified but the details are hidden from the UI.
- Binding the viewModel set by DataContext
- The ViewModel:
- Has a reference to the Model
- May or may not have a reference to the view
- Contains properties and commands and other abstratctions to make the communication easy between the view and the model.
- At minimum the view should implement the INotifyChanged interface because the ViewModel is bound to notify the view of a change.
- Although the ViewModel contains the state and the data for the UI is should have a UI control as a base object.
To Create the connection between the view and viewModel (Binding the view to ViewModel):
- Declaratively in XAML --> View first approach --> ViewModel as a resource --> Static resource on the View
- Cannot control instantiation
- Cannot pass parameter
- Imperatively in code
- The view model is assigned in the views code behing after the Initialization method
- View Model Locator --> Service Locator renamed for MVVM
- DataTemplates
- Inversion of Control
- Factory with Inversion of Control
- and more ..
Communication:
- Events
- Commands
- Execute
- CanExecute
Consequences
- Pro:
- Reduce Code behind
- Model doesnot need to change to support a view
- Designers design and coders code
- Reduces development time
- Multitargeting and project linking
-Con:
- Create more files
- Simple tasks can be complicated
- Lack of standardization
= Specific to WPF and Silverlight platforms
Prototype Pattern:
--------------------------------------
- Overview of the Prototype PAttern
- SPecify the kinds of objects to create using a prototypical instance and create new objects by
copying this prototype --> Cloning or Making a copy instead of newing the object up
- Its easier to make a copy of the object than going through the whole construction process this is why
this pattern is used.
- Problem 1: COnstruction cost of an object is expensive
- Problem 2: State is important copy the state.
- Problem 3: Hiding the constructor
- Prototype design --> Just implement a Icloneable Interface and while implementing Clone method return
MemberwiseClone()
- You can do a deep copy and shallow copy --> MemberwiseClone does only shallow copy is specified only at one
level
- Examples are present in javascript, javascript is a prototypical language. --> Structuring Javascript is a
course on pluralsight.
Friday, September 13, 2013
String.Intern Method
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
Definition taken from: http://msdn.microsoft.com/en-us/library/system.string.intern.aspx
Definition taken from: http://msdn.microsoft.com/en-us/library/system.string.intern.aspx
Tuesday, August 06, 2013
Service Stack : Solution to cross platform services
I have MSDN Magazine Reader 4 Android app which helps me read the latest msdn magazine.
I came across an article which talks about the ServiceStack, The article neatly and simply describes a brief POC on what can to be done with Service Stack.
Link to the article: http://msdn.microsoft.com/en-us/magazine/dn342871.aspx
To my surprise there's already a course on Pluralsight named: Using ServiceStack to Build APIs
Will go through the course soon and post my thoughts on that too.
Cheers!!
Dibyendu
I came across an article which talks about the ServiceStack, The article neatly and simply describes a brief POC on what can to be done with Service Stack.
Link to the article: http://msdn.microsoft.com/en-us/magazine/dn342871.aspx
To my surprise there's already a course on Pluralsight named: Using ServiceStack to Build APIs
Will go through the course soon and post my thoughts on that too.
Cheers!!
Dibyendu
Wednesday, July 10, 2013
Design Principle Learning
I am brushing up my fundamentals on SOLID principles, by going through the pluralsight course named: SOLID Principles of Object Oriented Design
The author of the course Steven Smith has done an amazing job here kudos to him.
Tell don't Ask:
Don't interrotgate objects for their internals -- move behavior to the object.
Tell the object what you want it to do.
Consider Refactoring to a new Base Class
- Given 2 classes share a lot of behavior refactor them to a base class
Interface segragation principle:
- Clients should not be forced to depend on methids they do not user.
- Prefer small, cohesive interfaces to fat interfaces
- Interface Segragation principle violations result in classses that depend on things they do not need,
increasing coupling and reducing flexibility and maintainability.
Smells:
- Unimplemented Interface methods
- Client references a class but only uses a portion of it.
- If you find yourself depending on a fat interface you own
- if you find fat interfaces are problematic but you don't own them
- Create a smaller interface with what you need
- Implement this interface using an adapter that implements the full interface.
Tips
Dependency Inversion Principle PART I:
- Highlevel modules should not depent on lowlevel modules. both should depend on abstractions.
- Abstractions should not depend on details rather details should depend on abstractions.
- What are the depdendencies ?
- Framework is a dependency, ohter dependencies are third party libraries, Database, File system, Email, Webservices, System Resources, configuration, the new keyword (this means direct dependency), Static methods, thread.sleep, Random(difficult to test if the code uses Random instead use a inteface to generate random so that during testing its possible to make sure that random returns the expected value by mocking and faking the objects)
- Classes dependencies should be honest
- Classes whose constructors make this clear are called as explicit dependencies
- Classes that do not have impplicit or hidden dependencies
- Classes should declare on what they need.
Dependency Injection : is a technique that is used to allow calling code to inject the dependencies a class needs when it is instantiated.
The hollywood principle: Don't call us; we'll call you.
The techniques:
1. Constructor Injection : Strategy Pattern
Pros:
- Classes self document on what they need to perform ofr their work
- Works well without a container
- Classes are always in a valid state once constructed
Cons:
- Constructors can have many parameters/dependencies
- Some features may require default constructor.(Serialization)
- Some methods in the calls may not require things other methods require but the constructor injection.
makes all the dependencies available for all the methods which is a design smell.
2. Property Injection: Setter Injection
Pros:
- Dependencies can be changed at any time during the lifetime of the object
- Very flexible
Cons:
- Objects may be in invalid state between the construction and seetion of dependencies via setters
- Less intuitive
3. Parameter Injection: dependencies are passed in via a method parameter
Pros:
- Most Granular
- very flexible
- Requires no change to the rest of the class
Cons:
- Breaks method signature
- Can result in many parameters
Consider if only one method has the dependency otherwise prefer constructor injection.
How to refactor to achieve dependency inversion principle;
- Extract dependencies to Interfaces
- Inject Implementaytion of interfaces into order
- Reduce Orders responsibility (apply SRP)
Design Smells which can be addressed via Dependency Inversion principle
- Use of new Keyword
- Use of Static method and properties
- Good way of using static method is the place where there is no dependency in the method apart from the parameters which are being passed
- static methods should not instantiate other classes which might have dependencies of their own then it becomes a problem.
Where do we instantiate the objects:
- Default Constructor
- Startup of the application or the main method of the application.
- Use an IOC container.
IOC Containers:
- Responsible for object graph instantiation
- Inititated at application startup via code or configuration
- Managed interfaces and the implementation to be used are Registered with the container
- Dependencies on interfaces are Resolved at application startup or runtime.
Dependency Inversion Principle PART II:
- Traditional application architecture follows the model where in we have UI --> BLL --> DAL
- The problem with such a design is that the dependencies flow towards the Infrastructure
- Core/Business/Domain classes depend on the Implementation details.
- This results in tight coupling
- No way to change implementation details without recompile(OCP violation)
- Difficult to test
- Dependencies is transitive
- If UI depends on BLL depends on DAL depends on DB. Then everything depends on database.
- Depend on abstraction
Don't Repeat Yourself :
- Every piece of knowledge must have a single, unambiguous representation in the system.
- Repetition of logic calls for abstraction. Repetition of process calls for automation.
- Once and only once
- Duplication is Evil
- Use of Magic strings
- Duplicate logic in multiple location
- Repeated if then logic in the code
- Applying DRY to remove magic string
- assign the magic string to a variable or in config file, this is just to avoid the repetition of value of connection string
- if then logic can be moved into a loop
Related fundamentals:
- Template method
- command pattern
- Depdendency Inversion principle
The author of the course Steven Smith has done an amazing job here kudos to him.
Tell don't Ask:
Don't interrotgate objects for their internals -- move behavior to the object.
Tell the object what you want it to do.
Consider Refactoring to a new Base Class
- Given 2 classes share a lot of behavior refactor them to a base class
Interface segragation principle:
- Clients should not be forced to depend on methids they do not user.
- Prefer small, cohesive interfaces to fat interfaces
- Interface Segragation principle violations result in classses that depend on things they do not need,
increasing coupling and reducing flexibility and maintainability.
Smells:
- Unimplemented Interface methods
- Client references a class but only uses a portion of it.
- If you find yourself depending on a fat interface you own
- if you find fat interfaces are problematic but you don't own them
- Create a smaller interface with what you need
- Implement this interface using an adapter that implements the full interface.
Tips
Dependency Inversion Principle PART I:
- Highlevel modules should not depent on lowlevel modules. both should depend on abstractions.
- Abstractions should not depend on details rather details should depend on abstractions.
- What are the depdendencies ?
- Framework is a dependency, ohter dependencies are third party libraries, Database, File system, Email, Webservices, System Resources, configuration, the new keyword (this means direct dependency), Static methods, thread.sleep, Random(difficult to test if the code uses Random instead use a inteface to generate random so that during testing its possible to make sure that random returns the expected value by mocking and faking the objects)
- Classes dependencies should be honest
- Classes whose constructors make this clear are called as explicit dependencies
- Classes that do not have impplicit or hidden dependencies
- Classes should declare on what they need.
Dependency Injection : is a technique that is used to allow calling code to inject the dependencies a class needs when it is instantiated.
The hollywood principle: Don't call us; we'll call you.
The techniques:
1. Constructor Injection : Strategy Pattern
Pros:
- Classes self document on what they need to perform ofr their work
- Works well without a container
- Classes are always in a valid state once constructed
Cons:
- Constructors can have many parameters/dependencies
- Some features may require default constructor.(Serialization)
- Some methods in the calls may not require things other methods require but the constructor injection.
makes all the dependencies available for all the methods which is a design smell.
2. Property Injection: Setter Injection
Pros:
- Dependencies can be changed at any time during the lifetime of the object
- Very flexible
Cons:
- Objects may be in invalid state between the construction and seetion of dependencies via setters
- Less intuitive
3. Parameter Injection: dependencies are passed in via a method parameter
Pros:
- Most Granular
- very flexible
- Requires no change to the rest of the class
Cons:
- Breaks method signature
- Can result in many parameters
Consider if only one method has the dependency otherwise prefer constructor injection.
How to refactor to achieve dependency inversion principle;
- Extract dependencies to Interfaces
- Inject Implementaytion of interfaces into order
- Reduce Orders responsibility (apply SRP)
Design Smells which can be addressed via Dependency Inversion principle
- Use of new Keyword
- Use of Static method and properties
- Good way of using static method is the place where there is no dependency in the method apart from the parameters which are being passed
- static methods should not instantiate other classes which might have dependencies of their own then it becomes a problem.
Where do we instantiate the objects:
- Default Constructor
- Startup of the application or the main method of the application.
- Use an IOC container.
IOC Containers:
- Responsible for object graph instantiation
- Inititated at application startup via code or configuration
- Managed interfaces and the implementation to be used are Registered with the container
- Dependencies on interfaces are Resolved at application startup or runtime.
Dependency Inversion Principle PART II:
- Traditional application architecture follows the model where in we have UI --> BLL --> DAL
- The problem with such a design is that the dependencies flow towards the Infrastructure
- Core/Business/Domain classes depend on the Implementation details.
- This results in tight coupling
- No way to change implementation details without recompile(OCP violation)
- Difficult to test
- Dependencies is transitive
- If UI depends on BLL depends on DAL depends on DB. Then everything depends on database.
- Depend on abstraction
Don't Repeat Yourself :
- Every piece of knowledge must have a single, unambiguous representation in the system.
- Repetition of logic calls for abstraction. Repetition of process calls for automation.
- Once and only once
- Duplication is Evil
- Use of Magic strings
- Duplicate logic in multiple location
- Repeated if then logic in the code
- Applying DRY to remove magic string
- assign the magic string to a variable or in config file, this is just to avoid the repetition of value of connection string
- if then logic can be moved into a loop
Related fundamentals:
- Template method
- command pattern
- Depdendency Inversion principle
Tuesday, April 16, 2013
WCF Message Tracing, Logging and Troubleshooting
Tracing Link on MSDN : http://msdn.microsoft.com/en-us/library/ms730342.aspx
For quick reference I have listed down some links below
For quick reference I have listed down some links below
- How to trace the messages, here's the link from MSDN: http://msdn.microsoft.com/en-us/library/ms751526.aspx
- The resulting trace file can be opened using the SvcTraceViewerTool.exe
- There is a useful guidance present for Using the SvcTraceViewerTool.exe and to see on how to use it for Troubleshooting and viewing Correlated traces at: http://msdn.microsoft.com/en-us/library/aa751795.aspx
Saturday, April 06, 2013
Javascript functions
@smashingmagFor JavaScript developers: A Deep Dive into JavaScript Functions -
http://markdaggett.com/blog/2013/02/15/functions-explained/
http://markdaggett.com/blog/2013/02/15/functions-explained/
Subscribe to:
Posts (Atom)