Monday 18 January 2016

S.O.L.I.D principles

Introduction

The principle; is a high level idea that born out of various minds and brains, it is recognized based on human experiences and experiments, it inspires other folks when they try to take similar actions or decisions. The critical thinking; is the curiosity and carefulness of providing full fledged set of solutions free of mistakes, errors, accidents and problems.

SOLID are a group of principles that guide critical thinking of software developers and programmers while they are developing a software code. Nevertheless, being aware of these principles guarantees a common understanding between developers about the decisions they usually made in the pattern body of their code. As result, a group of design patterns have come out of those principles, which progressively became popular and known to be best practices, currently there exist a set of known design patterns based on SOLID principles, they are out of the scope of this article, and I'll write about them latter on.

In this article I will try to talk a while about each principle and spot light on some practical examples that are already existed in .NET framework.

S: SRP Priniciple <<a class should only take care of only one responsibility>>
SRP is an abbreviation of "Single Responsibility" principle, this principle tells the developer to write his class for only one and single target, his class should take care of only one responsibility, it should has only one reason to change, it should does one thing and does it very well. So if it is an entity class, then it should only contains properties to hold values, without performing any business functionalities, data persisting functionalities or even UI functionalities. In case it is a provider class, it should only contains the persisting functionality of the data, like opening a connection with the DB server, executing SQL-commands or preventing security threatens on data. This principle is essentially required so that you have a clean code that is easy to be maintained by other developers. They will find it readable and easily approachable, they can move from generic-function to another without losing concentration of their purpose. They will find it also reusable, so your class will help others to reduce effort and consequently reduce the overall cost. One example of S-Principle in .NET framework is the "Math" class, which is a static class that can't be instantiated, its only purpose is to provide a collection of mathematical functions, these functions are available to be used in any context. Actually, any class in .NET framework is eligible to satisfy the "Single Responsibility" principle.

O: OCP Principle <<a class is opened for extension but closed for modification>>
OCP is an abbreviation of "Open Close" principle, this principle tells the developer to design his class so another developer "may be himself" is not allowed to modify its functionality but he is allowed to extend it. The class should be opened for extension but closed for modification. The creator-developer can use many techniques to provide such facility, like virtual methods, callback functions, events, delegates, actions or lambda. The user-developer in the other hand-side can use the corresponding techniques to extend the class functionality, like higher order functions technique, which is a functional style programming that allows him to pass his extension-functions as a parameter to the class's methods, so the class's methods will call his extension-functions to modify , format or evaluate the values of its properties. The .Net framework has provided the concept of the Extension-Methods to support "Open Close" principle, which allows us to extend any class using simple coding-style with static class, public static functon and "this" keyword. The most populare example in .Net is LINQ that extends IEnumerable with large number methodes like Where(), Join() and OrderBy(). IEnumerable is "closed" to be modified but is "opened" for extending by LINQ or any custom extensions.

L: LSP Principle <<child class object should be able to replace parent class object in any context>>
LSP is an abbreviation of "Liskov Substitution" principle, this principle is introduced by Barbara Liskov "American scientist" in 1987, the principle emphasizes on the deep relationship between the suppertype and its subtype, so that each of them should respect the state of the other, the subtype "derived class or child class" should respect the state of the suppertype "supper class or parent class". If a developer do respect this principle then he can safely use the subtype's object in any context where suppertype's object is expected. So, this principle is all about a parent class object that can be able to refer his child object during run time without any problem, and the child class object can replace the parent class object during run time with any problem. The most popular example in .NET is the "Object" class that is the parent of all classes in .NET, the Object's methods are available in every class such as "GetHashCode(), GetType(), Equals(), ToString() and Finalize()", and any class object can change the behavior of any of these functions using "override" keyword, but they can't change any certain state of the type "Object", so that the child object safely replaces "Object" type in any context.

