CRM 2015/CRM2013 – JavaScipt to get the current users name

This blog post will show you a quick way to get the name of the user using JavaScript.

Where you might use this functionality

This functionality is useful because you might need to update a User lookup field to a particular user in situations like

  • The current user changed a key field
  • The current user is primary contact for a project, account, deliverable.
  • Set a text field of the users name for reporting purposes.

Why are you mentioning it

To do retrieve the current user name in CRM 2011 it took a soap call to retrieve the user name field using the Xrm.Page.context.getUserId().  Below is a blog post I wrote

CRM 2011 – Setting a user lookup with the logged in user with Javascript

There is now a much easier way to do this in CRM 2013 and CRM 2015.  I found this way whilst reading this forum post

crm 2013: javascript get attributes from other entity in Contact Form

Start with the CRM SDK

The Hosk CRM developer mantra is to always start with the CRM SDK to see what methods and functionality exists which can help.

Searching the CRM SDK first helps you see what functionality Microsoft have added, most CRM developers will be surprised the number of new methods added.

It’s very easy for developers to copy and paste existing code in projects but just because it works it doesn’t mean its the best code to use.

This is classic case, the CRM 2011 code is long and involves a soap call, the new functionality added in CRM 2013 allows you to access the data with one line.

Microsoft Client code page – Client-side context (client-side reference)

There are three useful functions about the existing user (there’s another about language but I’m not including it).

getUserId
Returns the GUID of the SystemUser.Id value for the current user.
getUserName
Returns the name of the current user.
getUserRoles
Returns an array of strings that represent the GUID values of each of the security roles that the user is associated with or any teams that the user is associated with.

 

Xrm.Page.context.getUserId()

This would get you the SystemUser.Id

Xrm.Page.context.getUserName();

This would return a text string of the user name

Setting User lookups

The common reason for retrieving the user name and the user id is because both values are needed if you want to programatically set a lookup field in CRM.

Example code is shown below


var setUservalue = new Array();
 setUservalue[0] = new Object();
 setUservalue[0].id = Xrm.Page.context.getUserId();
 setUservalue[0].entityType = 'systemuser';
setUservalue[0].name = Xrm.Page.context.getUserName();

Xrm.Page.getAttribute("LookupField").setValue(setUservalue)

Alternatives

In the requirement I was working on I used JavaScript because I needed to set a field dynamically and instantly.  Other CRM customizations may have different requirements and you could set the lookup field using a Plugin or a workflow.

What I have learnt

  • Use the CRM SDK to see what functionality exists, there might be a better way
  • Microsoft added a new getUserName method in CRM 2013
  • You need the guid, name and entity type to set the value of a lookup field
  • If you don’t need to set the lookup instantly you can use workflows or plugins
  • CRM forum posts provide extremely useful information from a number of CRM developers

 

CRM 2015 – Why is the System user shown as disabled in the plugin registration tool

Someone asked me why the System user had the word disabled in brackets in the plugin registration tool when editing plugins and can we I still use it.

I have set plugins to run as SYSTEM but I couldn’t remember if the SYSTEM user had disabled in it. I fired up the plugin registration tool, selected a plugin, clicked the Run in User’s Context and found this

System User Disabled

I wasn’t sure whether I should be worried about the disabled or not, had it always been there?

In this example the CRM developer was setting a plugin to run as the SYSTEM user because the plugin need to run with more security privildges than the calling user.

To learn about Impersonation and plugins read my blog post

CRM 2015 – Understanding impersonation in plugins and knowing when to use it

What is the SYSTEM user

My knowledge of the SYSTEM user is it’s a super super in built user which you cannot see inside CRM in any of the views, the SYSTEM user won’t appear in disabled or enable user views inside CRM.

SYSTEM user is used by plugins, workflows to run with elevated privileges and when the user updates any records you will see SYSTEM.

Gonzalo Ruiz has written a great blog post on the SYSTEM and INTEGRATION

Explaining the built-in SYSTEM and INTEGRATION users

