Friday, March 6, 2020

Deep Copy vs Shallow Copy

The past couple of days I have been working on creating a logging service to capture any changes that have been made to our pages. We had a logging service made for another part of our application, but this new portion wouldn't be able to use the old logger. First, the old section that was logging was coded pretty specific to that section of the app. There are a lot of reusable parts, like checking the two objects to see if there are differences, but pieces like adding the differences into a database were very specific. So, I started down adding a method to the AuditLogService that will allow any type of object to go into service and have it logged in the database.

I ran into a problem though. The specific page I was working on was designed to save over the old value instead of creating a new line. I'm not sure why it was programmed this way, but it is what I have to work with. I could redo this part of the program to add a new record in the database and add a flag to show the old record was no longer the correct record, but there was going to be a lot of places to change, and I had all the information I needed in my controller. The old data in the row and all the new data was ready for me to use. All I needed to do was pull what the data currently was on the server, remember data came back, transform and save the new data, and finally run my new service that would find and log all the differences. Should be easy!

The problems all started when my history object kept changing when I would update my new object. What was going on? As I investigated, I determined that the object I was trying to create to remember the history was just a copy of the original object (a shallow copy I would later learn). I tried two ways to copy into the history. First I did a straight copy:

Response originalResponse = responseControllers.GetResponse();
Response historicalResponse = originalResponse;

Exact same copy. And I should have know that. The second method I tried was to go back to the controller and get the object again.

Response originalResponse = responseControllers.GetResponse();
Response historicalResponse = responseControllers.GetResponse();

I did some investigating and I learned that indeed what I was doing was just a direct copy. I should have known, the simple answer is most likely the answer. So, how do you fix it? I had spent a while on this task, so I asked for a little help from my team lead. He mentioned I probably needed to serialize and then deserialize the object again in order to create a deep copy. Well, I created an extension:

    public static class ObjectExtension

    {

        public static T CreateDeepCopy(this T objectToCopy)

        {

            try

            {

                string jsonSerailizedObject = JsonConvert.SerializeObject(objectToCopy);



                return JsonConvert.DeserializeObject(jsonSerailizedObject);

            }

            catch (Exception e)

            {

                Console.WriteLine(e);

                throw;

            }

        }

    }

Now when I change my originalResponse (typing this I realized that original and historical could have been called something different, naming, that hardest part) the historicalReponse no longer changes! Perfect! I am now getting a deep copy, which is a copy of the object and all the references. And I made an extension that we could use again the application, I'm sure we will use it again, right?

I have a console program that I was experimenting with to try and get it to work here


"A true friend never gets in your way unless you happen to be going down." - Arnold H. Glasow

Thursday, December 27, 2018

Observer Pattern

I have been sitting on this blog for a while. I finished the chapter a while ago, but not sure exactly why I wasn't getting to writing the blog post. At one time I had a few blogs written so I could just post, then I got sick or something and fell behind. I am obviously not as prepared as I was at that time. I am not going to make any promises because, when it comes to blogging, I don't usually keep the promise to write once time a week. At this point I am once a month. Let's put it out there. I will write one blog a month.

Let's start (and finish) December with Observer Pattern. The thought behind the Observer Pattern is pretty simple, objects subscribe to events and when that event happens the object will get notified. It is very similar to a newspaper model (except we hope the Observer Pattern doesn't get the same fate of newspapers). The object is an observer, or subscriber, to the subject, or publisher. Each morning a paper gets published and sent to everyone that subscribes to it. One can unsubscribe from the newspaper at anytime in order to stop receiving the papers, or new people can subscribe at any time.

Each object should implement an interface subject and all observers should implement an observer interface. The concrete observer will register with a concrete subject to receive updates.The concrete subject will contain methods to add or remove subscribers.

When the observer is subscribed to the subject anytime a change in the subject happens the observer will be notified. If the observer gets tired of receiving the notifications it can unsubscribe. This pattern allows for loose coupling:

  • The only thing the subject knows about an observer is that it implements a certain interface
  • We can add new observers at any time
  • We never need to modify the subject to add new types of observers
  • We can reuse subjects or observers independently of each other
  • Changes to either the subject or an observer will not affect the other

Loosely coupling allows for a pretty flexible design and will minimize the number of changes that we have to make if any changes need to make changes.

Different frameworks already have ways to do the Observer Pattern, in Java there is a built-in observable class in the java.util package. And C# you can use delegates and events. It will take a little research to find the correct way to implement the Observer Pattern in whatever you are using, or you can implement your own (probably not the most effective way to do it) as I did in the link below:

Link to my example

Alright, next up? Good question, but I want to get Google Analytics or some sort of analytics on jorgfam.com. We will see what January brings.