I: ISP Principle <<clients should not be forced to depend on methods that they do not use>>
ISP is abbreviation of "Interface Segregation" principle, this principle tells the developer to simplify the role of each interface, in order to keep the interface untouchable in front of any change requests in the future, and clients remain stable once they build their systems depending on this interface. This way, we will have different interfaces for different roles, the developer implementation may be accumulated in one class that inherits from multiple interfaces, hence, the client will not be forced to use an interface if he does not need it. It is all about identify small roles instead of one generic role, and assign every little role to an individual interface so we don't define too much methods for any individual interface. In .NET for example, we can find interfaces like IEquitable<T>, IComparable<T> and IEnumerable<T> that has only one method each, which are Equals(T), CompareTo(T) and GetEnumerator(). It was possible for the three functions to be accumulated into one interface, but that will enforce clients to depend on methods that they will not use. Being segregated is more easy to extend any one of them and left the others, it is also possible to implement or inherit one of them or more.

D: DIP Principle <<high level modules should not depend on low level modules, instead both should depend upon abstractions>>
DIP is abbreviation of "Dependency Inversion" principle, this principle tells the developer to give himself a freedom to switch or swap dependencies during run-time or compile-time instead of tightly coupling between modules or classes at design-time, that will only be achieved by abstracting the dependency between modules, so if we have the screen and the printer as output modules then we can make our copier module depends on abstracted output module at run time that will be assigned one of them to copy on. This is sometimes named dependency injection and is important to develop loosely coupled software systems. The .NET has introduced "Generic & Interface" as a very efficient techniques for dynamic dependencies whether at compiling time or at run time. That way we can have a reusable and extendable modules that are convenient with testing as well.

Saturday 16 January 2016

Clean Code

Introduction
In this article, I want to discus clean-code as a modern approach to build elegant software systems, and to spot the light on the main rules, practices, behaviors and knowledge that any developer needs in order to write clean code. I have been influenced by Jeremy Clark's ideas that he spreads in his sessions on YouTube, where he sets many valuable practical advices along with clear practical guide.

Clean is a Rule
"Try and leave this world a little better than you found it." - Robert Baden-Powell Rule -
"Always leave the campground cleaner than you found it." - The Boy Scout Rule -
"Always leave the code cleaner than you found it." - Clean Coder Rule -
"Always check a module in cleaner than when you checked it out." - Clean Coder Rule -


Clean Code
The clean code, from Jeremy Clarck's view point, is the code that is readable, maintainable, testable and elegant. Some people like Jeremy, doesn't favor the title "architect" to be hold by software engineer, that is because software industry is so different than architecture industry, software has particular aspects which don't exist in other fields, for example bug fixes, business changing, enhancements and new functionalities. This specialty of the software industry needs developers to be careful to write clean code because of the known truths:  (1)clean code saves time (2)Any code has at least five years life-span if not ten or more (3)We can't take a short term view of software. 

What really prevents developer to write clean code is he usually says "I will clean-up it later" and the other famous word of administrators "Ship it now!", So it is too important to avoid all prevents including ignorance, stubbornness, short-time syndrome, arrogance, job security and scheduling. The developer doesn't have to resolute adherence to his own ideas or desires against writing clean code. A developer makes mistake when work reaction instead of action and when feeling own importance and reject cleaning to his code.

The best way to convince yourself to write clean code is to imagine that the other developer guy who comes after you is a homicidal maniac who knows where you live :)

Intentional Naming
It is too important to get your intent to other developers, the thing you should focus on when coming to give a name for an object or a method. A not very good example of an object name is "theList", where at the time that other developer is going to know that it is a name of a collection, he doesn't know what is the type of items inside and what is the purpose hidden behind this collection. You didn't pass him any description to imagine your imagination, it is all a matter of what is the intent you want to pass for him to work with your code. A good naming example is "ProductList" but the more elegant one is "ProductCatalog".


Naming standards are something like "CamelCase, UpperCamelCase, lowerCamelCase, PascalCase, lower_Case_Underscores or Upper_Case_Underscore". It does not really matter which naming standard you choose, what really matter is to choose any and immediately use it, just have standard and be consistent.

You should also use "nouns" for naming variables, fields, properties and parameters, for example, you can use names like "indexer, currentUser, priceFilter". Moreover, you can use "verbs" to name methods and functions, for example you can use names like "SaveOrder(), GetApplicableDiscount(), FetchCustomerData(), RunPayroll()". But, names like "recdptrl" is not only ambiguous but they are also difficult to be pronounced as well, so it is more better to make it easier when you type it, for example "recordDepartmentRole" or "receivedPatrol".