The blog post has a few interesting points to consider

  • Nobody can log in CRM as either of these 2 users.
  • These users are always on the root business unit.
  • No security applies to these users (any action is allowed when executing as SYSTEM or INTEGRATION), all security validations are bypassed.

I’m guessing the SYSTEM user shows this SYSTEM (disabled) to indicate the user is disabled from user CRM as a general user.

Why is named SYSTEM (disabled)?

SYSTEM (disabled) lets the CRM developer know they are selecting the special SYSTEM user and not a user created user who could also have the name SYSTEM.

I did check some other CRM instances (CRM 2011, CRM 2013 and CRM 2015) to see if SYSTEM always had SYSTEM (disabled) and in the three instances I looked at all had the words disabled in brackets after the SYSTEM user.

I’m not sure labelling the system user as disabled is the best idea because it caused concern we had somehow disabled the SYSTEM user or maybe we shouldn’t select it because it was disabled.

It seems it’s just Microsoft Dynamics CRM having a quirky way to indicate the SYSTEM user is special and not to be confused with other non super users (surely there is a better way)

Hosk’s Top CRM Articles of the week – 24th August

Article of the Week

a good example and justification of using access teams to share record

A great post to help understand when and why to use access teams.  I wrote a brief article on access teams for CRM 2013 – MB2-703 – Access Teams and Access Team Templates how to use them and key facts

Why Use Access Teams in Dynamics CRM 2013

Initially I wasn’t sure the purpose of Access teams but the article above and this excellent article from Adam Vero should help you understand the concept.

CRM 2013 – Why are access teams marooned?

Oddly there isn’t a way to export the configuration for access teams, which means you have to recreate them.  This is another case of a Connect issue raised years ago and mainly ignored (Is Microsoft Listening to the Dynamics CRM Community?)

Console app for moving CRM Access Team templates

Luckily there is a console application which can copy the CRM access team templates written by Lucas Alexander.

Best of the Rest

CRM 2015 – How to diagnose plugin errors

Hosk blog with advice on how to diagnose Plugin errors

Using CRM from an external website – part 3: Stage one “Web API”

The series continues linking CRM with an external website.

Adding Custom Button on Security area in Dynamics CRM 2015

Ever wondered how to add a custom button to the security, nope me neither but it doesn’t you won’t have to do it in the future.

summary of all the import privileges

How to enable and disable users from importing and exporting in CRM

CRM 2011 – Javascript to set the current date and time

JavaScript showing how to set a CRM field to the current data and time

CRM UI Testing using Dalek

Interesting article on writing UI Tests for CRM, I will admit to never having heard of Dalek before.

What are the limitations of Microsoft Dynamics CRM Online and how do you work with them?

When you write customizations for CRM online you need to think differently

Use SQL Tracing to find the SQL query generated for Dynamics CRM Platform Operations for CRM On-Premise

Match your CRM queries to SQL queries, very useful.

New Localizable Attributes in Dynamics CRM 2015

Very useful

Looking at upgrade approaches

Things to consider about upgrading CRM and keep up with releases, rollups and service patches.

Using Microsoft Power BI Desktop to build Dynamics CRM Online reports Part 2

Hmmm Power BI seems pretty darn good.

programming
Why Software Development Time Estimation Doesn’t Work and Alternative Approaches

Why KISS isn’t easy

More Agile, More Problems

other
teaching is important as anything else

thinking small with Malcolm Gladwell

breaking the mold

8 MASTER STRATEGIES FOR PUBLIC SPEAKING

The Jerry Seinfeld and John Grisham Productivity Hack

Previous top picks

Hosk’s Top CRM Articles of the week – 10th August

Useful Hosk Links

Hosk list Of CRM 2013 Tools

A list and review of CRM 2013 tools, this will probably work in CRM 2015 as well

Hosk’s CRM Developer Articles

A collection of my favourite CRM Developer articles I have written

MB2-703 – CRM 2013 Customization and Configuration Certification Information

All the CRM 2013 content to help you pass the exam

HoskWisdom – Hosk Developer Quotes

 Words of Wisdom from the Hosk.  I have written over 900 articles, surely I should have said a few memorable things

