Rob Kraft's Software Development Blog

Software Development Insights

Advantages of Pure Functions and Idempotent Functions in .Net

Posted by robkraft on June 28, 2014

Summary

This article will define a “Pure Function” and an “Idempotent Function”. It will also explain the advantages of each type of function using examples in C# .Net.

Definitions

A method is a “Pure Function” when it always returns the same results when given the same inputs.  This method is a “Pure Function”:

An Idempotent method

This method is not a “Pure Function”:

A method that is not Idempotent

“Idempotent Functions” have two slightly different definitions.

  • In much of computer science, an “Idempotent Function” is a function that always returns the same result when given the same input and can include calls to methods that retrieve data from a database and also calls like HTTP GET and HTTP DELETE.  Methods that can be called repeatedly that will return the same result are “Idempotent”.

 

  • In “Functional Programming”, “Idempotent functions” are more like “Pure Functions” that go a step further. In “Functional Programming”, if you take the output of an “Idempotent function” and call that function again using the output of the last call as the input for the next call, you will get the same result again. Here is an example of using an “Idempotent Function” named abs:

var x = abs(-3); //x = 3

var y = abs(x); // y = 3

The result of calling abs(-3) is 3.  And that is the same result as calling the abs(abs(-3)).

More succinctly:

abs(abs(x)) = abs(x)

Apology

I previously wrote an article that I titled “Advantages of Making Your Methods Idempotent and Static in C#“, but I misunderstood idempotent. My article was really about “Pure Functions”, not “Idempotent Functions”. So in this article I attempt to make amends for putting something untrue on the Internet.  I want to think Phil Atkins in Cambridge, UK for patiently and persistently helping me to realize the error in my original article.

Advantages of Pure Functions

When adding methods to classes, many developers spend little time deciding if the method should be a pure function. Making use of the properties in the class causes the method to not be a pure function, as in this example of the method named ReturnNumberOfDaysSincePersonWasBorn:

Here is the ReturnNumberOfDaysSincePersonWasBorn method re-written to be a pure function:

A method that is not Idempotent

And here is another version of the method that is not a pure function. This time, the method is not a pure function because it is changing the value of a variable (Age) scoped outside of the method.

Here are the advantages to methods that are pure functions:

  • The methods are easier to maintain. They are easier to maintain because a developer needs to spend less time analyzing the impacts of changes to the method. The developer does not have to consider the state of other inputs that are used in the method. When considering a change to a method that is not a pure function, the developer must think about the impact on properties used in the method that were not passed in.
  • The methods are easier to test. When writing a unit test, it is easy to pass values into the method and write the test to verify the correct output. But writing tests on methods that are not pure functions take longer and are more complicated because more setup or injection of values is necessary for the test.
  • The methods are easier to re-use. You can call the method from other places in the module, or call the method from several different modules easily when the method is a pure function.
  • The methods are easier to move to other classes. If you have a pure function in one class and you want to move it to a utility class to be used by other modules, it is easy to do so.
  • The methods are more likely to be thread-safe. Pure functions don’t reference variables in shared memory that are being referenced by other threads. Caveat: variables such as objects that are passed by reference could still experience threading problems when used inside of static methods that are pure functions.

Resist the Temptation!

When you encounter a case like the one below, where Method3() needs the BirthDate for a calculation, it can be tempting to change the methods from static to be non-static and to reference the BirthDate property in Method3(). The other alternative is to pass the BirthDate into Method1(), and from Method1() to Method2(), and from Method2() to Method3(). Although we don’t like to make those changes, doing so allows keeps the method as a pure function and keeps the advantages provided by pure functions.

Resist the Temptation to Lose Idempotency

In C# .Net, if you are unable to mark your method “static”, then it is probably not a pure function. If the method makes database calls, API calls, updates properties outside of the method, or uses variables that have scope outside of the method, then it is not a pure function, but it may still be considered idempotent according to the non-functional definition of idempotent.

