SlideShare a Scribd company logo
1 of 6
Download to read offline
Diving into Visual Studio 2015 (Day #4): Code Refactoring
Introduction
Code Refactoring has always been a challenge for developers. This is one of the major skill that a developer should have
to write an optimized , clean and fast code. There were third party tools available to help you achieve this, but none
have shown that capability that Visual Studio 2015 has come up with. Visual Studio has always offered code refactoring
techniques in tit-bit, but the latest version of Visual Studio i.e. 2015 provides a unique experience altogether to achieve
refactoring. There are many features that refactoring of code in Visual Studio provides. We’ll cover few of them like
inline temporary variable and introduce local. Refactoring w.r.t. inline temporary variable and introduce local is not only
limited to C# but VB developers can also leverage this feature. We’ll cover the topic with one small method as an
example and try to optimize it as far as we can. One thing is worth taking care of that code refactoring software and
techniques are only meant for sharp developers. If you don’t have an idea what new code will do and it looks strange to
you, you should never try it.
Case Study
I am taking an example of MyProducts class that we created in earlier section.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: public class MyProducts :IProducts
10: {
11: List<Product> _allProduct = new List<Product>();
12: public MyProducts()
13: {
14: _allProduct.Add(new Product
{ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple
IPhone" } );
15: _allProduct.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice =
"20000", ProductType = "Phone", ProductDescription = "Micromax phone" });
16: _allProduct.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice =
"30000", ProductType = "Tab", ProductDescription = "Apple IPad" });
17: _allProduct.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice =
"30000", ProductType = "Phone", ProductDescription = "Google Phone" });
18: _allProduct.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice =
"40000", ProductType = "Phone", ProductDescription = "Samsung phone" });
19:
20: }
21:
22: /// <summary>
23: /// FetchProduct
24: /// </summary>
25: /// <param name="pCode"></param>
26: /// <returns></returns>
27: public Product FetchProduct(string pCode)
28: {
29: return _allProduct.Find(p => p.ProductCode == pCode);
30: }
31:
32: /// <summary>
33: /// FetchProduct with productCode and productName
34: /// </summary>
35: /// <param name="productCode"></param>
36: /// <param name="productName"></param>
37: /// <returns></returns>
38: public Product FetchProduct(string productCode, string productName)
39: {
40: return _allProduct.Find(p => p.ProductCode == productCode && p.ProductName==productName);
41: }
42:
43: public List<Product> GetProductList()
44: {
45: return _allProduct;
46: }
47: }
48: }
We’ll add one more method to this class. The objective of that method will be to return all products from the product
list whose price is greater than 30000. I am trying to keep the logic and method very simple for the sake of
understanding.I have kept the name of this method is FetchProduct(). Notice that we already had two methods with the
same name. Now this will also work as an overload to FetchProduct() method.
The above mentioned method is very simple in nature and contains LINQ query that fetches products having price
greater than 30000. When you call this method from Program.cs and iterate over the elements we get following result.
Program.cs code is as follows.
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6:
7: namespace VS2015ConsoleApplication
8: {
9: class Program
10: {
11: static void Main()
12: {
13: var myProducts = new MyProducts();
14: Console.WriteLine( String.Format("Product with code 0002 is : {0}",
myProducts.FetchProduct("0002").ProductName));
15: Console.WriteLine(Environment.NewLine);
16: var productList = myProducts.FetchProduct();
17: Console.WriteLine("Following are all the products");
18:
19: foreach (var product in productList)
20: {
21: Console.WriteLine(product.ProductName);
22: }
23: Console.ReadLine();
24: }
25: }
26: }
So, our method is working fine. the question is how much we can optimize this method further. When you click in
between products variable, the light bulb icon will show up with some suggestions that you can apply to this line to
optimize.
Here come inline temporary variable in picture. The light bulb icon says to remove this variable and bring that code to a
single line. When you preview the changes that this code assistance is suggesting you get following preview window.
It shows that the temporary products variable will be replaced with productList itself therefore helping us to save
number of lines as well as memory allocation for a variable. Click on apply changes and you’ll get the refactored code.
Now can this code be further refactored. you can take help from light bulb icon. Either click in between productList
variable or right click on productList variable and open Quick Actions from context menu.
We see here, productList is also a temporary variable and it is suggested to remove that too. Let us preview changes and
apply them to get more optimized code. Doing this the productList variable will be replaced by a single return
statement, but you’ll notice an error here.if you remember, I said that code refactoring is for intelligent and sharp
developers. We see here that while refactoring the code, LINQ query is not encapsulated in the bracket and ToList()
method is directly applied to “p” variable. We have to rectify this by putting brackets around LINQ query. This was one
of the scenario, and you may face many of such.So you have to be sure about the change that you are about to do.
visual Studio only suggests, it does not code for you.
Now we have a single return statement. Our code has reduced to just one line and we saved few memory too by
ignoring temporary variables. This certainly makes the code faster as well. But can we further optimize this method?
Let’s take a shot and click on return statement. You’ll see the light bulb icon again shows up with some suggestions.
It says that the method could be converted to an expression bodied member. Let us preview the change.
The preview says that the method is converted into an expression. Looking at this I do not find any issue. So we can
certainly opt this option for the sake of refactoring. Press apply changes and we get following code.
Now if you try to further optimize this method, you’ll not find much scope.
Conclusion
This was just a small example that I showed on how you can leverage the capability of Visual Studio 2015 in optimizing
your code. In the next section of this series I’ll be covering topics like debugging features in Visual Studio 2015.
For more technical articles you can reach out to my personal blog, CodeTeddy.