Comments
Comments should not be used to tell what code does, but if you need to explain what code is doing then you need to rewrite the code to make the code more clear, however, we can use comments to describe intent or consequences of code, and we have to avoid lies of comments, where it is truth that we update or move the code, but not the comments, so comments lie and you should avoid that by explaining yourself in code and rewrite the code if it is unclear. 

A good comment is the one that describes intent or clarification such as "//Product price of one month ago", gives warnings or consequences such as "//we do ... to make sure that ..." and mentions ToDos such as "//Magic variables should be moved to the configuration file" that is temporary and must be removed when the task is completed. 

A bad comment is the one that plays the role of other tools such as "journaling" comment that plays the role of source control, for example "//Wael | 20 Apr 2015 | Fix Bug No####", this is what source control for "i.e. who, what and when", it is recommended to know your tools and make use of them. Avoid "noise" comments such as "//default constructor".Avoid commented code and just delete the code that is no longer in use, it is the role of source control to retrieve old code back if you need so.

Refactoring
It is all about making code better without changing the functionality of the code. Look to your code and ask yourself, is this bad code? you may say no it is good code and no wrong with it, but it may not feel good for others, they may see it a little bit difficult to understand from the first time, they probably need time to scan it to know what it probably needs to do, and that what you would expect from any developer who would work to that code at the first time. So, ask yourself again what you can do to make this code more easir to work with, because after six months from now someone would going to ask you to make a change, and you might not exactly remember how it works, so you have to look to the code to figure it out "at least" to yourself.

Unit Tests is essential, if you do not have unit tests, you don't really know what your code really does, if you do not know what your code does, you can not safely refactor it, refactoring step one is to bring your code under test, refactoring step two is to safely and confidently update the code.

However, you should think in doing something for your code, like hierarchical functions, which is the concept of categorizing functions into "high, mid and low" levels. Go and start with the high level function that is the basic big chunk of what you are trying to implement, then drill down to the more detailed functions that will have the actual functionality. Then, refactor your code by extract methods out of the large blocks, you can use "Ctrl + [R | M]" to do so in visual studio or right click the editor and select "Refactor >> Extract Method". Make sure the new refactored methods is understandable from its name. A fast way to make sure you did the right refactoring is to run the unit tests for each refactoring step. You can even enable run test with each build operation by clicking "Run Test After Build" button on the top of the "Test Explorer". Having unit test in place makes sure we don't accidentally change the functionality of our code. The unit test naming convention you are using will help much finding where exactly the error happen. Roy Osherove, who wrote the "Art Of Unit Testing", recommended a naming scheme "model_operation_result" that slices unit-test-name into three parts, the first is for the model under test, the second part is the under going action and the last part is the result that we are expecting.

The refactor "Dry Principle" says "Don't Repeat Yourself!", it means don't copy, past and modify code but create a common piece of code to be reused in multiple contexts. If you have two sections with the same code they really need to combine, so that we elements the duplication of the code.

Visual studio automatically handles indents when you press "CTRL + [K | D]", that way you can easily see at a which level every statements is placed.

Use "#Region" to organize your code and specify one region for every similar parts of the code, such as fields, properties, constructors, public methods, private methods, events and notify changed members. That way we will have everything very well organized and we can watch them grouped on solution explorer too if we open the "file name >> class name". What we will see in the solution explorer is all the members of the class where everything is grouped together the same way we already did by "#Region".

Using refactoring techniques that way leads us to tell what our code is doing at a high level, and if we need to drill down to details, then we can do easily. Remember, we start with "not a bad code" and here we ended with something that is "very easy to walk up to very approachable", so six months from now if anyone asks you to make updates to that code, you can walk up to it and remember where you are too quickly and navigate to where you need to make these changes. 

Books To Read
Clean Code - Book by Robert Cecil Martin
Working Effectively with Legacy Code - Book by Michael C. Feathers
Refactoring: Improving the Design of Existing Code - Book by Martin Fowler
Refactoring to Patterns - Book by Joshua Kerievsky

Friday 15 January 2016

Visual Studio 2013 Productivity Power Tools New Features

With the release of Productivity Power Tools 2013 for Visual Studio 2013 come eleven new powerful features. Some of these features are brand new extensions, while others are improvements to functionality found in previous versions of Productivity Power Tools.

For full details of the features, please refer to the Productivity Power Tools 2013 entry.
For more about PPT of VS2015 & VS2017 please visit this page on GitHub.