Advantages of Idempotent Functions

If you are not a functional programmer and you define idempotent functions as “functions that always return the same result for specific inputs”, then the benefits of idempotent functions are the same as the benefits of pure functions, except when they involve retrieving or update data in locations outside the function.  I rarely think about idempotent functions from a functional perspective, but idempotent functions do provide the following benefits to intelligent code compilers.

  • In some languages, if a compiler recognizes that calling abs(abs(abs(abs(x)))) will always return the same results of abs(x), it can substitute abs(abs(abs(abs(x)))) in the written code with the more efficient abs(x) in the compiled code.
  • In some languages, if a compiler recognizes that a function is idempotent, it may be able to cache the result of the call to the function and provide the cached value in place of making calls to the function again with inputs previously used.

In functional languages, the primary advantages of idempotent functions do not apply to the developer writing and maintaining code, but rather to the compiler and performance of the program.

 References

http://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning

 

Posted in Code Design, CodeProject, Coding | Leave a Comment »

Advantages of Making Your Methods Idempotent and Static in C#

Posted by robkraft on June 22, 2014

THIS ARTICLE IS INCORRECT

I apologize for putting incorrect information on the Internet.  This article explains “Pure Functions”, not “Idempotent Functions”.  I have written a new article to provide a more accurate description of “Idempotent” and also “Pure Functions” here:

http://csharpdeveloper.wordpress.com/2014/06/28/advantages-of-pure-functions-and-idempotent-functions-in-net/

My thanks to Phil Atkins in Cambridge, UK for making me aware of my error.


Read the rest of this entry »

Posted in Code Design, CodeProject, Coding | Leave a Comment »

Use Fuzzy Hours for Your Software Task Time Estimates

Posted by robkraft on June 14, 2014

Like many software development shops, we need to provide estimates of the time required to fix each bug and add each new feature.  The primary reason for the estimates is to set expectations for when tasks will be completed and to prioritize what is to be worked on.

As an agile shop, we have tried a few scales for estimating such as:

tiny, small, medium, and large and also the Fibonacci sequence:    1, 2, 3, 5, 8

but the one we have been using for years that we like best is fuzzy hours.

We use the symbols 1,2,3, and 4 where:

  • 1 means 0 to 2 hours
  • 2 means 1 to 8 hours
  • 3 means 4 to 40 hours
  • 4 means more than 30 hours

Notice that our ranges overlap and that is what makes them fuzzy.  When an estimator feels an estimate is in a fuzzy zone it is up the estimator to pick one zone or the other based on their gut feeling.

We have also learned that the velocity for all items sized 1 and 2 are the same, and items with a size 3 take only slightly longer to reach a completed state (development, testing, quality assurance, and documentation all complete).  Items with a size of 4 take longer, but only about twice as long on average as a 3.

Posted in Estimating, Process | Leave a Comment »

Use “NETWORK SERVICE” to Start SQL Server Service in 2014 on Local Computer

Posted by robkraft on May 14, 2014

I had a really hard time getting the SQL Server 2014 install to succeed.  I spent days on it.  I uninstalled all my earlier SQL Server Editions, which is a tedious process because you need to uninstall a lot of different components in specific order.  The SQL Server 2014 install then succeeded, but the SQL Server service would not start.

Event viewer showed this error when trying to start SQL Server:
Initializing the FallBack certificate failed with error code: 1, state: 20, error number: 0.

I tried configuring the SQL Server Service to start using a different windows account, but that did not work either, although I was on the right track.  I did need to change the account used by SQL Server, but I needed to do it during the install process.  So, I uninstalled all the SQL Server components again, then ran the install again.

Apparently the default SQL Server service account is not working on my Windows 7 machine, so I need to pick a different account, and that account needed to be “Network Service”.  I tried several other promising looking accounts such as “Administrator”, “LOCAL SERVICE”, and “SERVICE”, but only “NETWORK SERVICE” from my local machine security group worked.