CRM 2015 – How to diagnose plugin errors

This blog talks about a plugin error which I have seen a number of times when using the Plugin Developer Toolkit, it will discuss how to diagnose plugin errors in general.

Before I talk about plugins can I encourage people to vote on the connect item to get the CRM Developer toolkit working with Visual studio 2013, if you can’t wait for Microsoft to fix it then read my blog post CRM Developer Toolkit Alternatives

Hosk CRM Brain

I like to think of my blog as my CRM brain uploaded to the internet, so whilst reading this you are currently crawling through my CRM brain.  This allows me to search my CRM brain when my real brain forgets how I resolved a problem, actually sometimes I even forget I have experienced a problem and get pleasantly suprised when I have found not only did I have the problem before but I blogged the solution.

The benefit of me blogging about CRM is I benefit and other people who read and search my blog.

My goal in writing articles focused on errors is not only to write about how to resolve the issue but additionally look into the cause of the problem and , the WHY.

Knowledge helps when things go wrong

There is always a difference between theoretical knowledge and practical knowledge.   You can learn the theory of something but find it’s different when you try to use the theory in practical use (e.g. after reading about plugins you then try to write a plugin) you there are gaps in knowledge which you quickly find.

When developers start to plugins they usually go through

  • learn to write plugin code, find lots of errors
  • try to deploy plugin, error haven’t signed the plugin, error permissions etc.
  • Slowly but surely the developers experience fewer problems or problems they know how to resolve

Indepth knowledge of how Microsoft Dynamics CRM works and the underlying plugin infrastructure becomes extremely important when things go wrong.  When errors appear and hold up development, developers need to understand the cause of the error but why it’s complaining, the answer is usually understandable if you understand

  • how the CRM developer toolkit works
  • The various parts of the CRM Developer toolkit
  • The CRM plugin execution framework
  • The roles and privileges needed to deploy plugins

Some useful Hosk Plugin blog posts

The CRM developer toolkit is great (which is why I get annoyed it hasn’t been updated because it automates a lot of the repetitive actions needed to deploy a plugin using the plugin registration tool.) but I feel CRM Developers should learn how to use and deploy plugins using the plugin registration tool.

I use the plugin registration tool to inspect what plugins and steps are deployed and the ability to change the view to see what plugins are deployed for each entity is really useful when investigating bugs on CRM solutions you are not familiar with.

Most of the time you don’t want to mix using the plugin registration tool and the CRM developer toolkit because the CRM developer toolkit will overwrite the changes you make manually next a developer uses it to deploy CRM customizations.

The plugin registration tool is great for viewing the plugins deployed and its portability allows you to use it in customer environments.

If the CRM Developer toolkit gets in a mess you might need to use the plugin registration tool to quickly update or deploy a plugin whilst you fix the plugin developer toolkit.

I had an error previously but the problem was the CRM developer toolkit had got out of sync and I struggled to resolve this problem.  You can read about my frustrations with the CRM Developer toolkit

Dealing with Plugin errors

If When you experience a plugin error I would recommend you first read my blog on common problems because I cover the most common errors.

If you don’t find the answer then stop and think about the potential cause of the problem.  Many developers can go into a mild panic mode when they encounter an error, instead of logically thinking about the problem they instantly go and get a senior developer to help them.

Then when the senior developer is at their desk, they explain the problem.  The process of explaining the problem to the developer, the solution to the problem can become clear.  This is known as rubber ducking or I call this Cardboard developer

When you encounter a plugin problem or CRM developer problems, follow these steps

  1. Stop
  2. Engage Brain\Think
  3. What’s happening?
  4. What should happen?
  5. Make a list of the possible causes of the problem
  6. Investigate your list

If you can’t resolve the problem, you can then at tell the developer what you know, what you have tried.

I don’t encourage any developers to suffer in silence but it’s more beneficial for you own personal learning if you try to understand and resolve problems yourself.  The major benefit of trying to resolve the problem yourself is you get in the habit and become less dependent on the help of your colleagues.

