Sunday, August 31, 2014

List vs. Dictionary

List is great when you do not have unique key for each item and the order they are added is important. If you need to be able to get the 3rd item of a list and return it, then its very useful. Its good for loops and iterations. A List will dynamically resize (no need to manage size manually). Lists are a Generic type and can hold anything. From the example above, think of a List as a bunch of different colored markers but that all have the same color outside. You have to grab the "5th" one, pick it up, remove the cap, and see what it is. But! It is in order, and the 5th marker will always be the 5th marker no matter what. Now get me a BLUE marker. Well.. you can iterate over this list and say you want to loop until you find blue. But then you have to pick up every marker and ask "Is it blue?".. and that is not the best design. Or the most logical.

Dictionary is a list with a guaranteed unique key. Both adding and getting are quicker when using a list. However, there is no order of the items.. so cannot iterate over the Dictionary. Like most other pieces of data, the same key is not allowed to be used twice. Now think of this disordered mess as a bunch of messy markers scattered into a pile (example above). They are not in order. But they do have a key.. they "key" here is the outside of the marker. It is labeled with certain colors on the outside so you know what it is.. and you do not have to uncap every one and check them to know. I want you to get a BLUE marker for me. You look and you can easily see from the "key" (outside of the marker color) which one is blue. Try and get me the 5th marker.. well-- you can't, there is no order.


You can see how list and dictionary both have their uses! It depends on the situation, as always :)

Friday, August 22, 2014

Brief Overview of JSON, jQuery, and Ajax

JSON (JavaScript Object Notation) is a lightweight, alternative format to store data (besides XML, CSV, etc..). Lightweight is the key here. It is very quick and simple on the machine side to parse and generate, and it is very easy for users to read and write. Usually, JSON is considered beneficial over XML because of its speed and ability to hold onto the design aspect of an XML relatively well. Here is an example of an XML file and its corresponding JSON syntax (source Wikipedia). XML file below:


  John
  Smith
  25
  
21 2nd Street New York NY 10021
212 555-1234 646 555-4567 male

The JSON equivalent of the XML file is below:

{
    "firstName": 'John',
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1239"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ],
    "gender":{
         "type":"male"
    }
}

jQuery simplifies JavaScript and is another lightweight option to do the same tasks with less writing. It makes using JavaScript easier on a website for animation, events, navigation, and it opens up the doors for adding a layer of AJAX. jQuery takes some of the most used functions in JavaScript and puts them into a method that can be as short as a line! A couple of specific examples that jQuery significantly simplifies are AJAX and DOM manipulation.

The core syntax for jQuery is: $(selector).action()

$ sign defines/accesses jQuery, (selector) will "query" HTML elements, and the .action() performs something on the element.

The jQuery library is inclusive of:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

AJAX is a tool used by jQuery for asynchronous server requests. The "$.ajax" directive means that jQuery ($.) is being used to execute an Ajax request. One of the biggest benefits and claims of AJAX is that is is the ability to exchanging data with a server, and update parts of a web page without a reload-- hence a massive plus for speed and optimization of websites. Asynchronous processing of web pages means that once the page has been initially loaded, AJAX can interact with the server and not change the current page being used in the browser. Think about good searches coming up with their best guess on what you are going to want to search in a drop down.. or eBay loading up new auctions as you scroll down. It would take a very long time to load every eBay auction at once and the user would dislike the page and probably be less likely to use it. However, since it loads quick AND has a lot of data to offer users are happy to use it and it manages to be quick, efficient, and continuously load data as needed or prompted by scrolling for more!

Ajax interacts with the server by an XMLHttpRequest object. The results can retrieve an XML, but more commonly in practice JSON is used for the data to enhance the speed and ability to process by JavaScript.

A list of jQuery AJAX methods can be found HERE.

Monday, August 18, 2014

Dependency Injection

As part of the movement for object oriented design, flexibility for change, and updates to more efficient design.. the dependency inversion principle helps by decoupling software modules. Specifically, high level modules are no longer dependent on the low level module implementations. The net result is a more re-useable high level idea that has easily interchangeable counterparts and details on the low level scale (good for flexibility/change = good for business!). Other examples of patterns besides Dependency Injection that help improve design (to reduce dependency and make separate changeable working parts) include: Plugin and Service Locator.

The following states the theory premises: [See reference 1]
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

If you do not use the dependency inversion principle, then the high level would conventionally depend on the low level modules. Therefore, if you change the small details of a low level module.. then the big picture becomes something different. And therefore it is more difficult to update and make the system more efficient piece by piece if sections bleed into one another and affect each other directly.