Don’t do this on production servers, it is not the best security choice.

Select NETWORK SERVICE to get SQL Server 2014 to work

Select NETWORK SERVICE to get SQL Server 2014 to work

Posted in SQL Server | Leave a Comment »

How I Figured Out Why I Could Not Get To My WebSite Hosted at Arvixe.com, But Others Could

Posted by robkraft on April 19, 2014

I encountered an unusual problem last night when I attempted to view one of my web sites (http://www.KraftSoftware.com).  I could not get to the web site.  Fiddler showed me a 502 response.  My site is hosted at arvixe.com and I use the name cp.violet.arvixe.com to connect to and manage my web site, but I also could not even connect to cp.violet.arvixe.com.  I scanned twitter for arvixe but found no one else complaining about outages.  Maybe others had not realized the problem yet.  Fortunately I was able to get to support.arvixe.com to chat with a technician.  He said there was no problem, that both sites were accessible and ended our chat.  That did not please me.  I opened a chat with a better technician at arvixe.

He told me that they could access the site, and we bounced some ideas back and forth.  I sent him the result of my traceroute, then I went to bed.

Tracing route to stats.violet.arvixe.com [198.252.79.4]
over a maximum of 30 hops:

1     1 ms    <1 ms    <1 ms  192.168.1.1
2    36 ms    28 ms    30 ms  cpe-65-28-0-1.kc.res.rr.com [65.28.0.1]
3    16 ms    15 ms    12 ms  tge7-2.lesmmo11-cer1.kc.rr.com [65.28.16.138]
4    13 ms    17 ms    13 ms  tge0-9-0-7.ksczmogn01r.kc.rr.com [98.156.42.246]
5    39 ms    27 ms    27 ms  ae30.dllatxl3-cr01.kc.rr.com [98.156.42.0]
6    28 ms    27 ms    27 ms  107.14.19.92
7    25 ms    24 ms    24 ms  ae-3-0.pr0.dfw10.tbone.rr.com [66.109.6.209]
8    24 ms    50 ms    34 ms  po21.bbr02.eq01.dal01.networklayer.com [66.109.9.222]
9    29 ms    28 ms    24 ms  ae5.dar01.sr01.dal05.networklayer.com [173.192.18.215]
10    24 ms     *       52 ms  po1.fcr03.sr03.dal05.networklayer.com [173.192.118.143]
11     *        *        *     Request timed out.
12     *        *        *     Request timed out.
13     *        *        *     Request timed out.
14     *        *        *     Request timed out.
15     *        *        *     Request timed out.
16     *        *        *     Request timed out.
17     *        *        *     Request timed out.
18     *        *        *     Request timed out.
19     *        *        *     Request timed out.
20     *        *        *     Request timed out.
21     *        *        *     Request timed out.
22     *        *        *     Request timed out.
23     *        *        *     Request timed out.
24     *        *        *     Request timed out.
25     *        *        *     Request timed out.
26     *        *        *     Request timed out.
27     *        *        *     Request timed out.
28     *        *        *     Request timed out.
29     *        *        *     Request timed out.
30     *        *        *     Request timed out.

Trace complete.

The next morning an Arvixe tech had sent me an email asking me for my IP address.   I supplied it to them 6 hours ago but have not heard another response from them yet.  So I started doing some more research.

After disabling the wireless on my phone (so that my phone would not be going to the Internet over the same connection as my home PC), I went to my web site and it was working from my phone.  I then went to www.pingwebsite.com and pinged my server web IP (192.252.79.4) and only 4 of the 10 hosts were able to get a response.

I emails to ‘admin@dnstinations.com’ and ‘dnsadmin@us.ibm.com’ because they were the apparent owners of the last node the tracert reached successfully (po1.fcr03.sr03.dal05.networklayer.com [173.192.118.143] ).  It is a Saturday, and I have no response from them yet.

I then considered that my IP address had been blacklisted.  I went to http://whatismyipaddress.com/blacklist-check and entered my IP Address for my server 198.252.79.4 and it showed that my site was blacklisted by two spamhaus.org servers, but not by any of the other 60 servers on the list.  One of the links from this site took me directly to the reason for the block by spamhaus.org at http://www.spamhaus.org/sbl/query/SBL213271. This document told me that a site named primus.com.mk was being blocked as a spammer.  The IP address for that site was the same as my site IP address (www.KraftSoftware.com).  So apparently my site, and all of my sites hosted at arvixe.com, have the misfortune of being on the same server as a spammer.

At this time I think there is nothing I can do except to ask Arvixe.com to move my sites to a different server and IP Address, or for me to move my sites to a different web hosting provider.  And of course I asked Arvixe.com to shut down primus.com.mk and get my IP address off of the blacklist.

At the moment, I am just waiting for their response.

UPDATE AND RESOLUTION:

So I was wrong about the blacklist being the cause of my site not working.  The blacklist just blocks emails, not web sites.  The problem was that my home security system was sending so many pictures to store on my site that it triggered a DDOS response and was blocked.  I have changed my security camera to send fewer pictures and will hope it doesn’t happen again.

Posted in I.T., Online Resources, Web Sites | Leave a Comment »

My Least Favorite New Feature in SQL Server 2014 – No CTRL+E

Posted by robkraft on April 4, 2014

Since as long as I can remember, perhaps back to SQL Server 6.5, I’ve been using CTRL+E to “execute” queries inside SQL Server Management Studio.  I knew that Microsoft warned they were going to eliminate that keystroke, and they finally have in SQL Server 2014.  Now the only keystroke for running queries appears to be F5.  I consider this a productivity setback because to hit F5, I have to lift my palm off of its resting position by the keyboard, then relocate my fingers back on the keyboard correctly to continue typing.  I did not need to do this when using CTRL+E.

Is it possible to complain enough to get a response from Microsoft?  I’m not asking for CTRL+E to come back, but I would like a key combination that does not require me to take my hands of the keyboard to use it.  I like running queries!

Posted in SQL Server | 1 Comment »

Error ORA-1153 using Oracle.ManagedDataAccess.DLL to connect

Posted by robkraft on March 17, 2014

We switched from using Oracle.DataAccess.DLL to Oracle.ManagedDataAccess.DLL in our .Net App.  The code change took minutes, but all the connection string  changes took me a few hours to resolve.  The last error I kept receiving when I tried to connect to Oracle was ORA-1153.  Specifically I had the following values in the exception:

  • HResult: -2147467259
  • Message: Oracle error ORA-1153 encountered
  • Source : Oracle Data Provider for .NET, Managed Driver

This error occurred when the code tried to open the connection

  • _cnOra.Open();

The error occurred because I was missing the CONNECT_DATA value from the descriptor in my datasource of my application .config file.  I had this value:

<dataSource alias=”dev” descriptor=”(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=myServerName)(PORT=1521)) )”/>