Don’t Assume, know

Don’t Assume, Know is a Hosk mantra I tell myself when investigating problems or debugging.  I have wasted many hours investigating problems and looking for solutions based on an incorrect assumption.  When dealing with problems don’t assume anything, check assumptions and cross them off.  Lots of times you will find the problem.

Plugin Error Messages

The error messages Microsoft Dynamics CRM throws are a mixture of a confusing statement with a nugget of truth tucked inside.  To developers new to CRM development they are just unhelpful messages.

As your experience and knowledge of CRM development increases you will find they often point you in the right direction but you need to have built up a map of the CRM landscape, so you know where to go and check.

Plugin Error Example

This is common error I have experienced a few times but I was trying to deploy a plugin using the CRM developer toolkit and I got this error

Error registering plugins and/or workflows. Plug-in assembly does not contain the required types or assembly content cannot be updated.

Lets break down the message to try and decify the problem

  1. It can’t register the plugin/workflow
  2. Plugin Assembly does not contain required types or the assembly cannot be updated.
  3. So we know the plugin assembly (the DLL) exists but it cannot update it.

The first thing to do is know not assume.  So I opened the Plugin Registration tool and found the DLL.  I could see it had three steps.

I then looked at the RegisterFile.crmregister file and found this had two steps.

The problem was because we were trying to update an assembly with 2 steps but the assembly had 3 steps.  It couldn’t update the assembly because it was too different and this error message was letting us know (in a slightly confusing way).

I have experienced this problem before and the solution to the problem is to unregister the Assembly and install it again.

This problem has occurred when I have created new plugins and sometimes when I have updated a plugin maybe in a different solution but for some reason I couldn’t update the DLL.

In this case how the extra step got into the assembly was a complete mystery but it’s OK to delete the plugin assembly because I knew I was going to deploy it again and install a new version of the Plugin assembly.

Hosk’s Top CRM Articles of the week – 19th August

Article of the week

Dynamics CRM 2015 JavaScript Form Notifications on Steroids

Great article on how to beef up the notification in CRM by using the solution provided for free on codeplex.  Those boys at Magnetism are a great bunch

call workflow in CRM 2015 easily from Javascript

I really liked this article as well

Best Of the Rest

CRM 2015 – How to decompile a plugin Assembly (DLL)

Hosk blog post talking about how to decompile a plugin assembly and more importantly when and why you might need to do this.

Gamifying Sales Comp

It’s all about the games you can play to motivate your CRM users at the moment, even I wrote a blog post a couple of weeks ago Is Gamification in a Microsoft Dynamics CRM a gimic?

Replicate Right Click behavior of Dynamics CRM Grid on Custom Grids

Interesting article about adding right click behaviour

Why understanding abstractions can help you write better code

read the article and find out why?

Adding JavaScript to Quick Create Forms in CRM 2015

how to isolate the quick create form in and write JavaScript just for it.

looking at CRM performance issues

Always good to know about performance issues before your CRM suffers from them.

Sample code to check if User is a member of a team C# CRM 2011/2013/2015

Simple but useful

Building not in queries in advanced find

A classic requirement

Angular with TypeScript

Pluralsight have a training course on Angular with TypeScript which is a dream for Dave Berry

Tips & Tricks for debugging unfamiliar AngularJS code

indepth article looking at debugging AngularJS, I haven’t seen any CRM projects use AngularJS yet but it might only be a matter of time.

Workflow ExecutionTimeSpan

good article because it shows some creative thinking, whilst teaching you about the underlying data in CRM.

Multi select field for Dynamics CRM 2013/2015

I haven’t needed a multi select for quite a while but I remember when it use to crop up all the time.

A free customizable Editable Grid for Dynamics CRM 2013/2015!

Does what it says

programming

Is Egoless Programming still relevant?

When Does DRY Become ARID?

Excellent article on the factory pattern using warriors and wizards.

how to become a better coder overnight

How Good Developers Deal With Bad Code

15 Ways To Write Beautiful Code [That Have Nothing To Do With Testing]