In this post I'll explain what I have learned from a video that introduces these new features such as quick tasks, recently closed documents, peek help, HTML copy and others.


Peek Help "Alt + F1"
This feature allows you to fetch the MSDN documentation for types and display it online inside the editor, you can right click on any type on the editor, and click on the "Peek Help" command or press "Alt + F1" key to fetch the MSDN documentation for that type and display it online in a full browser control, then you can navigate to other links, you can even do things like find, you can click "Promote To Document" button to open this link in a real browser or you can hit ESC to go back to your editor. This feature extremely useful to know about new type without having to leave visual studio.

Solution Explore Squiggle
This feature shows squiggles "red underline" on files on the solution explorer when there are errors, warnings or messages. You can hold the mouse pointer on this files to get quick view of all these errors, then double click on any item to quickly navigate to that point inside the editor. You can also filter the solution explorer by clicking "Error Filters" combo-box or press "Ctrl + L E" to just get a list of files that has the error. This feature extremely useful to get a quick view of the health of execution without having to open the error list.

Block Structure Visualizer
This feature creates marker in the editor corresponding to different blocks in your code. For example, you may see different vertical lines with different colors for different blocks in the code such as a vertical line corresponds to namespace, class or for-loops. Lines and colors differently depending on the type of the blocks and if the starting of the block is scrolled up to the screen it gives me a preview about the block when I hold the mouse "hover" on its corresponding line for a while. This extension can be relay helpful to understand the structure of your code base when it scrolled out of view.

Double Click To Maximize Windows
This feature allows you to double click on any window inside visual studio to quickly maximize it to full screen. You can double click on the full screen again to dock it back into the original position. The feature works not just for tools windows but even for documents, so I can double click on a document to quickly maximize it to a full screen, and double click again back to my original position. This feature extremely useful if you want to get quick full screen views of certain things inside visual studio.

The Time Stamp Margin In The Debug Output Window
If you open the output window and open the debug section, you will have time stamps corresponding to different debug messages. The feature is very useful if you have a very large number of debug messages to understand the times each of the message was created.

Quick Task Extension Improvement 
This feature is introduced in the previous versions of power tools. It helps if you want to turn line numbers on in the editor, pres "Ctrl + Q" and simply type "linenumon" to immediatly turn on line number inside the editor. We can search for all the tasks available to you by typing "@tasks e" to list all the tasks provided by the quick tasks extension. There are over 32 tasks from which you can chose. The most popular task of them is called "PresentOn", which pumbs up the editor and the environment font to optimize layout for presentations "i.e. adjusts font for code presentation". A popular feature we had for the "PresentOn" extension was to allow people to customize the font sizes and font families by typing "PresentEdit", which allows you to open an XML file and customize the font family and font size you want for your "PresentOn" task.

Document Table Extension Improvement
It colorizes document-tab depending on the file that the tab belongs to. You can customize document tab by clicking on the "Customize" option in the menu that pops on when you click the arrow button at the right had side of the tab ribbon. Where you will find an option called "Show icons" under "Productivity Power Tools >> Custom Document Well >> General". By checking this option it shows you icons right on the document tab. So, if you a solution with a large number of languages or different types of files then this extension can really help you landing down on the file that you are looking for.

Go To Definition Improvement
It is feature, which allows you to navigate to definitions by "Ctrl + Click" on a symbol. It is made easy by opening a peek view to show the definition inside, right below the symbol, of course it is an option for you that you can customize the symbol definition the way you want inside the peek view. 

HTML Copy Extension Improvement
This extensions allows you to copy your code as HTML and past into your blog site or any HTML editor. Open Edit menu and select "Copy Html Markup" to copy your select lines of code as HTML, If you have an editor that doesn't support WYSWYG you can directly past the HTML content inside it. So as you can see the code was copied along with HTML tags.

Undo Close Document
If you closed a punch of documents in the document tab you can click on the "File" menu and select "Recently Closed Documents", which allows you to open any recently closed document.

Match Margin
It is a feature that highlights all the text matches for any token in the editor, so if I place my caret on "System" token, it highlights all the occurrences of "System" in my file as well as the scroll-bar, for example, if you click on "Public" the scroll bar shows you many markers corresponding to the text "Public".