when I should have had this value:

<dataSource alias=”dev” descriptor=”(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=myServerName)(PORT=1521)) (CONNECT_DATA = (SERVICE_NAME = dev)))”/>

 

Posted in Coding | Leave a Comment »

Federal Unemployment Tax (FUTA) Credit Reduction for Missouri in 2014 is 1.2%

Posted by robkraft on January 18, 2014

In 2014 the FUTA Credit Reduction in Missouri is increasing from .09 to .12.

Q. What does this mean for Missouri employers?

It means that you will pay a little bit more in FUTA (Federal Unemployment Taxes) to the federal government this year.

Q. What is going on and why did it increase?

Every year states borrow money from the federal government to pay unemployment to unemployment recipients.  If a state fails to repay all the money they borrow, then the state is subjected to a “credit reduction” the result of which is that employers in the state pay more unemployment tax to the federal government.

Q. How is an employer’s unemployment tax to the federal government calculated?

The federal unemployment tax rate is 6.0% for 2014, as it was in 2013.  Employers pay the tax on the first $7,000 of salary for each employee each calendar year.  This would come to $420 per employee each year.

However, since employers also pay an unemployment tax to the state, the federal government allows employers to deduct 5.4% from the 6.0%.  This 5.4% is a “credit”.  Thus the amount paid in unemployment tax to the federal government becomes $42 per employee each year.