Other

Mental Model: Misconceptions of Chance

Lenovo preloaded laptops with reformat-resistant perpetual crapware

How To Be Loved By Everyone: 6 Powerful Secrets

The Science of Obesity

4 Tips to Boost Your Creative Thinking Skills

Schopenhauer: On Reading and Books

Previous top picks

Hosk’s Top CRM Articles of the week – 10th August

Useful Hosk Links

Hosk list Of CRM 2013 Tools

A list and review of CRM 2013 tools, this will probably work in CRM 2015 as well

Hosk’s CRM Developer Articles

A collection of my favourite CRM Developer articles I have written

MB2-703 – CRM 2013 Customization and Configuration Certification Information

All the CRM 2013 content to help you pass the exam

HoskWisdom – Hosk Developer Quotes

 Words of Wisdom from the Hosk.  I have written over 900 articles, surely I should have said a few memorable things

CRM 2015 – How to decompile a plugin Assembly (DLL)

This blog post looks at how to decompile plugin code because I had a problem recently where I needed to do it.  The process will work in all version of CRM because fundamentally it works at DLL level rather than CRM level.

It’s a useful to understand because there are some instances where you need to know what code has been deployed because it might be different from the code you have or the code in your source control.

The problem – Why isn’t my fix working?

A bug fix I had deployed and tested in our dev environment and test environment suddenly stopped working when deployed to the customer environment.

This isn’t an unusual problem but an annoying one for developers.

Don’t assume, know

When bug fixing and testing try to avoid the trap of assuming because assumptions are often wrong, resulting in missing the obvious source of the problem, spending time testing other possible reasons for a problem.

Usually when a bug fails on a different environment I want to recreate it in the DEV environment where I can easily debug it.
For this problem we have two internal instances

DEV
TEST

I tested my fix in DEV and it seemed to work and then I tested the fix in internal TEST environment and found my fix didn’t work, why?

Finding the plugin code deployed

There are instances when you need to find the code deployed in a plugin. It’s possible to version plugins but CRM developers don’t bother versioning their plugins and I currently don’t version the CRM plugins.

Plugins can be versioned in the same way solutions are version in CRM

major.minor.build.revision

You need to think about versions and solutions because when you change the major number of a plugin assembly CRM considers it a completely different plugin assembly

Microsoft has a good article on Plugin Assembly

This article on how to upgrade version

Hardcore CRM: Do a major upgrade of a plugin version!

What to do if you don’t use assembly versioning

The problem I had was how could I tell what code was inside the plugin and if my fix was deployed?  The code in TFS (Source Control) was correct and up-to-date but I tested the functionality and could see it wasn’t working.

I decided to download the plugin assembly dll and decompile the code.

The tools I used was

XRMToolbox

Go to releases and click latest release if you want to download the application not the source
https://github.com/MscrmTools/XrmToolBox/releases

The XRMToolbox has a tool called Assembly Recovery Tool. This tool allows you to connect to a CRM instance, it loads all the assembly DLL’s (which can some time), you can choose to download any of the Plugin assemblys(dll file). This will give you the dll, which you can decompile using a different tool.

Once you have the DLL file you can decompile the dll using a tool such as

ILSPY

There are lots of other decompilers out and the main reason I use ILSPY is because its free

To use the decompiler you open it up, select a DLL or copy one to the application, below I have selected a HoskCRMDev2013 plugin.  The dll’s in blue are dependant plugins

decompile plugin

If you then click on one of the methods, it decompiles the code, which you can view it in the yellow right hand screen.

decompile plugin1

ILSPY has a few neat options to save the to file.

A few notes on decompiling DLLS

DONT decompile DLL’S you or the company you work for doesn’t own because basically you are viewing the source code.

I’m not sure about the legality of it but it’s probably illegal, particularly if you don’t own the intellectual property.

If you aren’t sure if you should decompile a DLL think about it like this.  If you went to the owner of the source code and asked to view the source code, would they let you?

A common cause of decompiling plugins/custom workflows is to see what has been deployed if plugin versioning is not used.

