Showing posts with label principles. Show all posts
Showing posts with label principles. Show all posts

High Cohesion, Loose Coupling

0

Category : , ,

We are witnessing a high demand for a maintainable software, software that can change easily over time. In order to prolong the value of the software for a long period of time you have to make it respond easier to change. There are a few guidelines that you can follow that can help you out.

Here, I try to shed some light on two of those: cohesion and coupling

High Cohesion

Cohesion in software engineering is the degree to which the elements of a certain module belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

Functional Cohesion

Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module.

One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes. Below is one example of how a high-cohesion class would look like.

1:    class HighCohesion  
2:    {  
3:      private int _elementA;  
4:      private int _elementB;  
5:    
6:      public int MethodA()  
7:      {  
8:        var returnValue = SomeOtherMethod(_elementA);  
9:        return SomeVeryOtherMethod(_elementB);  
10:      }  
11:    
12:      public void PrintValues()  
13:      {  
14:        Console.WriteLine(_elementA);  
15:        Console.WriteLine(_elementB);  
16:      }  
17:    }  


The point is having a the classes as small as possible in terms of elements. The less elements we have the greater the possibility for them to be used in all the methods.

Loose Coupling

Coupling in simple words, is how much one component knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

Correct and clear description of what 1:1 coupling is:

iPods are a good example of tight coupling: once the battery dies you might as well buy a new iPod because the battery is soldered fixed and won’t come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.


Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…

Tight coupling is where components are so tied to one another, that you cannot possibly change the one without changing the other.

The image above shows us a relation between two classes that is called tight coupling. Class1 above directly instantiates objects of Class2, and even goes as far as accessing member variables and so on. This makes it very dependent on Class2. What if we decided we wanted to add extra parameter in Class2’s constructor and make the default one private? Then we would have to change every usage of Class2 everywhere.
1:    class ClassA  
2:    {  
3:      private bool _elementA;  
4:        
5:      public int MethodA()  
6:      {  
7:        if (_elementA)  
8:          return new ClassB()._elementB;  
9:          
10:        return 0;  
11:      }  
12:    
13:      public void PrintValues()  
14:      {  
15:        new ClassB().MethodB();  
16:      }  
17:    }  
18:    
19:    class ClassB  
20:    {  
21:      public int _elementB;  
22:    
23:      public void MethodB()  
24:      {  
25:        Console.WriteLine(_elementB);  
26:      }  
27:    }  

We can solve this is by so called inverting the dependencies, by adding another layer. Example in C# would be adding an interface. That’s way Class1 will only be dependent on the interface, and not the actual implementation of Class2. Image 4 ilustrates this point.
Instantiation of the actual implementation will take place somewhere else in the code. This is the one of the most important reasons why dependency injection frameworks are being used.
1:  class ClassA  
2:    {  
3:      private readonly ISomeInterface _interfaceImpl;  
4:    
5:      public ClassA(ISomeInterface interfaceImpl)  
6:      {  
7:        _interfaceImpl = interfaceImpl;  
8:      }  
9:    
10:      public int MethodA()  
11:      {  
12:        return _interfaceImpl.MethodB();  
13:      }  
14:    
15:      public void PrintValues()  
16:      {  
17:        _interfaceImpl.PrintValues();  
18:      }  
19:    }  
20:    
21:    interface ISomeInterface  
22:    {  
23:      int MethodB();  
24:      void PrintValues();  
25:    }  
26:    
27:    class ClassB : ISomeInterface  
28:    {  
29:      private int _elementB = 2 + 2;  
30:    
31:      public int MethodB()  
32:      {  
33:        return _elementB;  
34:      }  
35:    
36:      public void PrintValues()  
37:      {  
38:        Console.WriteLine(_elementB);  
39:      }  
40:    }  

What is the reason behind this, you may ask yourselves???……..Change.

When we have the components this separate, then we can have separate implementation of different problem areas. With separate implementation we can change as much as we want without breaking some other greater process that is using it. Furthermore, when you can change components independently, there is nothing stopping you from developing them independently and even deploy them separately.

Law of Demeter

The Law of Demeter (LoD) or the principle of least knowledge is a object-oriented software design principle. In its general form, the LoD is a specific case of loose coupling.