However, employers may only deduct 5.4% when their state has paid all of its borrowed money back to the federal government.  When states have not repaid all the borrowed money, they are subjected to a reduction of this 5.4% credit and this is called the “credit reduction”.

Q. So how much will Missouri employers pay in federal unemployment taxes in 2014?

In Missouri, for 2014, the credit reduction is 1.2%.  So the 5.4% credit is reduced by 1.2% becoming a 4.2% credit.  Subtracting the 4.2% credit from the 6.0% federal unemployment tax rate gives us a result of 1.8% for the tax rate we pay to federal unemployment.  So in Missouri for 2014, the unemployment tax we pay to the federal government on the first $7,000 of salary is ($7,000 * 1.8% =) $126.00.

 Q. How does the federal government determine the amount of the credit reduction?

The first year that a state fails to repay the federal government the credit rate is .03%.  The rate increases by .03% every year until the state has fully repaid the federal government.  Since this is the 4th year that Missouri has been unable to repay all of the loans the rate is up to 1.2%.  About half of the states have been unable to repay their loans since the recession began (http://en.wikipedia.org/wiki/FUTA_credit_reduction).

IRS Documentation of FUTA taxes: http://www.irs.gov/pub/irs-pdf/i940.pdf

Posted in Taxes and Fees | Leave a Comment »

How to Fix 2013 Internet Explorer Search Redirect to DNSSearch.rr.com

Posted by robkraft on January 13, 2014

For the last month I’ve been tolerating the redirect that Kansas City Time Warner slipped into my “Search with Bing” searches in Internet Explorer, but I found the fix is simple.

Go to http://dnssearch.rr.com/prefs.php and select the disable option and click “Save Setting”.

I believe this is just another dirty trick Time Warner realized that could sneak into innocent user settings and that most users won’t be able to figure out how to get rid of their search engine.

So, if you find that your search engine recently started redirecting to DNSSearch.rr.com, try the fix above to resolve it and get back to a legitimate search engine.

Posted in Web Sites | Leave a Comment »

How To Power On A Dead Nexus 7 Android Tablet That Won’t Boot At All

Posted by robkraft on January 1, 2014

I don’t use my tablet often, so I sometimes find that my Nexus 7 won’t boot when I power it on.  Not only does it fail to boot, it does not show any activity at all on the screen and I first thought the device was broken.  However, after searching the Internet I learned about similar reports from others and suggestions for getting the device working again.  I am writing this post so that I can find my own answer the next time I need to do this and hopefully provide the extremely precise instructions to help others.

Here is what I have to do when my Nexus 7 does not boot:

  1. Plug in the power to an electrical outlet.
  2. Hold down both the Volume Up and Volume Down buttons.
  3. While continuing to hold down both volume buttons, hold down the Power button for a few seconds.

At this point, a battery charging icon shows up on the screen and you can let go of all of the buttons.

From then on, you can occasionally press the power on button to see the battery charging icon.  If you look closely and wait long enough, you will notice that the battery charging icon appears to be more fully charged over time when it starts up.

Give it a few hours to charge, and then you should be able to unplug it from the power outlet and power it on and use it again.

Good luck!

On July 24th, 2014 this did not work for me, but when I tried this guy’s recommendation it did: http://www.droid-life.com/2012/12/27/fix-nexus-7-refusing-to-charge-try-this-trick/

Posted in Home Tech, I.T. | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 102 other followers