In order to use dependency injection, you need to do a few specific elements.
1. Implementation of service object.
2. Client object (whom depends on the service).
3. Interface (that client uses to access service).
4. Injector object (actually injects service to client). Can be called assembler, provider, container, factory, or spring also.

A few cons of this is that it may require more lines of code to accomplish this task, however this seems to be worthwhile in order to prevent the time in writing a few thousand more lines in the future when things really need to be changed. Encapsulation is reduced because users must now know how the system works and a few more details than otherwise without it. Behavior and construction are separated now which means that there may be many additional files added to a solution and more files must be referred to in order to make the whole system work together properly. I believe these are minor however, and if done neatly and conventionally will be worthwhile design investment in the long run.

There are 3 main types of injections:
1. Constructor: dependencies via class constructor.
2. Setter: client exposes setter method to injector --> injector uses setter to inject dependency.
3. Interface: dependency gives injector method --> inject the dependency --> client (obviously, the interface used must be implementer to expose setter method to accept the dependency).

References:
1. Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. Head First Design Patterns (paperback) 1. O'REILLY. ISBN 978-0-596-00712-6. Retrieved 2012-06-21.

Monday, August 11, 2014

Untangling API vs. Library vs. Framework

A framework will help you run your code and provides an environment for programmers to build inside. Frameworks determine the order things occur inside of the program. To contrast, a library is used by the code and says when/how to use code. An application programming interface (API) is a type of interface that helps specify the way components of a program work with each other. APIs are source code based. The API is part of libraries and frameworks. It defines many functions that are called upon.

In procedural languages (lists of step by step codes in C, Go, Fortran, Pascal, and BASIC), an API can specify functions that complete a certain task or interact with other components of the program. The functions will be used and say how to carry out their action in a library.

In object oriented languages (C++, C#, Java, etc..) API writes out how objects work together. It tends to take form as a set of classes and list of methods (blueprint of what to do), and it is functional when classes are implemented based on these 'requirements' in the API.

Build an API general with the future in mind so that parts are easily interchangeable, useful, and workable in the long term. Try to think hard and get it right the first time. It is easy to add functions, classes/methods, etc.. but you cannot take them out so add what is needed initially only. Extend it as needed and build on a good foundation. Keep names logical and self-explanatory. Try and keep a good system and use conventions to make it easier to work with others on the project.

Great API tips on building found: HERE.

Friday, August 8, 2014

WPF: Label vs. Textblock

I wanted to concatenate all the differences into a table form:

Label Textblock
System.Windows.Controls namespace, and is a control System.Windows.Controls namespace, but is not a control
derives from ContentControl derives directly from FrameworkElement
Input can be anything (strings, integers, dates, shapes/images, etc.) Input is only string
support multi-line text output via TextWrapping property support single line text output only
Option for: Custom control template (Template property) and DataTemplate to content (ContentTemplate property). Also, label text can have access keys (focus handling) and appears grayed out when not in use. Lighter and quicker way to display text (because only Strings).

Thursday, August 7, 2014

JavaScript: Arrays, Arrays with Loops, Continue, and Break

Creating an array: A very simple version of an array will start with var for variable and the name of you array (here it is: , but you can name it anything you like!). The first one in brackets will automatically be 0, as many programs are "zero-based" -- meaning start counting at 0, instead of 1. Let's say you have an Id of "example" and already declared a script. Then 1 will be cookies, 2 is salad.. And so on if you wanted more inside of your array. The code below would print: "Mint Chocolate Ice Cream" and "Cookies" only. Note how we have to call each one individually, but we don't have to call them all.
var food = ["Mint Chocolate Ice Cream", "Cookies", "Salad"];
document.getElementById("example").innerHTML = food[0];
document.getElementById("example").innerHTML = food[1];

Using an array in a loop: Now we can loop over all of the things in an array (or only things less/greater than etc.. If you wanted).

var myFoodArray = ["Chocolate", "Ice Cream", "Cookies"];
for (var i = 0; i < 100; i++)
{
    console.log("I like to eat: " + myFoodArray[i] + ".");
}

From the above your output would be:
I like to eat Chocolate.
I like to eat Ice Cream.
I like to eat Cookies.

Continue statement: If the loop keeps running, you are good and the number is even. If you cannot fulfill the "if" statement, it will break and skip the whole bracketed "if" part and go to the console.log portion. Since it would only break if you have an odd number, this is a good way and time to print as such!

for (var i = 0; i < 100; i++)
{
    // check that the number is even
    if (i % 2 == 0)
    {
         continue;
    }
    // if we got here, then i is odd.
    console.log(i + " is an odd number.");
}
Break statement : When i hits 0 here, it will stop the loop.
var i = 99;
while (true)
{
    console.log(i + "red balloons");
    i -= 1;
    if (i == 0)
    {
        break;
    }
}