The formal object form of the law can be summarized as:

A method of an object may only call methods of:
  1. The object itself.
  2. An argument of the method.v
  3. Any object created within the method.
  4. Any direct properties/fields of the object.

The conclusion can be summarized in one sentence:
Don’t talk to strangers!
An object A can request a service (call a method) of an object instance B, but object A should not “reach through” object B to access yet another object, C, to request its services. Doing so would mean that object A implicitly requires greater knowledge of object B’s internal structure. Instead, B’s interface should be modified if necessary so it can directly serve object A’s request, propagating it to any relevant subcomponents. Alternatively, A might have a direct reference to object C and make the request directly to that. If the law is followed, only object B knows its own internal structure.

In particular, an object should avoid invoking methods of a member object returned by another method , like for example:
var a = someObject.FirstMethod().SecondMethod();
For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as “use only one dot”. The above example breaks the law where for example:
var a = someObject.Method();
does not. As an analogy(Wikipedia), when one wants a dog to walk, one does not command the dog’s legs to walk directly; instead one commands the dog which then commands its own legs.

The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

my thanks to: http://thebojan.ninja/2015/04/08/high-cohesion-loose-coupling/

Learning TDD using Kata's

0

Category : ,

Why We Need to Learn TDD?

Think of a scenario where a developer did complete unit testing and the Quality Assurance guys did their job and marked the deliverables ready for production. What happened if the other developer’s code/changes break the first developer’s code? Now, here we can think about TDD. As it is self-explanatory, Test Driven Development means what we are writing, we are testing. In this way, if someone broke your code, then your test(s) will get failed and you can check the broken area. This is just a one aspect, TDD is a huge one.

What is TDD?

As per wiki, TDD is defined as:
"Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards"



TDD has three stages called Red Green Refactor (RGR).

  • Red – First write test that fails.
  • Green – Modify/alter code so, test pass.
  • Refactor- Re-write the code better.

What is TDD Kata?

Kata is a Japanese word and means as ‘form’ and detailed choreographed pattern of body moments.
In martial arts, what they do, they do practice and repeat the steps to hone the skills and their patterns. Similarly, in software, the idea was originally invented by Dave Thomas. The motive of this idea is the same, do practice, repeat tasks and make your skills perfect.

The FizzBuzz Kata

Print the numbers from 1 to 100. But for multiples of three, print "Fizz” instead of the number and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

Other Katas:

https://github.com/garora/TDD-Katas
http://tddkatas.codeplex.com/
http://codingkata.net/

My thanks to:
http://www.codeproject.com/Articles/886492/Learning-Test-Driven-Development-with-TDD-Katas

Developing MVC applications using SOLID principles

0

Category : ,

my thanks to: Developing MVC applications using SOLID principles http://www.codeguru.com/csharp/csharp/writing-c-code-using-solid-principles.htm

The Principles of Agile Development

0

Category :

http://code.tutsplus.com/articles/the-principles-of-agile-development--net-25732

SOLID: Part 4 - The Dependency Inversion Principle

0

Category :

Definition

  • A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • B. Abstractions should not depend upon details. Details should depend upon abstractions.


my thanks to:
http://code.tutsplus.com/tutorials/solid-part-4-the-dependency-inversion-principle--net-36872

SOLID: Part 3 – Liskov Substitution & Interface Segregation Principles

0

Category : ,

http://net.tutsplus.com/tutorials/php/solid-part-3-liskov-substitution-interface-segregation-principles/

Subtypes must be substitutable for their base types.

SOLID: Part 2 – The Open/Closed Principle

0

Category : ,

To design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.


http://net.tutsplus.com/tutorials/php/solid-part-2-the-openclosed-principle

SOLID: Part 1 – The Single Responsibility Principle

0

Category : ,

http://net.tutsplus.com/tutorials/php/solid-part-1-the-single-responsibility-principle/

Class and module design is highly affected by The Single Responsibility Principle and leads to a low coupled design with less and lighter dependencies. But as any coin, it has two faces. Excessive SRP consideration can easily lead to premature optimization and instead of a better design, it may lead to a scattered one where the clear responsibilities of classes or modules may be hard to understand

SOLID Principles of Programming

0

Category :