More Related Content

What's hot

Dependency injection: koin vs dagger
Dependency injection: koin vs daggerDependency injection: koin vs dagger
Dependency injection: koin vs daggerMatteo Pasotti
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionDive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionOleksii Prohonnyi
 
Ios ui automation test framework
Ios ui automation test frameworkIos ui automation test framework
Ios ui automation test frameworkWinter Hong
 
Tang doanh thu quang cao di dong
Tang doanh thu quang cao di dongTang doanh thu quang cao di dong
Tang doanh thu quang cao di dongDuc Canh Tran
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for BeginnersEdureka!
 

What's hot (6)

Dependency injection: koin vs dagger
Dependency injection: koin vs daggerDependency injection: koin vs dagger
Dependency injection: koin vs dagger
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionDive into Angular, part 1: Introduction
Dive into Angular, part 1: Introduction
 
Ios ui automation test framework
Ios ui automation test frameworkIos ui automation test framework
Ios ui automation test framework
 
Tang doanh thu quang cao di dong
Tang doanh thu quang cao di dongTang doanh thu quang cao di dong
Tang doanh thu quang cao di dong
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 

Viewers also liked

Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-Победы
Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-ПобедыЖуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-Победы
Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-ПобедыАлександр Астахов
 

Viewers also liked (11)

секреты PR кухни
секреты PR кухнисекреты PR кухни
секреты PR кухни
 
Эффективные каналы коммуникации в сфере недвижимости
Эффективные каналы коммуникации в сфере недвижимостиЭффективные каналы коммуникации в сфере недвижимости
Эффективные каналы коммуникации в сфере недвижимости
 
Как рекламировать недвижимость?
Как рекламировать недвижимость?Как рекламировать недвижимость?
Как рекламировать недвижимость?
 
Маркетинг проектов редевелопмента
Маркетинг проектов редевелопментаМаркетинг проектов редевелопмента
Маркетинг проектов редевелопмента
 
Эффективность печатных и интернет СМИ
Эффективность печатных и интернет СМИЭффективность печатных и интернет СМИ
Эффективность печатных и интернет СМИ
 
Глянец для B2B
Глянец для B2BГлянец для B2B
Глянец для B2B
 
Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-Победы
Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-ПобедыЖуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-Победы
Жуковка - малоэтажный жилой комплекс в Новосибирске на улице Жуковского-Победы
 
Бюджетирование маркетинга
Бюджетирование маркетингаБюджетирование маркетинга
Бюджетирование маркетинга
 
Маркетинг торговых центров
Маркетинг торговых центровМаркетинг торговых центров
Маркетинг торговых центров
 
Концепции деловых подарков к новому году
Концепции деловых подарков к новому годуКонцепции деловых подарков к новому году
Концепции деловых подарков к новому году
 
PR на рынке B2B: как работать со СМИ?
PR на рынке B2B: как работать со СМИ?PR на рынке B2B: как работать со СМИ?
PR на рынке B2B: как работать со СМИ?
 

Similar to Diving into VS 2015 Day4

Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1Akhil Mittal
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2Akhil Mittal
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3Akhil Mittal
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5Akhil Mittal
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnetrainynovember12
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdfssusera587d2
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 dayQuach Long
 