Be warned decompiled code is slightly different, often the variables don’t have the same name.

If you are concerned about your dlls being decompiled there is a tool to encrypt them, I haven’t used it.  The discussion on StackOverflow is a good place to start if you are interested

Protect .NET code from reverse engineering?

When might you need to decompile a DLL?

Surprisingly there are quite a few scenarios where you might need to decompile a DLL, I will go through some of the common scenarios but the

Lost source control

I have seen scenarios where a company has lost the source control for code which has been deployed.  Often its old legacy systems and most people who worked on the project have left the company

Deployed with source control checked out pending

A developer deploys some code, forgets to check in the code.  The developer then might leave the company, go on holiday and can’t be contacted.  You need to know what code has been deployed and what code might not be checked it.

Plugin won’t deploy from CRM Developer toolkit

Sometimes a plugin won’t deploy and you will get an error like this

Error registering plugins and/or workflows. Plug-in assembly does not contain the required types or assembly content cannot be updated

The reason for this error is often because the deployed assembly file (DLL) is different.  It might have an extra step and you are not updating the file but trying to replace it.  CRM doesn’t like this.

I had an example of this recently and there was an additional step in the deploy DLL.  I used the plugin registration tool to compare the steps but I wasn’t sure what was in the extra step.  So I download the DLL and looked at the code.

What has been deployed

This is the problem I was experiencing for this bug.  I needed to check if the code deployed was the same as the code in source control, the only way I could do it was to decompile the code and compare.

Plugins without versioning

A common cause of decompiling plugins/custom workflows is to see what has been deployed if plugin versioning is not used.

Multiple Developers Versus Source Control

When you have multiple developers working on a project, source control can sometimes lead to problems with people not getting the latest code and deploying an older version

Who deployed the different plugin?

I was wondering how the different plugin version got deployed. I wondered if I could work out what solutions were imported

I remember review a useful tool a while ago the Solution History tool, which is a tool which works with the XRMToolbox

You can download the tool here

The tool usefully told me what solutions had been imported and what files were included.

I could see the solution had been changed and who imported but I couldn’t tell what version of the Plugin Assembly had been deployed.

This tool would be extremely useful if the project you are working on imports multiple solutions without changing the version number.

What gets updated when you import a plugin to the database?

In the background when you import a plugin it updates system entity called plugin. I wondered if I could select these entities to see when they had been updated.

The problem is you can’t select system entities in an advanced find, so I remember another tool which works with the XRMToolBox the FetchXML Builder

You can get the tool here

This tool is useful because it has GUI interface to allow you to create Fetch XML queries. This means you can select system records.

The real beauty of this is you can create FetchXML queries and then use them in your plugins.

I wanted to use the tool to easily query the system entity of plugin

retrieve plugin

Which produces the FetchXML below

<fetch count ="50 " >
<entity name ="pluginassembly " >
< filter>
< condition attribute= "name" operator=" eq" value ="Full Assembly Name " />
</ filter>
</entity>
</fetch>

This allowed me to retrieve when the plugin was changed and by who. I was wondering if someone had directly deployed a plugin to the Test environment and bypassing the Solution import phase but it turned out not to be the case.

I couldn’t work out who had deployed an old plugin version and the important point was I had the resolution to the problem (although you would like to be confident it wouldn’t happen in the future)

Summary

This blog should show you how to download and decompile a DLL file.  There are certain scenarios where you aren’t sure if the code deployed is the same as the code in your source control.

Downloading and decompiling DLL’s is another tool to put in your development bag, make sure you use it for good not evil.

Why understanding abstractions can help you write better code

I have been a developer for many years, working with APL, Java, Javascript and C# and I considered myself a decent programmer (doesn’t everyone?)

I had read articles on the S.O.L.I.D principles

I had a decent grasp of OO design principles and understanding Polymorphism, encapsulation, abstraction and inheritance.

I used interfaces and abstract classes but it was only recently that I understood some of the benefits of abstraction with regards to code design.