"Maybe Christmas, the Grinch thought, doesn't come from a store." - Dr. Seuss

Wednesday, April 18, 2018

Strategy Pattern

I have been reading about design patterns. I realize that I often use them, but could not tell you what the are called or why the are good/bad. I decided to pick up a book, Head First Design Patterns, and look for other resources online as I read. I found a nice Pluralsight video that has many design patters included in the video called Design Patterns Library.

The first pattern in the book is the Strategy Pattern. This allows you to use a family of algorithms and the one that will be used is decided at run time. Each algorithm is encapsulated into the family and makes them interchangeable. This makes it beneficial when you have multiple classes that need an algorithm of the same type, such a speaking behavior, but not all classes implement the behavior in the same way.

Most animals have a form of speaking, dogs bark, cats meow, etc. So, if you take a class of Animal which contains a method for speaking then each class that extends animal will be able to speak. Now you have an issue, you will have to override the speak method for each class that inherits from Animal. That means a lot of extra code, and if the speak behavior ever needs to change you may miss changing one.

This is where the Strategy Pattern can come in handy. Now you have an interface for speaking Animal strategy, say ISpeaking. Then you have classes that extends the interface for different types of animal: dog, cat, etc. These classes will look something like:

public interface IAnimalType
{
   String Speak();
// other things animals need/do
}

public class Dog: IAnimalType
{
public String Speak() 
{
return "I am a dog, here me bark...woof!";
}
}

public class Cat: IAnimalType
{
public String Speak() 
{
  return "I am a cat, here me meow...if you can find me!";
}
}

We can then pull the strategies in an Animal context with code similar to:

public class Animal
{
IAnimalType iAnimalType;
// Other interfaces needed to make a true animal

public Animal(IAnimalType iAnimalType)
{
this.iAnimalType= iAnimalType;
// Your other animal interfaces go here
}

public void Speak()
{
Console.WriteLine(this.iAnimalType.Speak();
}
}

We can go to a employee now and return different request to the HRContext by selecting a strategy.

class Program
{
static void Main(string[] args)
{
Animal dog = new Animal(new DogType());
Animal cat = new Animal(new CatType());

Console.WriteLine("Here is a Dog");
dog.Speak();

Console.WriteLine("Here is a Cat");
cat.Speak();
}
}
If we were to run this program we would get out what each animal says. If we ever need to change what one type of animals speak behavior is, we just change it in one spot and don't need to worry about forgetting one.

Using this pattern also allows us to use an Open/Close principle, which is that the classes are open for extension but closed for modifications. We can add any type of animal and will not need to update our iAnimalType or Animal classes.


"You can't expect to hit the jackpot if you don't put a few nickels in the machine." - Flip Wilson

Wednesday, April 11, 2018

Sorting Objects in arrays

I finished a challenge on Free Code Camp called Inventory Update. The challenge asked you to update the first array (inventory) with either the array 2 (delivery) items if they don't exist in the inventory or update the inventory number if the item already exists in the inventory.

The arrays weren't objects with names, they came across with an integer and text. For example, my first item in array one was [10, "Bowling Ball"]. I probably could have converted each item in the array to an inventory item so then I would have [quantity: 10, name: "Bowling Ball"]. But with the all you can do with arrays I didn't find that necessary (although if this were a program for someone, it would have been beneficial to make the array into a more usable format instead of using array1[i][0].

Adding new items and updating the value of an item already in inventory seemed easy. I created a function to see if the array contained the inventory item and updated the amount. If it didn't contain it, push in the new array item.

function contains(obj) {
for (var i = 0; i < arr1.length; i++) {
if (arr1[i][1] === obj[1]) {
arr1[i][0] += obj[0];
return true;
}
}
arr1.push(obj);
return false;
}

Now came the more tricky part. The challenge asked you to alphabetize the items in the inventory. You know, make it easy to find an item in the list. I tried arr1.sort() but this seemed to just sort off the first item in the object of the array which was the quantity in the inventory. Great if I know the quantity of whatever I was looking up, but doesn't really make sense.

While reading, I found that you can create a function to sort your items in the array. This allows you to write a function to alphabetize based on the second member of my object, or the name of my inventory item.

I looked further and found a better way that didn't require me to write a function. Using String.prototype.localeCompare(). This compares the strings you have and returns a number that indicates whether the reference string comes before, after, or is the same as the other string provided. It then will sort the items for you.

This will allow for some options as well, such as case sensitivity, numeric, ignoring punctuation and more. It made the sorting pretty easy and able to use one line of code:

arr1.sort((a, b) => a[1].localeCompare(b[1]));

(if I had made each item in the array into an inventory object it would have been a.name and b.name instead of a[1] and b[1]).

I could see localeCompare coming in handy later in life.
"I have noticed that nothing I never said ever did me any harm." - Calvin Coolidge

Wednesday, April 4, 2018

Z-Index Values

Developing for different browsers can be difficult. Each browser can have it's own set of rules and coding for each browser can sure be difficult. For example when you use Flexbox you have to remember to add CSS display lines to make sure each browser will display correctly.

Recently, I was working on an informational window that will track with the question mark button. I make the window be positioned where it needed to be we ended up using NGX-Popper. Works great! You can resize the browser and the pop-up moves exactly where it needs to follow the button you pushed.

I checked how it looked in Chrome and everything was working great after adding a line in the CSS file:

.inside-popper {
z-index: 999;
}

I selected 999 just because it is a high number with the hope that a higher z-index would not be selected for another element. Looks great...until I pull it up in Internet Explorer.

When I opened this up in internet explorer, the pop-up was not the item at the front. Some elements of the pop-up were showing correctly but it seemed the background was clear and was allowing the elements behind to come to the front.

Here is a shot IE left and Chrome on the right:

I had the z-index in the CSS file but it wasn't recognizing it in IE, or so it appeared. After doing some research I found that it looks like IE generates a new stacking context for elements that are positioned. This means the z-index will have a value of 0. Z-index won't work as expected.

The work around I found was to wrap the popup in another div that had a class with a higher z-index then my pop-up:

.popper-wrap {
position: relative;
z-index: 1000;
}

.inside-popper {
z-index: 999;
}

Now IE looks the same as Chrome. Just another one of those things to watch out for when looking at the different browsers.


Wednesday, March 28, 2018

Javascript Variables

In C#, a method required you to declare the number of arguments and each arguments data type.If you declare a method requires an argument your code will not compile unless the argument is given each time the method is called. JavaScript works a little different.

JavaScript does not require you to specify the data types for each argument. It also does not perform any type of check on the arguments when the function is called. You can pass multiple arguments, or no arguments. If you declare an argument and the function receives nothing JavaScript will assume undefined for the missing arguments.

FreeCodeCamp had an algorithm where arguments were sent in different ways. For example, addTogether(2, 3) would return 5, just the sum of the two arguments passed.

 if(args.length == 2){
    if(typeof(args[0]) !== 'number' || typeof(args[1]) !=='number' ){
      return undefined;
      }
    return args[0]+args[1];
   }

But, what if you received something like addTogether(2)(3)? This confused me (and still kind of does), two sets of arguments? How do you deal with that?

I did some reading and found that it is a valid call to a function. Now I needed to figure out how to access that second variable.

It turns out that while looking at the first variable you can create another function that will look at the second variable.

if(args.length == 1){
     firstSet= args[0];
     
    if(typeof firstSet!=='number'){
        return undefined;
      }
   
    else{
       return function(secondSet){
         if(typeof secondSet !=='number'){
           return undefined;
           }
         else
            return firstSet+secondSet;
          };
      }
    }

Good to know, I'm just wondering when I will use this in real life...why would you send two sets of variables instead of just one set or an array?


"Sooner or later, those who win are those who think they can." - Paul Tournier


Wednesday, March 21, 2018

Smallest Common Multiple - using Euclid's method

I spent some time trying to figure out how I was going to solve the smallest common multiple. There are multiple ways to find this number. You can write down all the multiples and just look, you can use a grid/ladder method, prime factorization, or Euclid's method (the method I selected). If you want to see each method you can go here and see the how to accomplish through the different methods.

I decided to try and use Euclid's method. Math is used to find the greatest common divisor which is then used to find the least common multiple. Euclid's method requires you to perform the same calculation multiple times until you have a remainder of zero. You could do a while statement that looks at the remainder and stops when the remainder is zero. I also looked at a different way to do this, using recursion.

I learned about recursion a while back and figured I would give it a try here. I had a definite stopping point and needed to run the same calculations over until I got a certain number. It took me a few tries at getting the recursion to work (knowing what to put where), but I eventually landed on the below code:

function euclid(high, low) {
if(low === 0) {
return high;
} else {
return euclid(low, high%low);
}
}

I call the function and pass it the first number in an array as the high number and the second number as the low number. It then goes into the function to see that low is not at zero so it calls itself with the low number as high and the remainder of high divided by low (you use modulus to return only the remainder as the new low number. Once the modulus returns a zero, return the high number.

Euclid's method then takes the product of the first original two numbers and divides it by the number returned from our Euclid function. This will give you the smallest common multiple for the two original numbers.


"Laziness may appear attractive, but work gives satisfaction." - Anne Frank