235042632 super-shop-ee
235042632 super-shop-ee235042632 super-shop-ee
235042632 super-shop-eehomeworkping3
 
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...Gavin Pickin
 
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...Stefan Richter
 
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...Ortus Solutions, Corp
 
Design patterns 1july
Design patterns 1julyDesign patterns 1july
Design patterns 1julyEdureka!
 
PT1420 Modules in Flowchart and Visual Basic .docx
PT1420 Modules in Flowchart and Visual Basic             .docxPT1420 Modules in Flowchart and Visual Basic             .docx
PT1420 Modules in Flowchart and Visual Basic .docxamrit47
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Sameer Rathoud
 
O365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingO365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingRiwut Libinuko
 
Design Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareDesign Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareEdureka!
 
Meteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoMeteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoArabNet ME
 
IAP auto renewable in practice
IAP auto renewable  in practiceIAP auto renewable  in practice
IAP auto renewable in practiceHokila Jan
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 

Similar to Diving into VS 2015 Day4 (20)

Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
 
Diving into VS 2015 Day3
Diving into VS 2015 Day3Diving into VS 2015 Day3
Diving into VS 2015 Day3
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnet
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
 
235042632 super-shop-ee
235042632 super-shop-ee235042632 super-shop-ee
235042632 super-shop-ee
 
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
 
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...
Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-...
 
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...
ITB2019 ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 V...
 
Design patterns 1july
Design patterns 1julyDesign patterns 1july
Design patterns 1july
 
PT1420 Modules in Flowchart and Visual Basic .docx
PT1420 Modules in Flowchart and Visual Basic             .docxPT1420 Modules in Flowchart and Visual Basic             .docx
PT1420 Modules in Flowchart and Visual Basic .docx
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)
 
O365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingO365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side Rendering
 
Design Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareDesign Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for Software
 
Meteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoMeteor.js Workshop by Dopravo
Meteor.js Workshop by Dopravo
 
IAP auto renewable in practice
IAP auto renewable  in practiceIAP auto renewable  in practice
IAP auto renewable in practice
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 

More from Akhil Mittal

Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release PlanningAkhil Mittal
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questionsAkhil Mittal
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Akhil Mittal
 

More from Akhil Mittal (20)

PDFArticle
PDFArticlePDFArticle
PDFArticle
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
 
RESTfulDay9
RESTfulDay9RESTfulDay9
RESTfulDay9
 
PDF_Article
PDF_ArticlePDF_Article
PDF_Article
 
RESTful Day 7
RESTful Day 7RESTful Day 7
RESTful Day 7
 
RESTful Day 6
RESTful Day 6RESTful Day 6
RESTful Day 6
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
IntroductionToMVC
IntroductionToMVCIntroductionToMVC
IntroductionToMVC
 
RESTful Day 5
RESTful Day 5RESTful Day 5
RESTful Day 5
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Asp.net interview questions
Asp.net interview questionsAsp.net interview questions
Asp.net interview questions
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
 