This  understanding has come through reading (re-reading in some instances) various parts of the book mentioned below

  • Code Complete 2
  • Clean Code
  • Head First Design Patterns
  • Design Patterns – Elements of Reusable Object-Orientated Software
  • S.O.L.I.D design principles

Head First Design Patterns mention these design principles, which I found really useful to understand the effects of good OO design

  • Encapsulate what varies
  • Favour composition over inheritance
  • Program to interfaces, not to implementations
  • Strive for loosely coupled design between objects that interact
  • Depend upon abstractions. Do not depend upon concrete classes

Knowledge is like a jigsaw puzzle

I had read some of the material a long time ago, on my recent reading I found my initial understanding of some of the concepts was lacking a bit of understanding.  This isn’t unusual when trying to understand complex and abstract concepts, here is an interesting article on that phenomenon.

When learning new ideas and concepts you can get a partial understanding where bits of it are clear, whilst other areas can be fuzzy.  I view information/ideas as having a 3D property where it suddenly makes sense when you view the information/idea from a different perspective.

This article talks about the metaphor as knowledge as a jigsaw puzzle

Your understanding grows as more pieces of the puzzle fall into place

What is Abstraction?

Before looking at abstraction from a coding point of view what is a general definition of abstraction, Wiki has a few definition

http://en.wikipedia.org/wiki/Abstraction

Abstraction in its main sense is a conceptual process by which general rules and concepts are derived from the usage and classification of specific examples, literal (“real” or “concrete”) signifiers

Conceptual abstractions may be formed by filtering the information content of a concept or an observable phenomenon, selecting only the aspects which are relevant for a particular purpose. For example, abstracting a leather soccer ball to the more general idea of a ball selects only the information on general ball attributes and behavior, eliminating the other characteristics of that particular ball

Abstraction – Computer Science

In computer scienceabstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level

When abstraction proceeds into the operations defined, enabling objects of different types to be substituted, it is called polymorphism. When it proceeds in the opposite direction, inside the types or classes, structuring them to simplify a complex set of relationships, it is called delegation orinheritance.

 

Code Complete 2 gives a clear definition of what an abstraction is

abstraction is the ability to view a complex operation in a simplified form.  A class interface provides an abstraction of the implementation that’s hidden behind the interface

What is an abstraction?

Abstractions are used regularly in everyday language, we use abstraction when talking about lots of things, such as
 
  • Chair
  • Table
  • Computer
  • Mobile Phone
These are abstract ideas which everyone understands but people don’t have a mobile phone, they have an exact make of mobile phone but most people don’t talk about the exact type by the abstract type of mobile phone.
 
Mobile phones have some core data
 
  • Ringer
  • Screen
  • buttons
  • Mic
  • Speaker
A mobile phone would be a good case for a Abstract class which could be inherited by a real instance which may add more features.

Why is understanding Abstraction important

Abstractions help hide concrete code which can change with abstractions such as interfaces and abstract classes which are less likely to change.

Using abstraction limits dependencies in code, reduced dependency means reducing the effect of change in your code.

Two of the key long term goals for developers when writing code

  1. Increase the readability of the code
  2. Minimise dependencies in code, reducing the effects of change

The two goals will make maintaining the code easier, below I talk how abstraction can help you to achieve those goals.

Junior developers seem reluctant to use abstractions in code because of a mixture of not understanding how abstractions work and because they are focused on getting the code working and bypass the creation of abstractions, which can lead to big complex methods, few classes and no abstractions.

Junior developers are focused on the short term goal of getting the code working with the intent of leaving the design and creation of abstractions until later (later often doesn’t come).

Which leads me to write articles like the two below

 

Understanding Abstraction

Abstraction is one of the key principles behind many of the OO design principles such as

  • Inheritance
  • Polymorphism
  • Composition
  • Benefits of abstraction
  • Code is easy to understand
  • Manages change and the effect of chnage
  • Creates cohesive code – it finds common fields
  • Create loose coupling

Abstraction refines concepts to their core values, stripping away ideas to the fundamentals of the abstract idea.  It leaves the common details of an idea.

