The Extract Method refactoring has the following limitations:
Refactoring does not work with multiple output values in automatic mode. You have to change your code before applying the refactoring.
Refactoring does not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.
before (eclipse)
public class ExtractMethod1 {
public static void main(String[] args) { method1(); }
static void method1() { int a=1; int b=2; int c=a+b; int d=a+c; }
}
after (eclipse)
public class ExtractMethod1 {
public static void main(String[] args) {
method1(); }
static void method1() { getSum(); }
private static void getSum() { int a=1; int b=2; int c=a+b; int d=a+c; }
}
In Eclipse you select the code fragment you want to refactor,right click,refactor and extract method
before (IntelliJ IDEA 11.1)
public class ExtractMethod1 {
public static void main(String[] args) { method1(); }
static void method1() { int a=1; int b=2; int c=a+b; int d=a+c; }
}
after (IntelliJ IDEA 11.1)
public class ExtractMethod1 {
public static void main(String[] args) { method1(); }
static void method1() { int a=1; int b=2; int c=add(a,b); int d=add(a,c); }
private static int add(int a,int b) { return a+b; }
}
before (IntelliJ IDEA 11.1)
ArrayList method2() { String[] strings={"a","b","c","d"}; ArrayList list=new ArrayList(); for (int i = 0; i < strings.length; i++) { list.add(strings[i]); } return list; }
}
after (IntelliJ IDEA 11.1)
private ArrayList add(String[] strings) { ArrayList list=new ArrayList(); for (int i = 0; i < strings.length; i++) { list.add(strings[i]); } return list; }
http://www.jetbrains.com/idea/webhelp/extract-method.html#h2example
Extract Method
The Extract Method refactoring allows you to select a block of code and convert it to a method. Eclipse automatically infers the method arguments and return types.
This is useful when a method is too big and you want to subdivide blocks of it into different methods. It is also useful if you have a piece of code that is reused across many methods. When you select one of those blocks of code and do a refactoring, Eclipse finds other occurrences of that block of code and replaces it with a call to the new method.
Listing 3. Before Extract Method refactoring
@Override public Object get(Object key) { TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key); Object object = map.get(timedKey);
if (object != null) { /** * if this was removed after the 'get' call by the worker thread * put it back in */ map.put(timedKey, object); return object; }
return null; }
Listing 4. After Before Extract Method refactoring
@Override public Object get(Object key) { TimedKey timedKey = new TimedKey(System.currentTimeMillis(), key); Object object = map.get(timedKey);
return putIfNotNull(timedKey, object); }
private Object putIfNotNull(TimedKey timedKey, Object object) { if (object != null) { /** * if this was removed after the 'get' call by the worker thread * put it back in */ map.put(timedKey, object); return object; }
Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.
The other usage of refactoring is the verb form
Refactor (verb): to restructure software by applying a series of refactorings without changing its observable behavior.
“Is refactoring just cleaning up code?” In a way the answer is yes, but I think refactoring goes further because it provides a technique for cleaning up code in a more efficient and controlled manner
the purpose of refactoring is to make the software easier to understand and modify.
Only changes made to make the software easier to understand are refactorings
Like refactoring, performance optimization does not usually change the behavior of a component (other than its speed); it only alters the internal structure
the purpose is different. Performance optimization often makes code harder to understand, but you need to do it to get the performance you need.
The software still carries out the same function that it did before
When you use refactoring to develop software, you divide your time between two distinct activities: adding function and refactoring
When you add function, you shouldn’t be changing existing code; you are just adding new capabilities. You can measure your progress by adding tests and getting the tests to work
When you refactor, you make a point of not adding function; you only restructure the code. You don’t add any tests (unless you find a case you missed earlier)
Why Should You Refactor?
The harder it is to see the design in the code, the harder it is to preserve it, and the more rapidly it decays. Regular refactoring helps code retain its shape.
By eliminating the duplicates, you ensure that the code says everything once and only once, which is the essence of good design.
Refactoring Makes Software Easier to Understand
Refactoring helps you to make your code more readable.
Ralph Johnson describes these early refactorings as wiping the dirt off a window so you can see beyond.
http://sourcemaking.com/refactoring/why-should-you-refactor
Refactoring Helps You Program Faster
When I talk about refactoring, people can easily see that it improves quality. Improving design, improving readability, reducing bugs, all these improve quality. But doesn’t all this reduce the speed of development?
the whole point of having a good design is to allow rapid development. Without a good design, you can progress quickly for a while, but soon the poor design starts to slow you down.
http://sourcemaking.com/refactoring/refactoring-helps-you-find-bugs
When Should You Refactor?
In my view refactoring is not an activity you set aside time to do. Refactoring is something you do all the time in little bursts
The Rule of Three
he first time you do something, you just do it.
The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway.
The third time you do something similar, you refactor.
Refactor When You Add Function
The most common time to refactor is when I want to add a new feature to some software
This code may have been written by someone else, or I may have written it
Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent
I look at the design and say to myself, “If only I’d designed the code this way, adding this feature would be easy.” In this case I don’t fret over my past misdeeds—I fix them by refactoring
Refactor When You Need to Fix a Bug
As I look at the code trying to understand it, I refactor to help improve my understanding.
if you do get a bug report, it’s a sign you need refactoring, because the code was not clear enough for you to see there was a bug
Refactor As You Do a Code Review
Reviews help more experienced developers pass knowledge to less experienced people
My code may look clear to me but not to my team.
This idea of active code review is taken to its limit with the Extreme Programming [Beck, XP] practice of Pair Programming
Why Refactoring Works
Kent Beck
Programs have two kinds of value: what they can do for you today and what they can do for you tomorrow. Most times when we are programming, we are focused on what we want the program to do today. Whether we are fixing a bug or adding a feature, we are making today’s program more valuable by making it more capable
If you can get today’s work done today, but you do it in such a way that you can’t possibly get tomorrow’s work done tomorrow, then you lose.
Changing Interfaces
Something that is disturbing about refactoring is that many of the refactorings do change an interface. Something as simple as Rename Method is all about changing an interface. So what does this do to the treasured notion of encapsulation?
You should also use the deprecation facility in Java to mark the code as deprecated. That way your callers will know that something is up.
A good example of this process is the Java collection classes. The new ones present in Java 2 supersede the ones that were originally provided
When Shouldn’t You Refactor?
There are times when you should not refactor at all. The principle example is when you should rewrite from scratch instead. There are times when the existing code is such a mess that although you could refactor it, it would be easier to start from the beginning.
The other time you should avoid refactoring is when you are close to a deadline. At that point the productivity gain from refactoring would appear after the deadline and thus be too late
In software engineering, don't repeat yourself (DRY) is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
1) Define Web Service? A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users.
3) Give me an example of real web service? Basically web services can be used with the help of SOAP, WSDL, and UDDI . All these, provide a plug-and-play interface for using web services such as stock-quote service, a traffic-report service, weather service etc.
7) Define SOAP?
SOAP is an XML based protocol to transfer between computers.
8) Define WSDL?
It means Web Services Description Language. It is basically the service description layer in the web service protocol stock. The Service Description layer describes the user interface to a web service.
17) Differentiate between a SOA and a Web service?
SOA is a design and architecture to implement other services. SOA can be easily implemented using various protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP, RPC etc. While Web service, itself is an implemented technology. In fact one can implement SOA using the web service.
23) What is REST?
REST stands for Representational State Transfer. REST itself is not a standard, while it uses various standards such as HTTP, URL, XML/HTML/GIF/JPEG (Resource Representations) and text/xml, text/html, image/gif, image/jpeg, etc (MIME Types).
25) Name the various communication channels in web service?
Web service is integrated with three protocols such as HTTP/POST, HTTP/GET, and SOAP. It provides three different communication channels to clients. Client can choose any communication method as per requirements.
29) Differentiate between web services, CORBA and DCOM?
Web services transfer/receive messages to/from application respectively, via HTTP protocol. It uses XML to encode data.
CORBA and DCOM transfer/receive messages to/from application respectively, via non-standard protocols such as IIOP and RPC.
31) Can you name some standards used in web services?
The standards used in web services are WSDL (used to create interface definition), SOAP (used to structure data), HTTP (communication channels), DISCO (used to create discovery documents) and UDDI (used to create business registries).
33) Explain in brief, what UDDI is?
UDDI (Universal Description, Discovery, and Integration) provides consolidated directory for web services on the internet. Clients use UDDI to find web services as per their business needs. It basically hosts the web services from various companies. In order to share web services, you need to publish it in UDDI.
40) What are the steps performed by the client to access a web service?
First of all a web reference to the web service is created by the client in his application. Then a proxy class is generated. After that an object of the proxy class is created and at last, the web service is accessed via that proxy object.
44) Brief few drawbacks of using GET and POST methods to communicate with the web service?
These methods are less secure and inhibit users to pass structures and objects as arguments. Also, it doesn’t allow users to pass ByRef arguments.
48) Can you name different kinds of web services?
There are two types of web services in total i.e. SOAP based web service and RESTful web service.
49) What’s different in RESTful web services?
The RESTful web services contains no contract or WSDL file.
50) Give me few reasons to use RESTful web service?
The RESTFul web services are simple to implement and test. It supports various data formats such as XML, JSON etc.
WSDL is an XML-based language for describing Web services and how to access them.
WSDL Describes Web Services
WSDL stands for Web Services Description Language.
WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.
http://www.w3schools.com/wsdl/wsdl_intro.asp
Does Web Service call is synchronous or asynchronous ?
An asynchronous web service allows a client to submit a request, process the request and respond to the client after a given time -- the client would not block all activity on receiving a response.
Comparatively, a web service that is synchronous would provide a client directly with a response, expecting the client to block all activity until a response is returned. In this case the web service would limit the client to process requests one at a time.
What is the difference between Java RMI and JMS?
RMI is a form of Remote Procedure Call (RPC). It is a lightweight, Java specific API that expects the caller and receiver to be available at the time of communication.
JMS is a reliable messaging subsystem. Messages can be passed even if one of the parties is not available. It is an alternative to things like MQSeries.
RMI doesn't deal with guaranteed delivery or asynchronous responses, JMS does.
difference between RMI, WebService, CORBA
RMI is Java's native method of invoking methods on objects that are located in a different JVM - Remote Method Invocation. It passes objects over the wire in binary, and can run either over the JRMP (Java Remote Method Protocol) or via IIOP (CORBA's Internet Inter-ORB Protocol)
CORBA is a language neutral remote method invocation protocol specified by the OMG standards group, and works with C/C++, Smalltalk, etc as well as with Java. CORBA laos sends data across the wire in binary format, and specifies interfaces in a scheme known as IDL (Interface Definition Language)
Web Services are remote invocations that are sent across the wire usually via SOAP (a flavour of XML data) over HTTP, but they can also go as SOAP/JMS, or other bindings - SMTP, etc
About inheritance In this article, I'll be talking about single inheritance through class extension, as in:
class Fruit {
//... }
class Apple extends Fruit {
//... }
In this simple example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this example, Fruit is the superclass and Apple is the subclass.
bout composition By composition, I simply mean using instance variables that are references to other objects. For example:
class Fruit {
//... }
class Apple {
private Fruit fruit = new Fruit(); //... }
In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object. In this example, Apple is what I will call the front-end class and Fruit is what I will call the back-end class. In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.
The composition alternative Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change cod
Inheritance is used to create a hierarchical-type code structure that tries to keep as much “common” code near the top of the hierarchy. In small, static systems, inheritance can be ok. But large inheritance chains can also lead to hard-to-maintain code design patterns that favor composition over inheritance for more info when to use inheritance and when not to.
Delegation is simply passing a duty off to someone/something else. Delegation is alternative to inheritance. Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.
It is better than inheritance because it makes you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class you can provide only the methods that really make sense. Delegation can also a powerful design/reuse technique. The primary advantage of delegation is run-time flexibility the delegate can easily be changed at run-time.
the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism.
Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object
Often the approach taken is based on the restriction in Java that a class can only extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:
using a factory method to get instances of a class (factory method pattern) storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (Multiton pattern, similar to the singleton pattern) using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).
Lazy initialization is a performance optimization.
if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary. since accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.
Lazy initialization has two objectives :
delay an expensive operation until it's absolutely necessary store the result of that expensive operation, such that you won't need to repeat it again
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.
A magic cookie that encapsulates a “check point” capability.
Promote undo or rollback to full object status.
Rules of thumb
Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
Command can use Memento to maintain the state required for an undo operation.
Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
http://sourcemaking.com/design_patterns/memento
Memento pattern
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
The memento pattern is implemented with two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.
Classic examples of the memento pattern include the seed of a pseudorandom number generator (it will always produce the same sequence thereafter when initialized with the seed state) and the state in a finite state machine.
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
Rules of thumb
Strategy is like Template Method except in its granularity.
Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
Factory Method is a specialization of Template Method.
http://sourcemaking.com/design_patterns/template_method
Template method pattern
the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure
http://en.wikipedia.org/wiki/Template_method_pattern
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
An object-oriented state machine
wrapper + polymorphic wrappee + collaboration
Example
The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.
Rules of thumb
State objects are often Singletons.
Flyweight explains when and how State objects can be shared.
Interpreter can use State to define parsing contexts.
Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.
http://sourcemaking.com/design_patterns/state
State pattern
The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime
http://en.wikipedia.org/wiki/State_pattern
a Null Object is an object with defined neutral ("null") behavior.
The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof).
Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.
For example, a function may retrieve a list of files in a directory and perform some action on each. In the case of an empty directory, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design.
By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.
The null object pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.
http://en.wikipedia.org/wiki/Null_Object_pattern
Rules of thumb
The Null Object class is often implemented as a Singleton. Since a null object usually does not have any state, its state can’t change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly.
If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface.
A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern or perhaps the Proxy pattern. In this case a Null State may be used or the proxy may hold a Null Object.
The use of a null object can be similar to that of a Proxy, but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.
A Null Object can be a special case of the Strategy pattern. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View’s Strategy for handling input, and NoController is the Strategy that ignores all input.
A Null Object can be a special case of the State pattern. Normally, each ConcreteState has some do nothing methods because they’re not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state.
A Null Object can be used to allow a Visitor to safely visit a hierarchy and handle the null situation.
Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Design an intermediary to decouple many peers.
Promote the many-to-many relationships between interacting peers to “full object status”.
Example
The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.
Rules of thumb
Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing “observer” and “subject” objects, whereas a Mediator object encapsulates the communication between other objects. We’ve found it easier to make reusable Observers and Subjects than to make reusable Mediators.
On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.
Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).
http://sourcemaking.com/design_patterns/mediator
Mediator pattern
The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.
http://en.wikipedia.org/wiki/Mediator_pattern
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.
Rules of thumb
Considered in its most general form (i.e. an operation distributed over a class hierarchy based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language.
Interpreter can use State to define parsing contexts.
The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.
Interpreter pattern
the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence
http://en.wikipedia.org/wiki/Interpreter_pattern
Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers.
Chain of Responsibility can use Command to represent requests as objects.
Chain of Responsibility is often applied in conjunction with Composite. There, a component’s parent can act as its successor
http://sourcemaking.com/design_patterns/chain_of_responsibility
Chain-of-responsibility pattern
the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
command pattern is a behavioural design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.
http://en.wikipedia.org/wiki/Command_pattern
Rules of thumb
Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Command normally specifies a sender-receiver connection with a subclass.
Chain of Responsibility can use Command to represent requests as objects.
Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
Command can use Memento to maintain the state required for an undo operation.
MacroCommands can be implemented with Composite.
A Command that must be copied before being placed on a history list acts as a Prototype.
Two important aspects of the Command pattern: interface separation (the invoker is isolated from the receiver), time separation (stores a ready-to-go processing request that’s to be stated later)
http://sourcemaking.com/design_patterns/command
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
The new operator considered harmful.
Rules of thumb
Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used properly. At other times they are complementory: Abstract Factory might store a set of Prototypes from which to clone and return product objects. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
Factory Method: creation through inheritance. Protoype: creation through delegation.
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.
Prototype co-opts one instance of a class for use as a breeder of all future instances.
Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. Object-oriented languages like Self and Omega that do away with classes completely rely on prototypes for creating new objects
http://sourcemaking.com/design_patterns/prototype
Prototype pattern
The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.
Problem
Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.
Example
Do you like bowling? If you do, you probably know that you should change your shoes when you getting the bowling club. Shoe shelf is wonderful example of Object Pool. Once you want to play, you’ll get your pair (aquireReusable) from it. After the game, you’ll return shoes back to the shelf (releaseReusable).
Rules of thumb
The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates.
Object Pools are usually implemented as Singletons.
The object pool pattern is a software creational design pattern that uses a set of initialised objects kept ready to use, rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object, which is a specific type of factory object, to the pool rather than destroying it
http://en.wikipedia.org/wiki/Object_pool_pattern
Object Pool Pattern
The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/objectpool.html
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Parse a complex representation, create one of several targets.
http://sourcemaking.com/design_patterns/builder
Builder pattern
he intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance with the composite pattern.
http://en.wikipedia.org/wiki/Builder_pattern
The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility. It reduces the number of class attributes by encapsulating them in single Data object. It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.
Consequences
The consequences of using this design pattern include the following:
Controlling write access to class attributes;
Separating of data from methods that use it;
Encapsulating class attribute (data) initialization; and
Providing new type of final: final after constructor.
Josh Bloch: I like to ask a candidate to solve a small-scale design problem, finger exercises, to see how they think and what their process is: "How would you write a function that tells me if its argument is a power of 2?" I'm not looking for the optimal bit-twiddling solution ((n & -n) == n). I'm looking to see if they get the method signature right, if they think about boundary cases, if their algorithm is reasonable and they can explain its workings, and if they can improve on their first attempt.
Hamming codes are used to insert error correction information into data streams. The codes are designed so that an error can not only be detected, but corrected. Adding error correction information increases the amount of data, but increases the reliability of communications over mediums with high error rates
Hamming distance of two bit strings = number of bit positions in which they differ
If the valid words of a code have minimum Hamming distance D, then D-1 bit errors can be detected.
If the valid words of a code have minimum Hamming distance D, then [(D-1)/2] bit errors can be corrected.
The Hamming Distance is a number used to denote the difference between two binary strings.
Hamming's formulas allow computers to detect and correct error on their own.
The Hamming Code earned Richard Hamming the Eduard Rheim Award of Achievement in Technology in 1996, two years before his death
Hamming's additions to information technology have been used in such innovations as modems and compact discs.
Step 1
Ensure the two strings are of equal length. The Hamming distance can
only be calculated between two strings of equal length. String 1: "1001
0010 1101" String 2: "1010 0010 0010"
Step 2
Compare the first two bits in each string. If they are the same, record a
"0" for that bit. If they are different, record a "1" for that bit. In
this case, the first bit of both strings is "1," so record a "0" for the
first bit.
Step 3
Compare each bit in succession and record either "1" or "0" as
appropriate. String 1: "1001 0010 1101" String 2: "1010 0010 0010"
Record: "0011 0000 1111"
Step 4
Add all the ones and zeros in the record together to obtain the Hamming distance. Hamming distance = 0+0+1+1+0+0+0+0+1+1+1+1 = 6
The Hamming Distance can be used to correct or detect errors in a transmission.
If there are d errors, you need a Hamming Distance of 2d+1 to correct or d+1 to detect.
Hamming distance between two vectors is the number of bits we must change to change one into the other.
Example Find the distance between the vectors 01101010 and 11011011.
01101010
11011011
They differ in four places, so the Hamming distance d(01101010; 11011011) = 4.
SYSVOL Replication Migration Guide: FRS to DFS Replication
Domain controllers use a special shared folder named SYSVOL to replicate logon scripts and Group Policy object files to other domain controllers. Windows 2000 Server and Windows Server 2003 use File Replication Service (FRS) to replicate SYSVOL, whereas Windows Server 2008 uses the newer DFS Replication service when in domains that use the Windows Server 2008 domain functional level, and FRS for domains that run older domain functional levels.
http://technet.microsoft.com/en-us/library/dd640019%28v=ws.10%29.aspx
Database mirroring is a solution for increasing the availability of a SQL Server database. Mirroring is implemented on a per-database basis and works only with databases that use the full recovery model.
automatic failover
The process by which, when the principal server becomes unavailable, the mirror server to take over the role of principal server and brings its copy of the database online as the principal database.
High-performance mode
The database mirroring session operates asynchronously and uses only the principal server and mirror server. The only form of role switching is forced service (with possible data loss).
High-safety mode
The database mirroring session operates synchronously and, optionally, uses a witness, as well as the principal server and mirror server.
mirror database
The copy of the database that is typically fully synchronized with the principal database.
principal database
In database mirroring, a read-write database whose transaction log records are applied to a read-only copy of the database (a mirror database).
Witness
For use only with high-safety mode, an optional instance of SQL Server that enables the mirror server to recognize when to initiate an automatic failover. Unlike the two failover partners, the witness does not serve the database. Supporting automatic failover is the only role of the witness.
Group Policy slow link detection
Defines a slow connection for purposes of applying and updating Group Policy.
If the rate at which data is transferred from the domain controller providing a policy update to the computers in this group is slower than the rate specified by this policy, the system considers the connection to be slow.
If you disable this policy or do not configure it, the system uses the default value of 500 kilobits per second.
Routing Information Protocol (RIP),
Open Shortest Path First (OSPF),
Enhanced Interior Gateway Protocol (EIGRP, Cisco proprietary protocol),
Intermediate System to Intermediate System (IS-IS).
Exterior Gateway Protocols (currently there is only one in use)
Once upon a time, when the Internet was just a tiny cloud, there were only a few networks connected to each other
All that needed to be done to set up routing was to define network nodes and make connections between them as needed.
As we all know, the Internet didn’t stay small for very long.
It began to incorporate more and more networks, which necessitated a more dynamic routing system.
EGP (External Gateway Protocol) was invented to do the job.
In modern networks, tree topologies were replaced by fully connected mesh topologies to allow for maximum scalability.
The Emergence of Autonomous System Architecture
As the Internet continued to expand, it became increasingly difficult to keep track of all the routes from one network to another.
The solution was to transition to an Autonomous System (AS) architecture
An AS can be an Internet Service Provider, a university or an entire corporate network, including multiple locations (IP addresses).
Each AS is represented by a unique number called an ASN.
each autonomous system controls a collection of connected routing prefixes, representing a range of IP addresses
It then determines the routing policy inside the network.
As the number of autonomous systems in the internet grew, the drawbacks of EGP became more pronounced.
Its hierarchical structure hampered scalability and made it difficult to connect new networks in an efficient manner.
it was necessary to define a new exterior routing protocol that would provide enhanced and more scalable capabilities.
BGP is Just Like GPS for Packets
You can think of an autonomous system in the computer world as a city with many streets. A network prefix is similar to one street with many houses. An IP address is like an address for a particular house in the real world, while a packet is the equivalent of a car travelling from one house to another using the best possible route.
BGP is designed to exchange routing and reachability information between autonomous systems on the Internet.
Each BGP speaker, which is called a “peer”, exchanges routing information with its neighboring peers in the form of network prefix announcements. This way, an AS doesn’t need to be connected to another AS to know its network prefix.
Each peer manages a table with all the routes it knows for each network and propagates that information to its neighboring autonomous systems.
In this way, BGP allows an AS to collect all the routing information from its neighboring autonomous systems and “advertise” that information further.
Each peer transfers the information internally inside its own autonomous system.
https://www.incapsula.com/blog/bgp-routing-explained.html
MicroNugget: What is BGP and How Does it Work?
The routing protocol of the internet
management of trust and untrust
the slowest routing protocol in the world
service providers use BGP,or enterprise level customers
Static routing
Static routes are one way we can communicate to remote networks. In production networks, static routes are mainly configured when routing from a particular network to a stub network.
stub networks are networks that can only be accessed through one point or one interface.
There are three routing table principles that dictate how routers communicate.
“routers forward packets based on information contained in their routing tables ONLY.”
” Routing information on one router does not mean that other routers in the domain have the same information.”
“Routes on a router to a remote network do not mean that the remote router has return paths.”
http://www.ccnablog.com/static-routing/
Dynamic routing protocols
Classification
Dynamic routing protocols can be classified in several ways.
Interior and exterior gateway routing protocols,
Distance vector, path vector and link state routing protocols,
Classful and classless.
Routing protocols function by:
Discovering remote networks
Maintaining current routing information
Path determination
Disadvantages
Require more expertise by the administrator, they are not as simple to configure as static routes.
They use more of the routers resources; such as CPU and RAM.
routing protocols fall into two main categories which are;
EGP – Exterior Gateway Protocols
IGP – Interior Gateway Protocols
Autonomous systems also known as routing domains; are collections of routers under the same administration. This may mean the routers that are owned by one company.
Interior Gateway Protocols (IGP) are used for intra-autonomous system routing – routing inside an autonomous system.
Exterior Gateway Protocols (EGP) are used for inter-autonomous system routing – routing between autonomous systems.
Egp vs igp
Interior Gateway Protocols (IGPs) can be classified as two types:
Distance vector routing protocols
Link-state routing protocols
Distance vector routing protocols vs. link state routing protocols
Distance vector protocols work best in situations where:
The network is simple and flat and does not require a special hierarchical design.
The administrators do not have enough knowledge to configure and troubleshoot link-state protocols.
Specific types of networks, such as hub-and-spoke networks, are being implemented.
Worst-case convergence times in a network are not a concern
Link state routing protocols usually have a complete view of the topology. They usually know of the best paths as well as backup paths to networks. Link state protocols use the shortest-path first algorithm to find the best path to a network.
Link-state protocols work best in situations where:
The network design is hierarchical, usually occurring in large networks.
The administrators have a good knowledge of the implemented link-state routing protocol.
Fast convergence of the network is crucial.
Classful and classless
Classful Routing Protocols
Since they do not include the subnet mask in their routing updates, they cannot work where the networks have been subnetted.
Classless routing protocols
Classless routing protocols include the subnet mask with the network address in routing updates.
Metric
The metric, is the mechanism used by the routing protocol to assign costs to reach remote networks
The metric is used to determine the best path to a network when there are multiple paths.
Administrative distance
The administrative distance is the way routers use to give preference to routing sources. For example if a router learns of the same route via EIGRP and RIP, it will prefer the route it learnt via EIGRP.
The AD is usually a value from 0 to 255, the lower the value the better the routing source, a route with an administrative distance of 255 will never be trusted.
To provide for fault tolerance, many networks implement redundant paths between devices using multiple switches. However, providing redundant paths between segments causes packets to be passed between the redundant paths endlessly. This condition is known as a bridging loop.
(Note: the terms bridge, switch are used interchangeably when discussing STP)
To prevent bridging loops, the IEEE 802.1d committee defined a standard called the spanning tree algorithm (STA), or spanning tree protocol (STP). Spanning-Tree Protocol is a link management protocol that provides path redundancy while preventing undesirable loops in the network. For an Ethernet network to function properly, only one active path can exist between two stations.
How Spanning Tree Protocol (STP) works
SPT must performs three steps to provide a loop-free network topology:
1. Elects one root bridge
2. Select one root port per nonroot bridge
3. Select one designated port on each network segment
when turned on, each switch claims itself as the root bridge immediately and starts sending out multicast frames called Bridge Protocol Data Units (BPDUs), which are used to exchange STP information between switches.
https://www.9tut.com/spanning-tree-protocol-stp-tutorial
Rapid Spanning Tree Protocol RSTP Tutorial
One big disadvantage of STP is the low convergence which is very important in switched network. To overcome this problem, in 2001, the IEEE with document 802.1w introduced an evolution of the Spanning Tree Protocol: Rapid Spanning Tree Protocol (RSTP), which significantly reduces the convergence time after a topology change occurs in the network. While STP can take 30 to 50 seconds to transit from a blocking state to a forwarding state, RSTP is typically able to respond less than 10 seconds of a physical link failure.
http://www.9tut.com/rapid-spanning-tree-protocol-rstp-tutorial
Ethernet Automatic Protection Switching Overview
Ethernet automatic protection switching (APS) is a linear protection scheme designed to protect VLAN based Ethernet networks.
With Ethernet APS, a protected domain is configured with two paths, a working path and a protection path. Both working and protection paths can be monitored using an Operations Administration Management (OAM) protocol like Connectivity Fault Management (CFM). Normally, traffic is carried on the working path (that is, the working path is the active path), and the protection path is disabled. If the working path fails, its protection status is marked as degraded (DG) and APS switches the traffic to the protection path, then the protection path becomes the active path.
https://www.juniper.net/documentation/en_US/junos/topics/concept/ethernet-automatic-protection-switching-overview.html
VRRP, the Virtual Router Redundancy Protocol, explained by Juniper Engineers
multicast IP packet
destination IP address is multicast not unicast, group of IPs,not a single IP
source IP address is unicast
IPv4 multicast address
all has first 3 bits set to 1
unlike unicast there is not a protocol to map IP addresses to MAC addresses
all multicast MAC addresses has last bit of first octet set to 1.
Open Standard means VRRP can be configured on any vendor
VRRP Roles
Master/Active
Backup/Standby
VRRP encapsulated in IP protocol No:112
VRRP supports two types of authentication; plaintext and MD5
VRRP MAC;0000.5e00.01XX ; XX is groupid
Quagga is a network routing software suite providing implementations of Open Shortest Path First (OSPF), Routing Information Protocol (RIP), Border Gateway Protocol (BGP) and IS-IS for Unix-like platforms, particularly Linux, Solaris, FreeBSD and NetBSD
https://en.wikipedia.org/wiki/Quagga_(software)
an autonomous system (AS) is a large network or group of networks that has a unified routing policy. Every computer or device that connects to the Internet is connected to an AS.
An autonomous system (AS) is a collection of routers under a common administration such as a company or an organization. An AS is also known as a routing domain. Typical examples of an AS are a company’s internal network and an ISP’s network.
What Does External Border Gateway Protocol (EBGP) Mean?
External Border Gateway Protocol (EBGP) is a Border Gateway Protocol (BGP) extension that is used for communication between distinct autonomous systems (AS). EBGP enables network connections between autonomous systems and autonomous systems implemented with BGP.
We need EBGP between AS1 and AS2 because these are two different autonomous systems. This allows us to advertise a prefix on R1 in BGP so that AS2 can learn it.
We also need EBGP between AS2 and AS3 so that R5 can learn prefixes through BGP.
So that’s the first reason why we need IBGP…so you can advertise a prefix from one autonomous system to another.
Border Gateway Protocol (BGP) is a standardized exterior gateway protocol designed to exchange routing and reachability information among autonomous systems (AS) on the Internet.[2] BGP is classified as a path-vector routing protocol,[3] and it makes routing decisions based on paths, network policies, or rule-sets configured by a network administrator.
BGP used for routing within an autonomous system is called Interior Border Gateway Protocol, Internal BGP (iBGP). In contrast, the Internet application of the protocol is called Exterior Border Gateway Protocol, External BGP (eBGP).
Spanning Tree Protocol (STP) is a communication protocol operating at data link layer the OSI model to prevent bridge loops and the resulting broadcast storms
In case a particular active link fails, the algorithm is executed again to find the minimal spanning tree without the failed link. The communication continues through the newly formed spanning tree. When a failed link is restored, the algorithm is re-run including the newly restored link.
By default Cisco Catalyst Switches run PVST+ or Rapid PVST+ (Per VLAN Spanning Tree). This means that each VLAN is mapped to a single spanning tree instance. When you have 20 VLANs, it means there are 20 instances of spanning tree.
MST works with the concept of regions. Switches that are configured to use MST need to find out if their neighbors are running MST.
Listening state: Only a root or designated port will move to the listening state. The non-designated port will stay in the blocking state.No data transmission occurs at this state for 15 seconds just to make sure the topology doesn’t change in the meantime. After the listening state we move to the learning state.
Learning state: At this moment the interface will process Ethernet frames by looking at the source MAC address to fill the mac-address-table. Ethernet frames however are not forwarded to the destination. It takes 15 seconds to move to the next state called the forwarding state.
Forwarding state: This is the final state of the interface and finally the interface will forward Ethernet frames so that we have data transmission!
With STP, the key is for all the switches in the network to elect a root bridge that becomes the focal point in the network. All other decisions in the network, such as which port to block and which port to put in forwarding mode, are made from the perspective of this root bridge. A switched environment, which is different from a bridge environment, most likely deals with multiple VLANs. When you implement a root bridge in a switching network, you usually refer to the root bridge as the root switch. Each VLAN must have its own root bridge because each VLAN is a separate broadcast domain
OSPF is an interior gateway protocol (IGP) that routes packets within a single autonomous system (AS). OSPF uses link-state information to make routing decisions, making route calculations using the shortest-path-first (SPF) algorithm (also referred to as the Dijkstra algorithm). Each router running OSPF floods link-state advertisements throughout the AS or area that contain information about that router’s attached interfaces and routing metrics.
This document describes the Open Shortest Path First Version 3 (OSPFv3) Autonomous System (AS) External Link State Advertisement (LSA) Type 5 route selection mechanism. It presents a network scenario with the configuration for how to select the route received from one Autonomous System Boundary Router (ASBR) over another.
MPLS operates at a layer that is generally considered to lie between traditional definitions of OSI Layer 2 (data link layer) and Layer 3 (network layer), and thus is often referred to as a layer 2.5 protocol
Why VPWS service - MPLS has a two ethernet frame headers?
the encapsulation is removed and the original frame is sent to the local network.
The outer label is used for switching within the MPLS tunnel. The inner label is ignored while in the tunnel - currently, it's just payload to transport.
Once the encapsulated payload reaches the destination network, the encapsulation is removed and the original frame continues on as before the tunnel.
As packets travel through the MPLS network, their labels are switched or swapped.
The packet enters the edge of the MPLS backbone, is examined, classified and given an appropriate label, and forwarded to the next hop in the pre-set Label Switched Path (LSP). As the packet travels that path, each router on the path uses the label – not other information, such as the IP header – to make the forwarding decision that keeps the packet moving along the LSP.
However, within each router, the incoming label is examined and its next hop is matched with a new label. The old label is replaced with the new label for the packet’s next destination, and then the freshly labeled packet is sent to the next router. Each router repeats the process until the packet reaches an egress router.
The label information is removed at either the last hop or the exit router, so that the packet goes back to being identified by an IP header instead of an MPLS label.
When an IP packet arrives at a router (Rosen et al., 2001) the next hop for this packet is determined by the routing algorithm in operation, which uses the longest prefix match
“Border Gateway Protocol (BGP) is a standardized exterior gateway protocol designed to exchange routing and reachability information between autonomous systems (AS) on the Internet.
While processing the header, the router compares the destination IP address, bit-by-bit, with the entries in the routing table.
The entry that has the longest number of network bits that match the IP destination address is always the best match (or best path) as shown in the following example:
A switch dynamically builds its MAC address table by examining the source MAC addresses of the frames received on a port. The switch forwards frames by searching for a match between the destination MAC address in a frame and an entry in the MAC address table.
If the destination IP address and the subnet mask do not match, the entries in the routing table are compared to the destination IP address. If a match is found (i.e., the destination IP address and the subnet mask AND to a value found in the routing table), the packet is sent to the gateway listed in the routing table. If no matching entries can be found, the packet is sent to the defined default gateway
A switching loop or bridge loop occurs in computer networks when there is more than one Layer 2 (OSI model) path between two endpoints (e.g. multiple connections between two network switches or two ports on the same switch connected to each other). The loop creates broadcast storms as broadcasts and multicasts are forwarded by switches out every port, the switch or switches will repeatedly rebroadcast the broadcast messages flooding the network. Since the Layer 2 header does not support a time to live (TTL) value, if a frame is sent into a looped topology, it can loop forever
How do I stop a network loop?
A physical topology that contains switching or bridge loops is attractive for redundancy reasons, yet a switched network must not have loops. The solution is to allow physical loops, but create a loop-free logical topology using the shortest path bridging (SPB) protocol or the older spanning tree protocols (STP) on the network switches
A switching loop or bridge loop occurs in computer networks when there is more than one layer 2 path between two endpoints (e.g. multiple connections between two network switches or two ports on the same switch connected to each other). The loop creates broadcast storms as broadcasts and multicasts are forwarded by switches out every port, the switch or switches will repeatedly rebroadcast the broadcast messages flooding the network.[1] Since the layer-2 header does not include a time to live (TTL) field, if a frame is sent into a looped topology, it can loop forever.
A physical topology that contains switching or bridge loops is attractive for redundancy reasons, yet a switched network must not have loops. The solution is to allow physical loops, but create a loop-free logical topology using link aggregation, shortest path bridging, spanning tree protocol or TRILL on the network switches.
Routing loops are tempered by a time to live (TTL) field in layer-3 packet header; Packets will circulate the routing loop until their TTL value expires. No TTL concept exists at layer 2 and packets in a switching loop will circulate until dropped, e.g. due to resource exhaustion.
https://en.wikipedia.org/wiki/Switching_loop
Broadcast storm
Most commonly the cause is a switching loop in the Ethernet network topology (i.e. two or more paths exist between switches). As broadcasts and multicasts are forwarded by switches out of every port, the switch or switches will repeatedly rebroadcast broadcast messages and flood the network. Since the layer-2 header does not support a time to live (TTL) value, if a frame is sent into a looped topology, it can loop forever.
In some cases, a broadcast storm can be instigated for the purpose of a denial of service (DOS) using one of the packet amplification attacks, such as the smurf attack or fraggle attack, where an attacker sends a large amount of ICMP Echo Requests (ping) traffic to a broadcast address, with each ICMP Echo packet containing the spoof source address of the victim host
In wireless networks a disassociation packet spoofed with the source to that of the wireless access point and sent to the broadcast address can generate a disassociation broadcast DOS attack
Prevention
Switching loops are largely addressed through link aggregation, shortest path bridging or spanning tree protocol. In Metro Ethernet rings it is prevented using the Ethernet Ring Protection Switching (ERPS) or Ethernet Automatic Protection System (EAPS) protocols.
Filtering broadcasts by Layer 3 equipment, typically routers (and even switches that employ advanced filtering called brouters).
Physically segmenting the broadcast domains using routers at Layer 3 (or logically with VLANs at Layer 2) in the same fashion switches decrease the size of collision domains at Layer 2.
Routers and firewalls can be configured to detect and prevent maliciously inducted broadcast storms (e.g. due to a magnification attack).
Broadcast storm control is a feature of many managed switches in which the switch intentionally ceases to forward all broadcast traffic if the bandwidth consumed by incoming broadcast frames exceeds a designated threshold. Although this does not resolve the root broadcast storm problem, it limits broadcast storm intensity and thus allows a network manager to communicate with network equipment to diagnose and resolve the root problem.