Diving into VS 2015 Day4

  • 1. Diving into Visual Studio 2015 (Day #4): Code Refactoring Introduction Code Refactoring has always been a challenge for developers. This is one of the major skill that a developer should have to write an optimized , clean and fast code. There were third party tools available to help you achieve this, but none have shown that capability that Visual Studio 2015 has come up with. Visual Studio has always offered code refactoring techniques in tit-bit, but the latest version of Visual Studio i.e. 2015 provides a unique experience altogether to achieve refactoring. There are many features that refactoring of code in Visual Studio provides. We’ll cover few of them like inline temporary variable and introduce local. Refactoring w.r.t. inline temporary variable and introduce local is not only limited to C# but VB developers can also leverage this feature. We’ll cover the topic with one small method as an example and try to optimize it as far as we can. One thing is worth taking care of that code refactoring software and techniques are only meant for sharp developers. If you don’t have an idea what new code will do and it looks strange to you, you should never try it. Case Study I am taking an example of MyProducts class that we created in earlier section. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: public class MyProducts :IProducts 10: { 11: List<Product> _allProduct = new List<Product>(); 12: public MyProducts() 13: { 14: _allProduct.Add(new Product {ProductCode="0001",ProductName="IPhone",ProductPrice="60000",ProductType="Phone",ProductDescription="Apple IPhone" } );
  • 2. 15: _allProduct.Add(new Product { ProductCode = "0002", ProductName = "Canvas", ProductPrice = "20000", ProductType = "Phone", ProductDescription = "Micromax phone" }); 16: _allProduct.Add(new Product { ProductCode = "0003", ProductName = "IPad", ProductPrice = "30000", ProductType = "Tab", ProductDescription = "Apple IPad" }); 17: _allProduct.Add(new Product { ProductCode = "0004", ProductName = "Nexus", ProductPrice = "30000", ProductType = "Phone", ProductDescription = "Google Phone" }); 18: _allProduct.Add(new Product { ProductCode = "0005", ProductName = "S6", ProductPrice = "40000", ProductType = "Phone", ProductDescription = "Samsung phone" }); 19: 20: } 21: 22: /// <summary> 23: /// FetchProduct 24: /// </summary> 25: /// <param name="pCode"></param> 26: /// <returns></returns> 27: public Product FetchProduct(string pCode) 28: { 29: return _allProduct.Find(p => p.ProductCode == pCode); 30: } 31: 32: /// <summary> 33: /// FetchProduct with productCode and productName 34: /// </summary> 35: /// <param name="productCode"></param> 36: /// <param name="productName"></param> 37: /// <returns></returns> 38: public Product FetchProduct(string productCode, string productName) 39: { 40: return _allProduct.Find(p => p.ProductCode == productCode && p.ProductName==productName); 41: } 42: 43: public List<Product> GetProductList() 44: { 45: return _allProduct; 46: } 47: } 48: } We’ll add one more method to this class. The objective of that method will be to return all products from the product list whose price is greater than 30000. I am trying to keep the logic and method very simple for the sake of understanding.I have kept the name of this method is FetchProduct(). Notice that we already had two methods with the same name. Now this will also work as an overload to FetchProduct() method. The above mentioned method is very simple in nature and contains LINQ query that fetches products having price greater than 30000. When you call this method from Program.cs and iterate over the elements we get following result.
  • 3. Program.cs code is as follows. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading.Tasks; 6: 7: namespace VS2015ConsoleApplication 8: { 9: class Program 10: { 11: static void Main() 12: { 13: var myProducts = new MyProducts(); 14: Console.WriteLine( String.Format("Product with code 0002 is : {0}", myProducts.FetchProduct("0002").ProductName)); 15: Console.WriteLine(Environment.NewLine); 16: var productList = myProducts.FetchProduct(); 17: Console.WriteLine("Following are all the products"); 18: 19: foreach (var product in productList) 20: { 21: Console.WriteLine(product.ProductName); 22: } 23: Console.ReadLine(); 24: } 25: } 26: } So, our method is working fine. the question is how much we can optimize this method further. When you click in between products variable, the light bulb icon will show up with some suggestions that you can apply to this line to optimize.
  • 4. Here come inline temporary variable in picture. The light bulb icon says to remove this variable and bring that code to a single line. When you preview the changes that this code assistance is suggesting you get following preview window. It shows that the temporary products variable will be replaced with productList itself therefore helping us to save number of lines as well as memory allocation for a variable. Click on apply changes and you’ll get the refactored code. Now can this code be further refactored. you can take help from light bulb icon. Either click in between productList variable or right click on productList variable and open Quick Actions from context menu.
  • 5. We see here, productList is also a temporary variable and it is suggested to remove that too. Let us preview changes and apply them to get more optimized code. Doing this the productList variable will be replaced by a single return statement, but you’ll notice an error here.if you remember, I said that code refactoring is for intelligent and sharp developers. We see here that while refactoring the code, LINQ query is not encapsulated in the bracket and ToList() method is directly applied to “p” variable. We have to rectify this by putting brackets around LINQ query. This was one of the scenario, and you may face many of such.So you have to be sure about the change that you are about to do. visual Studio only suggests, it does not code for you. Now we have a single return statement. Our code has reduced to just one line and we saved few memory too by ignoring temporary variables. This certainly makes the code faster as well. But can we further optimize this method? Let’s take a shot and click on return statement. You’ll see the light bulb icon again shows up with some suggestions. It says that the method could be converted to an expression bodied member. Let us preview the change.
  • 6. The preview says that the method is converted into an expression. Looking at this I do not find any issue. So we can certainly opt this option for the sake of refactoring. Press apply changes and we get following code. Now if you try to further optimize this method, you’ll not find much scope. Conclusion This was just a small example that I showed on how you can leverage the capability of Visual Studio 2015 in optimizing your code. In the next section of this series I’ll be covering topics like debugging features in Visual Studio 2015. For more technical articles you can reach out to my personal blog, CodeTeddy.