Abstractions make it easier to understand code because it concentrates on core features/actions and not on the small details.

My understanding started to grow whilst reading these two OO design principle

  • Encapsulate what varies
  • Program to interfaces, not to implementations.

The various books and articles concentrated on the benefits of these two design principles I start to understand how abstraction could reduce dependences and the affect of changes on code, you can see I started thinking about whilst writing this article Information Hiding.

How to find abstractions?

In the blog post  How to find classes I talked about how to find classes, finding abstractions is a similar exercise.  Common abstractions are
  • Nouns – things, people, systems
  • Verbs
  • Types
  • Behaviours
  • Is A – Inheritance
  • Has A – Behaviours

Actions/Verbs are often abstractions e.g. Drawing, validating, processing, routing.

When I mention types I am referring to

Abstractions are useful in life

People use abstractions all the time, you often mention 

  • Computers
  • Chairs
  • People
  • Cars

You don’t talk about the distinctive type of car but say car in general and people will understand you what you are talking about.

The same idea can be used in your code design.  You can find a common action like validating, drawing, Updating, exceptions.  The common action will be the interface and the concrete classes can hide behind it.

Exceptions are a good example you have a core exception (the ones lazy programmers throw when they don’t want to specify the exact error) and then distinctive exceptions extend it.

Exception is the abstraction and InvalidPluginExecutionException , NullReferenceException etc are the implementing concrete classes.  

Examples

I had some code where which was triggered on the change of state and depending on certain values it would be go a different route, there were lots of different routes

The abstraction was Route, I made this an interface and it was then implemented by many different Routes through the system.  If the users wanted more routes the code was made to encapsulate what varies.  

Half the code used the interface Route, any changes by adding more routes would mean the code which used the interface would need to change or be effected by the change.

Why Abstractions are so important

Abstractions help create well designed code.

The code is easy to understand because if you have captured the right abstractions is obvious what the code is doing.

Abstractions help create loosly coupled code.  The reason is the abstraction acts like a type and encapsulates the potential changes behind the abstract class/interface.  

To understand why this is import you need to understand the statement

code to an interface, not a concrete class.

A classic abstraction is creating a database layer, an abstract class or interface which parts of the code users to interact with the database. The abstract minimises the effects of change because the code which interacts with the interface will not be effected by the implementation/concrete class changing.  It also allows the code to change in the future and more types being added.

Adding more types will not effect any code which interacts only with the interface.

This brings me nicely to the design principle

Encapsulate what varies

Business rules or algorithms are a good example.  When you have a behaviour or type you have an Abstraction.  Using an abstract class will manage the effects of change and create a loosely coupled system which will manage the effect of change.

Understanding abstraction can take time

Abstractions are used everywhere because they make life easier

  • Common language
  • S.O.L.I.D principles
  • Design Patterns
  • Design Principles

It was until I began to understand the terms Encapsulate what varies and Code to an interface that I slowly (very slowly) could see how abstractions made it easier to organise code/reduce dependencies and how abstractions through abstract classes and interfaces helped manage the affects of change.

Change can ripple through poorly designed code because poorly designed code is fragile, you change one part of it and an unrelated part of the code suddenly breaks.  The reason for this sudden breaking is dependency.

Abstractions (interfaces/Abstract classes) reduces dependencies and the abstraction acts as a barrier to dependency and change.

The next stage of my personal appreciation of abstraction was when writing the blog post – How to find classes, the method of looking and finding classes through nouns and types made it easier for me to identify potential abstractions.

Studying design patterns and good code will help you to understand and learn how great code uses abstractions.  The two books below are great books to get started with design patterns, my vote goes to Head First Design Patterns because it’s easier to get started with.

Summary

Abstractions are a handy tool to understand when designing your code, it can make maintaining code much easier because you will improve readability and reduce dependencies in the code.

It’s definitely time well spent understanding abstractions in code design and it will make designing code easier.

Understanding abstractions can make you look at your existing code base from a different perspective because the potential abstractions highlight where the code might change in the future and areas of potential refractoring.