Robert C Martin introduced the acronym SOLID in the early 2000s to communicate five high level principles for object oriented programming. The five principles are:

Single Responsibility – an object should have only one responsibility.

Objects created in this fashion are considered more durable over the long term because they have only one reason to change. Using the single responsibility principle will cause you to have many more classes.
However, the more granular your classes become, the easier it will be to maintain and modify those classes without impacting a large portion of your code.
http://codebetter.com/karlseguin/2008/12/05/get-solid-single-responsibility-principle/

Open/Closed – an object is open for extension, but closed for modification.

This principle is implemented by utilizing the other SOLID principles in conjunction with object oriented development patterns. How do you make modifications, sometimes major modifications, without breaking your existing code? Applying the open/closed principle you would not modify the existing code; rather, through implementing software development patterns, you would add new functionality, taking advantage of the existing software, without changing the way it works internally.
That is the reason that SOLID is an acronym. Each of the principles work hand in hand and cannot stand alone. For example, the Single Responsibility pattern we reviewed yesterday provides a framework for Open/Closed. If each object has a single responsibility, it is a lot easier to lock them down (Close) while still adding new functionality at a later time (open).
If you would like to see an example of code techniques implementing Open/Closed, I found a great article in MSDN magazine by Jeremy Miller, http://msdn.microsoft.com/en-us/magazine/cc546578.aspx, from 2008 demonstrating how the SOLID principles may be implemented through different object oriented patterns.

Liskov Substitution – An object should be replaceable with instances of a subtype without altering the correctness of a program.

Liskov postures that your specific class implementations should utilize an abstract implementation of external objects. In so doing, you can change the functionality of that class by substituting a different implementation of the abstract external object with another, and the containing class need not be modified in any way. In essence, this is one technique for fulfilling the Open/Closed principle.
an object called BusinessProcess. BusinessProcess requires interaction with a data source. Rather than instantiating a specific data source the BusinessProcess class utilizes an IDataSource interface. By using an interface the BusinessProcess object works with any implementation of the IDataSource interface.
The IDataSource interface can be implemented by an XML data store. Later it may be implemented with a relational database data store without modifying the BusinessProcess class in any manner.
In this fashion, Single Responsibility, Open/Closed and Liskov Substitution work together resulting in code that may be easily extended with the least impact to existing code. Utilizing other software development patterns, new implementations of IDataSource may be created, instantiated, and inserted into the program for execution by adding only new code, and modifying configuration data for implementation.

Interface Segregation – segregated interfaces are better than on single general purpose interface.

Unlike the other principles we have covered up to this point, Single Responsibility, Open/Closed, and Liskov Substitution, the Interface Segregation Principle is less transferable to languages that are not object oriented.
If I were to summarize the principle into one sentence it would be, “it is better to have more tightly defined interfaces rather than fewer comprehensive interfaces.”.
A rule of thumb might be, if you can foresee a realistic potential for the need to separate an interface into smaller interfaces because the interface contains features that do not apply to all implementations, then it makes sense to break it out.
This is where refactoring comes into play. Perhaps your interface was too general when you started out. That doesn’t mean you can’t break the interface out into smaller more granular interfaces at a later date. It just takes more work; especially if you don’t have automated unit tests to prove your refactoring work hasn’t broken your business requirements.

Dependency Inversion = Base your code on abstractions such rather than concrete implementations.

If your class dependencies are based on abstractions (Interface or abstract class) then the classes implementing the abstractions may be replaced without impacting any and every consumer.
Dependency Injection is a good implementation of the Dependency Inversion Principle. Using Dependency Injection, a consumer passes a desired kind of implementation to a class capable of resolving the correct implementation required, returning the correct object. container i guess.
One of my favorite examples is having a web app that can save data to a web service, an XML File, or a relational database. The user says, Save to XML. The web application knows nothing about how to save XML; but it knows how to call a persistence controller that returns a class that will save the data as an XML file. The Class supporting XML is based on an interface shared by the web application. The Web site, in this instance is injecting through a controller, the information necessary to implement the correct type of Class to persist the data to XML.
Dependency Injection is one technique of implementing Dependency Inversion. They are not equivalent concepts.


my thanks to: http://www.sswug.org/nlarchive.aspx
first email newsletter received on 30/07/2012