fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,22 @@
---
title: Code Coverage
---
## Code Coverage
When you run automated tests on software to find bugs, **code coverage** is a measurement of how much of the code you are testing is actually executed during the tests.
Code that has not been executed during testing has, by definition, not been tested, and so may contain bugs. So generally speaking, the higher code coverage reported by the test suite, the less chance there is of bugs going unnoticed.
This is not to say that 100% code coverage means 0% chance of bugs, however! It's easy to imagine a situation in which all the available functions in a piece of code are called, but not not necessarily with inputs representing all the kinds of scenarios you might expect from real users.
The ins and outs of how code coverage will not be of much interest until you are actually using automated testing and trying to ensure you are doing it effectively.
#### More information
[Wikipedia - code coverage](https://en.wikipedia.org/wiki/Code_coverage)
[freeCodeCamp Guide - Test Driven Development](https://guide.freecodecamp.org/agile/test-driven-development)
[freeCodeCamp Guide - Unit Tests](https://guide.freecodecamp.org/software-engineering/unit-tests)
[freeCodeCamp Guide - Continuous Integration](https://guide.freecodecamp.org/agile/continuous-integration)

View File

@@ -0,0 +1,70 @@
---
title: Builder
---
The builder is a design pattern that could abstract and decouple the creation of a very complex object.
## Builder in Python
Here is an example of Builder Pattern implementation in Python3.
```python
# Builder
class CourseBuilder(object):
def __init__(self, teacher):
self.teacher = teacher
def build_course(self):
self.teacher.provide_homework()
self.teacher.provide_exam()
return self.teacher.course
# Teacher
class Teacher(object):
def __init__(self, name=None):
self.name = name
self.course = Course()
def provide_homework(self):
raise NotImplementedError
def provide_exam(self):
raise NotImplementedError
class MathTeacher(Teacher):
def provide_homework(self):
self.course.homework = 'This is Math homework provided by {}.'.format(self.name)
def provide_exam(self):
self.course.exam = 'This is Math exam tested by {}.'.format(self.name)
class HistoryTeacher(Teacher):
def provide_homework(self):
self.course.homework = 'This is History homework provided by {}.'.format(self.name)
def provide_exam(self):
self.course.exam = 'This is History exam tested by {}.'.format(self.name)
# Target objects to be produced
class Course(object):
def __init__(self):
self.homework = None
self.exam = None
def __str__(self):
return 'Homework: {}\nExam: {}\n'.format(self.homework, self.exam)
math_course = CourseBuilder(MathTeacher('Harry')).build_course()
print(math_course)
>>> Homework: This is Math homework provided by Harry.
>>> Exam: This is Math exam tested by Harry.
history_course = CourseBuilder(HistoryTeacher('Potter')).build_course()
print(history_course)
>>> Homework: This is History homework provided by Potter.
>>> Exam: This is History exam tested by Potter.
```

View File

@@ -0,0 +1,40 @@
---
title: Decorator
---
The decorator is a design pattern that could modify or enhance the interface of a class.
## Decorator in Python3
Here is an example of Decorator implementation in Python3.
```python
class MyText(object):
def __init__(self, text=''):
self.text = text
def __str__(self):
return 'This is {}'.format(self.text)
class BracketDecorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def __str__(self):
return '({})'.format(self._decoratee)
class QuoteDecorator(object):
def __init__(self, decoratee):
self._decoratee = decoratee
def __str__(self):
return '\"{}\"'.format(self._decoratee)
print(BracketDecorator(MyText('apple')))
>>> (This is apple)
print(QuoteDecorator(MyText('banana')))
>>> "This is banana"
```

View File

@@ -0,0 +1,15 @@
---
title: Factory Method
---
## Factory Method
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/machine-learning/monte-carlo/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -0,0 +1,103 @@
---
title: Factory
---
The factory is a design pattern which aims to reduce the dependencies between classes instantiating (creating) objects and the objects themselves, by creating a "factory" class which handles the creation of classes. By doing this, we allow can allow subclasses to redefine which class to instantiate, and group potentially complex creation logic into a single interface.
Programmers use factory design patterns to because it allows them to create instances of objects which implement a common interface, without necessarily knowing beforehand the exact concrete class (implementation) being used. A common situation in which this is useful is when a parent class is relying on it's children classes to specify the type of object it should be instantiating. It is also useful when the creation of an object is complex, as it allows the programmer to group the code into a single class and reduce duplication.
## Using the Factory Pattern in Java
To use the factory design pattern, you first need to have a interface - an object with class and variable names, but no definitions. For example, here we have a Java interface for animals.
```
public interface Animal {
void talk();
}
```
We now need to have "concrete classes" - classes which implement our interface and define the associated functions/ variables.
```
public class Dog implements Animal {
@Override
public void talk() {
System.out.println("Woof");
}
}
```
```
public class Cat implements Animal {
@Override
public void talk() {
System.out.println("Meow!");
}
}
```
We now define our "AnimalFactory" - the class which will handle the creation of these classes.
```
public class AnimalFactory {
public Animal getAnimal(String animalType) {
if (animalType.equals("dog")) {
return new Dog();
} else if (animalType.equals("cat")) {
return new Cat();
}
return null;
}
}
```
Now when we want to create a new Cat object, instead of saying something like ``` Cat cat = new Cat(); ```, we use the factory class that we have defined. For example:
```
AnimalFactory animalFactory = new AnimalFactory();
Animal cat = animalFactory.getAnimal("cat");
cat.talk();
```
Here we can see that the class with this instance of "Cat" doesn't really know which animal it has. But this doesn't matter - because all the classes the factory creates are concrete classes of the same interface, the parent class doesn't need to know the exact class it is using.
## Factory in Python3
We can implement a Factory easily with static methods.
```python
class Drink(object):
def __init__(self, name, price=None):
self.name = name
self.price = price
class Tea(Drink):
def __str__(self):
return 'This is tea: {} in ${}'.format(self.name, self.price)
class Milk(Drink):
def __str__(self):
return 'This is milk: {} in ${}'.format(self.name, self.price)
class DrinkFactory(object):
@staticmethod
def generate(drink_type=None, *args, **kwargs):
if drink_type == 'tea':
return Tea(*args, **kwargs)
elif drink_type == 'milk':
return Milk(*args, **kwargs)
raise NotImplementedError("{} drink do not exist.".format(drink_type))
# Testing
black_tea = DrinkFactory.generate('tea', 'Black Tea', price=4.39)
whole_milk = DrinkFactory.generate('milk', 'Whole Milk', price=5.49)
print(black_tea)
print(whole_milk)
```

View File

@@ -0,0 +1,65 @@
---
title: Finite State Machine
---
The finite state machine (FSM) is a software design pattern where a given model transitions to other behavioral states through external input.
## Finite State Machine
A FSM is defined by its **states**, it's **initial state** and the **transitions**.
The power of FSM comes from the ability to clearly define different *behaviors* in different conditions. Usually FSM is used with looping behavioral scripts which constantly evaluate the current situation in a loop or with events.
To help form an image of how this might be applied, a coffee machine will be used as an example of a finite state machine. We will also cover a state diagram to visualise the FSM and provide coding examples.
### State Diagram
![Coffee machine finite state machine diagram](https://raw.githubusercontent.com/arunma/blogimages/master/AkkaFSM/CoffeeMachineFSM.png)
This diagram shows three possible states for the coffee machine:
- Open
- ReadyToBuy
- PoweredOff
The lines between these states show which transitions are possible between states and in which direction. These transitions have conditions for when the FSM needs to change between states.
- StartUpMachine
From the PoweredOff state to the Open state the machine has to start up. This is done manually in this case.
- deposit >= cost of coffee
The FSM evaluates the amount of deposited cash either in a loop or when the amount changes (recommended in this case)
If you deposit enough cash into the coffee machine, the FSM will go from 'Open' to 'ReadyToBuy'.
- ShutdownMachine
The machine will automatically go from Open to PoweredOff through the ShutDownMachine method if the condition 'no more coffees left' is met.
- DispenseCoffee
In the ReadyToBuy state the user can buy a coffee whereafter it will be brewed and dispensed. The condition is when the BuyCoffee event (!Link to observer pattern!) fires. (not shown in diagram)
- CancelCoffee
If the user opts to cancel, the machine will go from ReadyToBuy to Open.
- ShutDownMachine
The machine will go to PoweredOff state
### States
In every state there is defined behavior which will only be executed when the object is in that state. For instance, during PoweredOff the coffee machine won't brew coffee before it's powered on, during the Open state it will wait either until there's enough cash inserted, until the power down command is given, or until it runs out of coffee. During this Open state it can do routines such as cleaning which won't happen in other states.
### Initial State
Every FSM has an initial state, this means which state it starts in when it is created and has to be defined when constructed or instantiated. Of course it's possible to directly change state if conditions are met.
### Transitions
Every state either constantly evaluates if it should transition to another state or will transition to another state based on a triggered event.
## DFA and NFA
There are two types of finite automaton, Deterministic (DFA) and Nondeterministic (NFA). Both of them accept regular languages and operate more or less in the same way described above however with some differences.
A DFA accepts or rejects a string of symbols and only produces one unique computation or automaton for each input string. <i>Deterministic</i> refers to the uniquness of the computation.
A Finite State Machine is called a DFA if it obeys the following rules:
1. Each of its transitions is <i>uniquely</i> determined by its source state and input symbol
2. Reading an input symbol is required for each state transition.
An NFA does not need to obey these restrictions, meaning that each DFA is also an NFA.
And since they both only recognize regular languages, each NFA can be converted into an equivalent DFA using the powerset construction algorithm.
So what sort of rules can we expect to find in NFAs but not DFAs ?
1. An NFA can have an <i>empty string</i> transition (generally denoted by an epsilon). Meaning that when at a certain state with an epsilon for a transition rule, the machine can transition to the next state without reading an input symbol
2. In an NFA, each pair of state and transition symbol can have multiple destination states as opposed to the unique destinations of pairs in DFAs
3. Each pair of state and transition symbol produces a 'branch' of computation for each of its possible destination creating some sort of a multithreaded system.
4. A DFA will reject the input string if it lands on any state other than the acceptance state. In an NFA, we only need one 'branch' to land on an acceptance state in order to accept the string.

View File

@@ -0,0 +1,48 @@
---
title: Design Patterns
---
## Design Patterns
Programmers and software architects use design patterns to solve **common, recurring problems** in software architecture. The patterns provide a language-agnostic approach to **object-oriented programming** that helps developers follow principles of good application design.
### Why Design Patterns?
Developing by design patterns offer several advantages:
* It's easier to follow good programming principles such as the **<a href='https://www.youtube.com/watch?v=XzdhzyAukMM' target='_blank' rel='nofollow'>SOLID</a> <a href='https://medium.com/@cramirez92/s-o-l-i-d-the-first-5-priciples-of-object-oriented-design-with-javascript-790f6ac9b9fa' target='_blank' rel='nofollow'>principles</a>.**
* It keeps code chunks smaller so code is easier to **test** and **debug**
* It helps keep code loosely coupled so code is easier to **re-use** and **update** for new applications
* It makes code easier to **understand**, so new contributors can **ramp up quickly**
Using design patterns incurs some trade-offs, and developers new to the practice should remember the following:
* There are **no silver bullets** in programming, and design patterns are not an exception
* Design patterns add a **layer of abstraction** to code which increases initial design and development effort
* Over-use of design patterns or forcing them to fit makes code **harder** to understand
### Language Support
Design patterns originated from the world of statically-typed languages like C++, Java, and C#. Most resources about development by design pattern are based in one of these languages.
Nonetheless, design patterns are just that: patterns. They are **not implementations**, like classes or interfaces, and are **not constrained to any one language**.
When learning design patterns within a dynamic language, if particular patterns seem needlessly complex or counter-intuitive, recall their origins. Developers in dynamic languages can still use and benefit from following design patterns, although more research may be required to fully understand them.
### Uses
Design patterns are excellent at solving foundational coding problems in a simple and repeatable fashion. Broadly, they fall into three categories:
* **Creational** patterns describe how to create new objects
* **Structural** patterns describe how to compose objects out of other objects
* **Behavioral** patterns describe how objects communicate with each other
These tasks can all be performed without design patterns, but design patterns **reduce the risk** that you will violate good practices and create code that is hard to maintain.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* Kamran Ahmed's <a href='https://github.com/kamranahmedse/design-patterns-for-humans' target='_blank' rel='nofollow'>Design Patterns for Humans</a> is an excellent introduction to the specific patterns
* <a href='https://en.wikipedia.org/wiki/Design_Patterns' target='_blank' rel='nofollow'>Design Patterns</a> is the book that started this practice
* Martin Fowler's <a href='https://martinfowler.com/eaaCatalog/' target='_blank' rel='nofollow'>Patterns of Enterprise Application Architecture</a> provide a suite of more sophisticated patterns for enterprise applications
* Sourcemaking provides an <a href='https://sourcemaking.com/design_patterns' target='_blank' rel='nofollow'>online resource</a> with additional examples and information about design patterns

View File

@@ -0,0 +1,12 @@
---
title: Observer pattern
---
The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs.
## Observer pattern
This pattern is the basis of event-driven programming. In Front End Development this is an essential pattern to sturdily scale your application logic. In this pattern, you make a difference between the **subject** and the **observers**. The subjects are the events themselves such as a _click_, a _keypress_ or a signal from the server. All subscribed **observers** are notified when a subject changes state (when an event fires). For more information on events read here [Evenet Driven Programming](https://www.technologyuk.net/software-development/designing-software/event-driven-programming.shtml)
### Subscribing
The advantage of this pattern is having a collection of subscribed objects that will respond to an event instead of calling a function on every object that should be notified. Another advantage is that observers are subscribed through an interface, which allows changes to the event function to be only within the function.
## Other resources
A code example & more at [Observer Design Pattern](http://www.dofactory.com/javascript/observer-design-pattern)

View File

@@ -0,0 +1,152 @@
---
title: Singleton
---
The singleton is a design pattern that restricts the instantiation of a class to one object. It is useful when you want to give only one object the ability to coordinate actions across your application.
## Singleton in Android
Singleton is a design pattern often used in Android. It is easily misused and so can cause app to be hard to maintain. It is useful in Android because they live across fragments, activities, and rotations.
- Singletons are often used in Android to store temporary data
- They allow the application to have one owner of the data and provides an easy way to pass data between controller classes
- Singletons are destroyed when Android removes your app from memory
- Singletons can make it difficult to unit test your app
```java
public class DataStore {
private static DataStore sDataStore;
private List<Data> mData;
public static DataStore get(Context context) {
if (sDataStore == null) {
sDataStore = new DataStore(context);
}
return sDataStore;
}
// Make constructor private to prevent other classes from creating a DataStore instance
private DataStore(Context context) {
mData = new ArrayList<>();
}
// The only way for other classes to get data from DataStore
public List<Data> getData() {
return mData;
}
}
```
## Singleton in PHP
> A private constructor is used to prevent the direct creation of objects from the class.
> The only way to create an instance from the class is by using a static method that creates the object only if it wasn't already created.
```php
Class Singleton {
// Hold the class instance
private static $instance = null;
/**
* The constructor is private
* it is ensure the class can be initialized only from itself
*/
private function __construct(){}
/**
* Return the singleton instance of this class
*
* @return Singleton
*/
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new Singleton();
}
return self::$instance;
}
}
$obj1 = Singleton::getInstance();
$obj2 = Singleton::getInstance();
```
## Singleton in C#
The most elegant, simple and highly performant version of the pattern using [System.Lazy\<T\>](http://msdn.microsoft.com/en-us/library/dd642331.aspx) type from .NET 4.0 or higher.
```csharp
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
```
## Singleton in Python3
We can use metaclass to implement Singleton in Python3.
```python
class Singleton(type):
# Mapping from a class to its singleton instance
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in Singleton._instances:
Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return Singleton._instances[cls]
class MyClass(metaclass=Singleton):
pass
```
### Testing
```python
obj_0 = MyClass()
obj_1 = MyClass()
In [2]: obj_0
Out[2]: <__main__.MyClass at 0x111130da0>
In [3]: obj_1
Out[3]: <__main__.MyClass at 0x111130da0>
```
## Singleton in iOS
```Swift4
class Singleton {
static let sharedInstance = Singleton()
init() {
print("Singleton has been initialized")
}
//write your functions here
func sampleFunction() {
}
}
//Uses
Singleton.sharedInstance.sampleFunction()
```
This simple code is all there to implement a singleton design pattern in iOS using Swift. We put `static` because it is a type property, and its functionality is to create only one instance of an object and prevents its methods from being overridden. Using `let` will guarantee that sharedInstance's value will not change.
An important thing to note is that `static` properties and methods are lazy initialize by default meaning that it will not be instantiated until it is being called, therefore it provides some optimization.
## More Information
For more information, visit the following links:
- [MSDN: Implementing Singleton in C#](https://msdn.microsoft.com/en-us/library/ff650316.aspx)
- [C# in Depth. Implementing the Singleton Pattern in C#](http://csharpindepth.com/Articles/General/Singleton.aspx)

View File

@@ -0,0 +1,42 @@
---
title: Functional Programming
---
## Functional Programming
Functional programming is the process of building software by composing **pure functions**, avoiding **shared state**, **mutable data**, and **side-effects**. Functional programming is **declarative** (telling the computer what you want to do) rather than **imperative** (telling the computer exactly how to do that), and application state flows through pure functions. Contrast it with object-oriented programming, where application state is usually shared and co-located with methods in objects.
### Why Functional Programming?
* It's generally more concise
* It's generally more predictable
* It's easier to test than object-oriented code
### Adoption by Programing Languages
Many programming languages support functional programming like Haskell, F#, Common Lisp, Clojure, Erlang, OCaml. JavaScript also has the properties of an untyped functional language.
### Uses
Functional programming has long been popular in academia, but with few industrial applications. However, recently several prominent functional programming languages have been used in commercial or industrial systems. For example, the Erlang programming language, which was developed by the Swedish company Ericsson in the late 1980s, is used for building a range of applications at companies such as T-Mobile, Nortel, Facebook, Électricité de France and WhatsApp.
### Higher-Order Functions
Higher-order functions are a big part of functional programming. A higher-order function is a function that either takes a function(s) as a parameter or returns a function.
### Map
`map` is a higher-order function that calls a function to each element of a list, and returns the results as a *new* list.
Here is an example of `map`:
```javascript
const myList = [6, 3, 5, 29];
let squares = myList.map(num => num * num); // [36, 9, 25, 841]
```
### More Information:
* [Wikipedia - Functional Programming](https://en.wikipedia.org/wiki/Functional_programming#Use_in_industry)
* [KeyCDN - Functional Programming What Is It and Why Does It Matter?](https://www.keycdn.com/blog/functional-programming/)
* [Medium - What is Functional Programming?](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0)

View File

@@ -0,0 +1,24 @@
---
title: Software Engineering
---
## Software Engineering
The field of **software engineering** is the study of techniques and strategies in order to efficiently manage the entire life cycle of software development.
If you are writing just scripts that might be used once or twice, implementing software engineering principles may be too involved. However, as software projects get larger and foresee future ongoing use, principles of software engineering become increasingly important.
The entire life cycle of software development ranges from the creation of ideas and design of the software to maintenance of the developed software over time.
You might think of software engineering as just how do you code up something and keep it going. However, an important aspect of software engineering you might not think about is the ethical practice of software development.
In this age where software can be used maliciously to steal information or do harm if software is implemented incorrectly, software engineers (or practitioners) must be aware of their duties to ethically develop software.
### More Information:
- <a href='http://iansommerville.com/software-engineering-book/' target='_blank' rel='nofollow'>Software Engineering 10th Ed. by Sommerville</a> - website companion to the book with slide decks for each chapter
- <a href='https://www.computer.org/web/swebok' target='_blank' rel='nofollow'>The Guide to the Software Engineering Body of Knowledge</a>
- <a href='http://www.se-radio.net/' target='_blank' rel='nofollow'>Software Engineering Radio</a> - podcast for professional software developers
- <a href='https://softwareengineeringdaily.com/' target='_blank' rel='nofollow'>Software Engineering Daily</a>
- <a href='https://github.com/kilimchoi/engineering-blogs' target='_blank' rel='nofollow'>Curated List of Engineering Blogs</a>
- <a href='http://www.acm.org/about/se-code' target='_blank' rel='nofollow'>Software Engineering Code of Ethics and Professional Practice</a>
- <a href='https://en.wikipedia.org/wiki/Software_engineering' rel='nofollow'>Wikipedia Article</a>

View File

@@ -0,0 +1,22 @@
---
title: The Iron Triangle, or "Pick Two"
---
# The Iron Triangle, or "Pick Two"
Software development is a series of tradeoffs between features implemented, the quality of the features, and how long it takes to produce.
But, no matter how much effort is put in, one cannot sustainably maximize all three of these without increasing the cost of the project.
For software development, often cost is directly related to the number of people assigned to and working on a project.
This concept is often summed up as "Pick Two: Quality, Speed, Features".
This relationship between quality, features, speed, and cost is illustrated by imagining a triangle with a fixed volume
with the volume being quality.
One can increase speed to implement and the features, but quality will suffer if cost is unchanged,
keeping the volume of the triangle the same.
Frequently cost is assumed to be constant because in most cases the cost is fixed and there is no budget to add more people
nor are there people available for transfer from other projects.
![Illustration of Iron Triangle with Scope, Resources, Schedule, and Quality](http://www.ambysoft.com/artwork/ironTriangle.jpg)
----
## Sources:
* [The Broken Iron Triangle Anti-Pattern](http://www.ambysoft.com/essays/brokenTriangle.html) Classic essay by [Scott Ambler](https://en.wikipedia.org/wiki/Scott_Ambler)

View File

@@ -0,0 +1,35 @@
---
title: Orthogonality
---
## Orthogonality
In software engineering, a system is considered orthogonal if changing one of its components changes the state of that component only. For instance, consider a program with three variables: a, b, and c. Changing the value of a, should not change the value of b, or c, provided they are independent. This property is particularly critical in debugging a program since one relies on narrowing down the number of moving parts of a program to identify the root cause of the problem.
See the following quote from Eric S. Raymond's "Art of UNIX programming"
> Orthogonality is one of the most important properties that can help make even complex designs compact. In a purely orthogonal design, operations do not have side effects; each action (whether it's an API call, a macro invocation, or a language operation) changes just one thing without affecting others. There is one and only one way to change each property of whatever system you are controlling.
Orthogonality is a software design principle for writing components in a way that changing one component doesn't affect other components. It is the combination of two other principles, namely strong cohesion and loose coupling.
Orthogonality is a term borrowed from mathematics. For example, two lines are orthogonal if they are perpendicular. In software design, two components are orthogonal if a change in one does not affect the other.
Applying this concept to classes or other sections of code results in less coupling. To be orthogonal two classes cannot depend on each others implementation. They also cannot share global data. Changing the internals of one class does not affect the other class. Components should be independent and have only a single responsibility.
Consider a method that reads a list of numbers from a file and returns them in sorted order. Now the requirements change and the numbers are in a database. Modifying this method to access the database would cause client code to change. If this were two different methods, then a new source would not affect the sorting method. Only the client code would have to know the source of the numbers.
### Strong Cohesion
Inside a software component, code should be strongly connected. This is an indication that the code is correctly divided. If a component had two or more relatively disconnected parts, that may indicate that those parts should be in a different component, or on it's own.
### Loose Coupling
Between software components, there should be few connections. If two components are strongly coupled, it may indicate that they need to be one component, or that they need to be differently divided into more components.
#### More Information:
* [Orthogonality(programming) | Wikipedia](https://en.wikipedia.org/wiki/Orthogonality_(programming))
* [Principles of Orthogonal Object Oriented Programming | jasoncoffin.com](http://www.jasoncoffin.com/cohesion-and-coupling-principles-of-orthogonal-object-oriented-programming/)
* [GRASP - object-oriented design principles | Wikipedia](https://en.wikipedia.org/wiki/GRASP_(object-oriented_design)
Stack Overflow: What is Orthogonality?. https://stackoverflow.com/questions/1527393/what-is-orthogonality

View File

@@ -0,0 +1,86 @@
---
title: Quality Assurance
---
## Quality Assurance
Quality Assurance (commonly known as QA) is the means by which a product in development is checked to make sure it works as it's supposed to. The actual methods used in QA processes vary hugely depending on the size and nature of the product.
For a personal project you will probably just test as you go, asking others to provide feedback at appropriate stages. By contrast, a banking application must have every aspect of every feature exhaustively checked and documented to ensure it is both functional and safe.
Regardless of how formal or detailed a QA process is, its aim is to identify bugs so they can be resolved before the product is released.
### Methodologies
#### Agile
In an Agile approach to development, the aim is that each cycle of work ('sprint') produces working software that can be added to and improved upon iteratively. This makes QA processes an intrinsic part of the development cycle. By testing software components at each stage of their production you reduce the risk of bugs being present at release.
### Terminology
#### Automation Testing
Testing done with pre-written scripts designed to control the execution of tests.
#### Black Box
These test do not look inside the system under test, but treat it as 'closed' in the same way that the end user will experience it.
#### Defect
Any deviation from an application's specifications; often referred to as a &ldquo;bug&rdquo;.
#### Exploratory Testing
An unscripted approach to testing, which relies on the tester's unique creativity in an effort to find unknown bugs and identify regressions.
#### Integration Testing
Testing individual components/modules together to ensure they connect and interact well with one another.
#### Negative Path Testing
A testing scenario designed to produce an error state in a feature/application and verify that the error is handled gracefully. An example of this is inputing a series of numbers in the email field in a user registration form and checking to make sure the registration is not accepted until an actual email address is provided.
#### Regression Testing
Testing done on a new build to ensure that new functionality has not unintentionally broken previously tested functionality.
#### Smoke Tests
A minimalistic approach to testing intended to ensure basic functionality is working before more in-depth testing takes place. Typically occurs at the beginning of the testing process.
#### Test Case
Specified preconditions, steps, and expected results referred to by a QA tester/engineer to determine whether or not a feature performs its task as expected.
#### White Box
Refers to tests performed at a structural level, within the codebase. Programmers checking that the inputs to and outputs from specific functions or components would be white box testing.
Also known as 'Glass Box', 'Clear Box', 'Transparent Box' because the tester can 'see inside' the system under test.
Main categories are
* **Unit tests** (individual units of code do what they should)
* **Integration tests** (units/components interact with each other properly)
* **Regression tests** (re-applying tests at later stages of development to ensure they still work)
There are three main techniques:
* **Equivalence partitioning** (the tested input values are representative of larger input datasets)
* **Boundary Value Analysis** (the system is tested with chosen inputs where behaviour and therefore output should change)
* **Cause-Effect Graphing** (tests are designed from a visualization of the input-output relations)
### Other Resources
<a href='https://guide.freecodecamp.org/agile/test-driven-development' target='_blank' rel='nofollow'>Test Driven Development (freeCodeCamp Guide)</a>
<a href='https://guide.freecodecamp.org/software-engineering/unit-tests/' target='_blank' rel='nofollow'>Unit tests (freeCodeCamp Guide)</a>
=======
[Software Testing Fundamentals](http://softwaretestingfundamentals.com/)

View File

@@ -0,0 +1,15 @@
---
title: Scalability Cube
---
## Scalability Cube
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/software-engineering/scalability-cube/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -0,0 +1,63 @@
---
title: TCO Tail Call Optimization
---
## Tail Call Optimization (TCO)
Tail Call Optimization (**TCO**) is a solution to the problem of stack overflows when doing recursion.
### The Problem
Every call to a function is pushed to a stack in computer memory. When the function finishes, it is popped from the stack. In recursion, the function calls itself so it keeps on adding to the stack until all those functions finishes. There is, of course, a limit to this stack. When there are too many functions called, too many calls are added to the stack. When the stack is full and a function is called, this results in a **stack overflow** because the stack is already full. The recursive function will not finish and will result in an error.
#### Example
Here is an example of a JavaScript factorial function using recursion **without** TCO:
```javascript
function fact(x) {
if (x <= 1) {
return 1;
} else {
return x * fact(x-1);
}
}
console.log(fact(10)); // 3628800
console.log(fact(10000)); // RangeError: Maximum call stack size exceeded
```
Notice that running `fact` with an argument of 10000 will result in a **stack overflow**.
### Using TCO to solve the problem
To solve this using Tail Call Optimization, the statement where the function calls itself should be in a tail position. The tail position is the last statement to be executed in a function. Therefore, the function's call to itself should be the last thing called before the function ends.
In the previous example, the multiplication operation is executed last in the `return x * fact(x-1)` statement, so it was not the final operation of the function. Therefore, it is not tail call optimized. In order for it to be tail call optimized, you need to make the call to itself the last operation of the function.
#### Example
Here is an example of a JavaScript (ES5) factorial function using recursion **with** TCO.
```javascript
function fact(n) {
return factTCO(n, 1);
}
function factTCO(x, acc) {
if (x <= 1) {
return acc;
} else {
return factTCO(x-1, x*acc);
}
}
console.log(fact(10)); // 3628800
console.log(fact(10000)); // Infinity - Number too large, but unlike the unoptimized factorial, this does not result in stack overflow.
```
Notice that running `fact` on 10000 this time will **not result in a stack overflow** when *run in a browser that supports ES6* because the call to `factTCO` is the last operation of the function.
### Why this works
When the compiler or interpreter notices that the self-call is the last operation of the function, it pops the current function and pushes the self-call to the stack. This way the size of the stack isn't changed. Therefore, the stack doesn't overflow because of the function.
### Notes
#### More Information:
- <a href='https://stackoverflow.com/questions/310974/what-is-tail-call-optimization' target='_blank' rel='nofollow'>What is tail call optmization?</a> (StackOverflow)
- <a href='http://2ality.com/2015/06/tail-call-optimization.html' target='_blank' rel='nofollow'>Tail call optimization in ECMAScript 6</a> (2ality - Dr. Axel Rauschmayer's blog)

View File

@@ -0,0 +1,49 @@
---
title: Unit Tests
---
## Unit Tests
Unit testing is a type of testing which is found at the bottom of the software testing pyramid.
It involves breaking the codebase down into smaller parts (or units) and testing those in isolation.
Depending on the type of programming language (or paradigm) these can be against anything you define as a unit, although the most common practice is against functions.
### Why do it?
- **Protection** - Unit testing protects against introducing new or old bugs for defensive programming
- **Confidence** - You can add changes, or reuse or refactor code (both very common) and be sure you haven't added a bug
- **Documentation** - Unit testing documents the behavior and flow of code so its easy for someone new to the code to understand it
- **Isolation** - It isolates a module from the entire feature. This approach forces you to think of a module by itself, and ask what is its job?
- **Quality** - As unit testing forces you to think about and use your own API, it enforces good/extendable interfaces and patterns. It can point out any tight coupling or over-complexity which should be addressed. Bad code is usually much harder to test
- **Industry Standard** - Unit testing is a common discipline these days, and is a requirement for a large portion of software companies
- **Fewer bugs** - Substantial research suggests that applying testing to an application can reduce production bug density by 40%80%.
### Example(In Javascript)
Suppose there is a function written in file **add.js**
```javascript
var add = function(number1, number2){
return number1 + number2;
}
```
Now, in order to write unit test of this particular function we can use testing tools like [mocha](http://mochajs.org/)
```javascript
const mocha = require('mocha')
const chai = require('chai') // It is an assertion library
describe('Test to check add function', function(){
it('should add two numbers', function(){
(add(2,3)).should.equal(5) //Checking that 2+3 should equal 5 using the given add function
});
});
```
### Test-Driven Development
Unit testing is a key feature of the test-driven development (TDD) approach to software development. In this approach, code for specific features or functions is written through the repeated use of a very short cycle. First, the developer writes a set of automated unit tests and ensures that they fail initially. Next, the developer implements the bare minimum amount of code required to pass the test cases. Once it has been validated that the code is behaving as expected, the developer then goes back and refactors code to adhere to any relevant coding standards.
### More Information
Martin Fowler on Unit Testing: <a href='https://www.martinfowler.com/bliki/UnitTest.html' target='_blank' rel='nofollow'>martinfowler.com</a>
Robert Martin aka "Dr. Bob" on TDD: <a href='http://www.butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd' target='_blank' rel='nofollow'>butunclebob.com</a>
Eric Elliot on Unit tests and TDD: <a href='https://medium.com/javascript-scene/5-common-misconceptions-about-tdd-unit-tests-863d5beb3ce9' target='_blank' rel='nofollow'>Medium</a>

View File

@@ -0,0 +1,54 @@
---
title: Version Control System
---
## Version Control System
Version control systems (VCS), also called Source Code Management (SCM), are tools used to track changes on files, manage version and ease collaborative file editing.
There are mainly 2 types of VCS:
- Centralized Version Control System
Where a central repository is authoritative. The associate architecture is client/server.
The first VCS (CVS, SVN...) were Centralized Version Control System.
- Distributed Version Control System
Where multiple repository exchange modification. The associate architecture is mostly peer to peer, but one repo can be declared as authoritative.
The most used modern VCS (Git, Mercurial...) are Distributed Version Control System.
### Why use it?
- **Changes history** - VCS enable the user to browse and search all the changes which are automatically recorded with useful information (date, author...) and
- **Versions/tags** - The user can search/retrieve specific state of the files that have been labeled with tags and version names
- **Branching/Merging** - Distributed Version Control System make it easy to maintain parallel branch of files and to merge them partially or totally when needed.
- **Atomic operations** - All modern VCS provide atomic operations: All modifications are guaranteed to succeed or fail as whole which ensure that the files are always in a consistent state.
### Most popular Version Control System
- Git
*Git* is a Distributed Version Control System and probably the most used VCS used nowadays with *Mercurial*.
- Mercurial
*Mercurial* is a Distributed Version Control System and probably the most used VCS used nowadays with *Git*.
- CVS
*CVS* is an old SCM which was proeminent before *SVN* widespread.
*CVS* and *SVN* are now deprecated in favor of Distributed Version Control System like *Git* and *Mercurial*.
- SVN/Subversion
*SVM* is an old SCM that succeeded *CVS*.
Eventually *SVN* was deprecated by the wide adoption of Distributed Version Control System like *Git* and *Mercurial*
### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
<a href='http://savannah.nongnu.org/projects/cvs' target='_blank'>CVS</a>
<a href='https://git-scm.com/' target='_blank'>Git</a>
<a href='https://www.mercurial-scm.org/' target='_blank'>Mercurial</a>
<a href='http://subversion.tigris.org/' target='_blank'>SVN</a>
<a href='https://en.wikipedia.org/wiki/Version_control' target='_blank'>Version Control on Wikipedia</a>