Using Factories

Factories are neat, because they allow you to set common properties for objects before you create the object. Plus, all the objects coming out of the factory will have those same settings.

For instance, take the follow factory:


class Item{
    public $price = 0;
}

class ItemFactoryA{

    public $item_price = 15;
    public function get(){
        $item = new Item;
        $item->price = $this->item_price;
    }

}

$iFactory = new ItemFactoryA;
$item = $iFactory->get();

The benefit of this is that every item coming out of FactoryA will have the same price. This is useful if you are going to set the price once, but want to remember it for a while.

In a real life scenario, it could look more like this:


class UTC_TimeClock{
    public function get_time(){
        return time();
    }
}
class TimeZoneClock{
    public function __construct( $utc_clock, $timezone_offset ){
        $this->utc_clock = $utc_clock;
        $this->timezone_offset = $timezone_offset;
    }
    public function get_time(){
        return $this->utc_clock->get_time() + $timezone_offset;
    }
}
class TimeZoneClockFactory(){
    private $utc_clock;
    public function __construct(){
        $this->utc_clock = new UTC_TimeClock;
    }
    public function build( $timezone_offset ){
        return new TimeZoneClock( $this->utc_clock, $timezone_offset );
    }
}

This factory would make sure that all of the Time Zone clocks are running off of the same UTC time clock, but that they all could have different offsets based on what time zone they are representing.

There are many more examples of how this could be useful.

Posted in Programming | Leave a comment

Building a Language: Math Expressions

If someone tells you to list every math operation you know, you might tell them: addition, subtraction, multiplication and division. And you would be right. Each of these are math operations. But to a programming language, these are the least used math operators in existence.

When a programming language goes to evaluate an expression, it must deal with a variety of math operators. Each of these math operators has a common behavior: it takes 2 values (on the left and on the right) and spits out a single value (the result of the operation).

Basic arithmetic operators all fit this description. And if you were to write a programming language, you could very easily model those operators after this behavior. However, it would be a big waste to forget 3 other operators that have this very same behavior: equals, and, and or.

If you think about the ‘==’ operator (or equality operator), it takes the value on the left and compares it to the one on the right. If both are equal, it outputs a single value: boolean true. The same can be said for ‘and’ and ‘or’. Both look at the values on the left and right of them and output true or false, based on the keyword in use.

If you look at SomeLanguage, you’ll see that all of these math operations are implemented using a single MathOperation behavior that allows expressions to be evaluated very easily.

Posted in Other | Leave a comment

The 3 Levels of Thinking

Programmers all over the world start new projects everyday. You can see them start on social sites like Github, or in the shadows of the internet hosted on random servers. Each one of these projects has a purpose and function.

In the recent months, I have come to believe that everything that is done in a project can be talked about in 3 levels of thinking. Furthermore, I believe that these 3 levels of thinking are entirely separate from each other and the way we execute these different types of thinking are very distinct.

The first type of thinking I’d like to propose is Business thinking. This is the type of thinking you would normally credit towards an entrepreneur or inventor. When you are doing business thinking, you are trying to come up with abstract ideas that solve real-world problems. For instance, you might come up with the idea of a keyless lock for your front door, or a Twitter feed that tells you when to water your plant. When you are trying to come up with ideas for a new business venture, you tend to look for problems that need solving.

The funny part about this type of thinking is that it is usually open ended. There seems to be an endless number of ideas that you could implement, as there are. Some people are really bad at this type of thinking because they freeze at the realization of how vast it is and simply can’t hone in on an idea.

The thing about Business thinking is that it can be done by pretty much anyone. Business thinking revolves around how the consumer interacts with a product/service, and doesn’t require a ton of technical knowledge. Because we are all consumers, we can generally grasp the concept of how we want to interact with something. (Not that we are particularly good at it. Many people will say that consumers don’t really know what they want, but I digress.)

The next type of thinking is Functional. Functional thinking start to look at the very abstract parts of the project. It might start to think about how a car has an engine which generates power, and that transfers the power to the drive train and finally to the tires. It might talk about brakes stopping the tires from spinning, a steering wheel turning the wheels, etc. In essence, functional thinking moves away from the base idea of a project and into the actual components that make it work.

This type of thinking is harder than business thinking. It requires more knowledge about the domain, and a general insight to what different mechanisms do. It is much more close ended than business thinking because you are no longer in a giant sea of options. Unlike ideas, which are seemingly infinite, components that preform certain tasks are limited in number. You might have a dozen mechanisms that can stop a wheel from turning, which is a far cry from the number of ideas swirling around in your brain when asked for an idea for a transportation device.

The last part of thinking is Implementation. This is where you separate your entrepreneurs and project managers from your mechanics and programmers. Implementation requires intimate knowledge of how the different parts work, and how to use them properly. A mechanic knows the right bolt, belt, and wrench to use to get a engine up and running. A programmer knows how different objects and protocols and severs communicate with each other to preform the correct actions. Implementation is a highly skilled art.

If you were waiting for the point of all of this paper, you can stop waiting now. I’d like to argue that Implementation is a very closed-mind type of thinking, and that it is this way because of human ability to understand complexity.

It is fairly easy to understand all the details of a program from a Business point of view. You can probably describe a project in a few sentences, or if you really bad, a few paragraphs. Like I said, Business thinking is fairly noncomplex and abstract. Functional thinking is only slightly worse. You could probably explain a developed program in a few pages.

But Implementation is the hard one. Implementation is all the little nuts and bolts that put something together. It is the classes, the interfaces, the constants, variables, functions, all of those things that put together end up making something that works, that is so incredibly complex and low-level that the only way to describe it is by simply looking at it.

But even just looking at the source code can overwhelm someone. It has so many different parts to it, so many different variables and syntaxes and complexities that even most programmers don’t like to think about it.

It is because of these complexities that implementation programming is very closed-minded. Here’s why:

If you’ve looked over how these 3 layers have progressed, you’ll notice when more complexities were added, the number of options were decreased. At the Business level, you have very few complexities so “the sky is the limit”! Any idea could work! You could make rocket! or an airplane! Once you got down into the Functional level, you had more complexities, more things that had to work together, more components you had to think about, and thus you have fewer options. Now you choose between a few dozen wheel sizes and types. But once you get down into the Implementation level, the amount of things affected by any piece of code is so vast that your options are limited to just a few options. For instance, a bolt vs a nail vs a screw. A while vs a for.

And actually, this limitation of ideas isn’t completely factual. It is a human-made reaction to complexity, and you can see it in every profession out there. The more low-level the task, the more likely that someone will have found a solution that works in 98% of cases, and no one will really want to attempt to discover a new methodology. Because the old solution works, they use it. Not only does that person not have to think up a new idea and deal with all the relationships and complexities that a fundamental piece of equipment will have, but they already found a solution, so why bother?

It is because of this human-created reaction, this development of low-level solutions to everyday problems, that low-level thinking is very close-minded. The Implementation view of the world, the extremely low-level view, is not as much of a ‘idea’ creation methodology of thinking, but a methodology of think that takes solutions already created and tries to piece them together into a program that is functional.

Posted in Other | Leave a comment

Modularity: What is it?

You may have heard of the term ‘Modularity’ before. In fact, I have several articles written about how to use it right on this blog. But, before you can use it you need to know what it is.

As Wikipedia defines it, Modularity is the concept of taking a complex system, and dividing it up into components that can later be reformed. For instance, if you were making a blogging software you might separate it into, among other things, a RSS Feed Generator and Commenting System.

Designing a single component to be modular means that the component is able to fit together with the other parts of the system, or even in other similar systems. For instance, if you have multiple projects that require RSS output, you can use the same RSS feed generator in all of them.

How do I achieve modular code?

The best way to create modular code is to create each component separately. When you go to build a part, make sure it functions the way you want it to without the rest of your code. And while you are doing this, make sure that it raises errors correctly and acts exactly how you expect it act. Once it is all running, you now have a modular component for your project. After that, you will want to continue on with the other components in your project. Once you’ve created all the components, and they all work separately, you can begin to bring them together so that they work as a single program.

This sounds ‘too’ easy.
There are problems with Modular design. The biggest problem with modular design coordination and planning. If you haven’t done proper planning, different parts can be designed in ways that just don’t fit together correctly. This is where things like design constraints, looking at the big picture, and proper class planning are really helpful.

Posted in Programming | Leave a comment

Your Methods Are Showing: Why Public Methods Need Special Attention

So you are about to create a new class. You go to define the first method. You mull over whether to make it a private or public method, choose public, and go on with your day. This isn’t exactly the best way to create a class, especially one that you might want to use for other projects or even distribute to other developers.

The fact is, the methods that you declare public in your class are special. They are the methods that code outside of your class can interact with. This is both good and bad. It is good because without these methods, outside code can’t tell your class to preform its function or obtain the product of its work. It is bad because when outside code interacts with these methods, pretty much anything can be passed in as an argument and any method can be called at any time in any order.

Because of this, you need to have a basic checklist of defenses set up to make sure the public methods of your class can withstand whatever some other chunk of code throws at it.

1) Set Data Expectations and Check Them
You should have expectations for any data coming in from outside classes. Checking that the data they give you is a certain datatype (string, integer, object, etc) should happen as soon as possible. If the data given doesn’t meet expectations, you need to present them with an error.

By checking the data as soon as it comes into the class, it is easier to debug what is going wrong later on. It also means that you don’t have to follow your class’s logic to figure out if a piece of data is actually checked.

2) Make sure your object is in the correct state
For some objects, you might be expecting certain conditions to be met before a specific method is called. For instance, a disconnect method would expect connect to already be called. You need to check the state of your object to make sure you are in a state where you can preform your task. For instance, you would check that there is a connection already opened before trying to disconnect it. If there isn’t a connection you could create an error, or you could decide that the function has technically done its job (ensure that there isn’t a connection open).

3) Standardize your return values
Because your class might have a lot of public methods that return data (think a class representing a database table), you need to make it easy for others to figure out what data you are returning. Because of this, similar methods should return similar data. If your getPosts method returns an array, getComments should also return an array. These arrays should also use similar field names with a similar naming convention (camelCase, etc).

Tip: The reason all of these things should be standardized is for consistency. If you are consistent with return values, method names, etc, other developers know what to expect which makes your class more useful.

Tip: When you create a method that returns an array, it should always return an array. Even in dynamically typed languages like PHP, an error should not mean you return false but instead return an empty array. If you’d like, you can raise an exception, but never return a boolean when developers expect an array.

Posted in Programming | Tagged , , | Leave a comment

Modularity: You Can’t Ignore the Big Picture

Building modular components can be a very efficient method of construction. Each component is its own mini-project, and all the parts come together to form something greater than the sum of its parts. Instead of building a blog, you build a post writing/editing system, a commenting system, an RSS generator, and afterwards you piece them all together.

As ideal as all of this sounds, there is a trap that you can fall into when you do things modularly. And it has to do with requirements.

At the end of the day, your modular component is a part of a bigger picture. When you’ve finished building your component, the rest of the project needs to be able to interface with your component to get work done. If you build something that isn’t easily dropped into the bigger project, you will end up wasting a lot of time.

Whenever you design something modular, you need to list out your requirements. This includes everything from the tasks your component needs to preform to the way it needs to interact with the main project. You also need to be aware of the things your component requires to work, and make sure that those are available when it comes time to pull everything together.

Here are a few quick questions you should ask when you go to design a modular component:

1. What actions does the main project need to be done?

While this might sound obvious, it is very important to make a list of the functionality the component is required to provide. This does two things that help everyone’s productivity and sanity. With a written list of functionality, no one needs to try to add a ton of extra functionality “just incase”. Instead, once everything is checked off you can move on to another component.

It also helps everyone’s sanity by making a sort of contract that states exactly what the component needs to do. There isn’t any confusion over what a component should do and not do when there is a list sitting in front of you. And if the main project needs more functionality they can change the contract, but only after making sure everyone creating the component knows about the changes.

2. Where are the connection points between the main project and my component?

Knowing the entry points to your component is crucial. All interactions between the main project and your component should be carefully looked at and tested for possible errors. Making sure that your component can handle all of these interactions properly will make integrating it with the rest of the project less painful.

One of the most important tests is data validation. The data that is passed to your project should be validated and verified to make sure it is in the proper format. It is unendingly annoying to be expecting data in one format, and getting errors because the data you are getting was never put into that format.

3. What are my dependencies?

Whether you have just a few dependencies, or a lot, listing them and making sure that they will be available in the main project is important. If you use a library like jQuery, make sure that when your code gets merged you will still have access to it. Verify that systems like databases and mail servers will work the way you expect them to, and if possible create code to make it easy to adapt your component to them when they do change.

When you’ve completed all 3 of these steps, you should have a very good idea of what it will take to integrate your component with the main project. Now all you have to do is build it. Have fun!

Posted in Programming | Tagged , , , | Leave a comment

Design Constraints

This year we attempted to design our robot modularly. We assigned separate teams to each design parts of the robot (lift, grabber, chasis, minibot) and then brought them all together. Whether or not this is the best way to design a robot is up for debate. However, there are a few parts of modular design that would have helped us in the end.

Working in different teams has advantages and disadvantages. When you work separately,you can be designing the arm at the same time as you design the lift at the same time you design the chasis. This is called doing things in parallel. This is a clear advantage because things get done faster.

On the other hand, the biggest disadvantage of modular design is communication. Because teams are separate, one team might assume that the other teams are building their parts in a certain way. We experience that this year with weight. When everything was put together the resulting robot simply weighed too much. This was probably caused because each team designed their part and nobody told them how much their part had to weigh.

Design Constraints are very helpful in this situation. In essence, a design constraint is a rule that must be followed in order for the design to be considered. For instance, we could have put a constraint that whatever lifting mechanism we used had to weigh under 20 pounds. When we prototyped the forklift, we could have weighed it and made the changes necessary for it to be under 20 pounds.

The beauty of design constraints are when you bring multiple pieces together, they all work. When build season first starts, the leaders would look at the maximum weight (120lb this year) and look at the different parts that need to be built (lift, grabber, chassis, minibot deployment) and estimate about how much each system should weigh. When we go to assemble the robot, because we had those constraints placed on the individual mechanisms, the entire robot should come in under weight.

Note: Having an estimate of what each system weighs is a good idea in general. It helps you make decisions later on if you need to loose weight.

Design constraints can be used for anything from weight to the types of bolts you use to connect to the chasis. If we know that we only have 7 motor controllers, you might want to limit the lifting mechanism to two motors and limit the arm to one.

Finally, just because you put a constraint there doesn’t mean it can’t be changed. If a certain parts needs more weight, and another parts comes in under weight, everyone wins. However, it is important to first set the constraints, and then change them down the road. And when they change, every team should be aware of it so they can adapt to it.

Posted in Planning | Tagged , | 1 Comment

Code: Reuse and Recycle.

Have you ever gotten the feeling that you’re currently writing a piece of code you’ve written before? I have. And when I started having those feelings too often, I knew that something had to be done. If I spend hours a day writing code for a project, finish the project, and turn around and start writing the same code for another project, we’ve ran into a major problem. Instead of creating new code that do new, interesting things, I’m writing code that does the the same, uninteresting things. It is time for a change, for both of us. It is time to write reusable code that can go from project to project with little effort, and can stop us from spending all of our time writing the same stuff.

Step 1: Plan It
The code you are about to build should be able to last untouched for a long time. Therefore, you need to spend some time figuring out all the details and all the different things this code might run into along the way. For an example, I’m going to be building a simple class that allows me to connect to a MySQL server using the built-in PHP commands.

I’m going to start out with a list of things the program has to do:

 1. Connect to a MySQL Server using a Username, Password, and Host field
 2. Select a database
 3. Run a query and return the results
 4. Escape values to prevent query injection
 5. Handle errors using PHP's built-in exceptions

This is a simply list, and should be fairly easy to accomplish. One piece of advice when writing code is that it should be very specific to the task at hand. If you need to be able to turn an RSS feed into a PHP object, don’t let other features creep in like inserting that data into a database. Your code should have a very specific task so it is easier for you to use down the road.

Step 2: Pusedo Code It
Now that you have a plan, you should start turning this into code. However, programming all the minute details into the program isn’t what we want right now. We don’t want to actually commit ourselves to code just yet, instead we want to create a high level design that can easily be manipulated without a lot of extra work.

Pusedo coding is the practice of writing out the programs flow without actually coding anything. Most of the time it include writing the functions a class has and then commenting about what those classes will do. Here is my example:

    class MySQL{
        private $connection = false;

        /*
             Connects to the MySQL Server using the host, username and password.
             Stores the connection created in $connection
        */
        public function __construct($host, $username, $password){
        }

        /*
              Selects a database on the MySQL Server
              Throws an exception if the database does not exist
        */
        public function select_db($database_name){
        }

        /*
              Queries the database and returns the result
         */
        public function query($string){
        }
    }

As you can see, my class outlines what each function will do. Now I am coming closer to a finished product and can see what the class with end up looking like. However, it is very easy for me to add, change, or delete functions without wasting any code that they might have contained.

Side Tip: At this point it would be a very good idea to make sure that your class lines up with your original specifications. If there are certain things in your specifications that never made it into the class, you should add those now.

Step 3: Reduce
Some say that simplicity is key to good design. Generally the less code that you use in your class, the fewer bugs you will create. Look at the flow of the class. How does the class get from the initial function call to the result? Are there ways to reduce the amount of code that it takes to get from Point A to Point B.

This is a great place to look at reusing code inside the actual class. If you have 3 or 4 functions that all do similar things (like sorting an array, or validating data), it might be a good idea to make that step its own function.

Step 4: Code
This is the part everyone knows about. Now that you’ve planned out your class, you are able to write code with more certainty that you won’t need to change it later on. Some of you might ask, what does any of this have to do with reusable code? Well, reusable code is generally code that has been planned out well. If design your classes beforehand and don’t try to hack it together, you’re more likely to design a class that will work in multiple situations.

If you really want some tips on making classes more reusable, here are a few:

  • Reduce dependencies on other classes.
    If your arguments require that the variables passed in are of a certain class type, it means that every time you want to use this class you also have to use those other classes. I’m by no means saying **not** to make your code depend on other classes, but do try to make the number of classes you depend upon a fairly small number. If it is absolutely necessary that you 2 or more dependency classes (making your total number of classes 3 or more), you might want to think about packaging less important classes together to make it easier to transport between projects.

  • Make use of your framework
    If you work in a framework like Java or PHP which already has lots of classes and functions, use them to your advantage. Instead of creating your own Exception classes, use the standard ones given to you by the framework. That way you can assure that anything you do can be ported between projects because they all will most likely be running with those standard classes available.

  • Be courteous of namespaces
    If you create a class called ‘Main’ or ‘System’, chances are that when you go to bring this class into another project, there might already be a class with that name. You should make your class’s names specific and fairly uncommon. Making a XMLParser is better than making a Parser, however making a XML2OBJParser is even better. (Even though the name doesn’t roll off the tounge…)

  • Posted in Programming | Tagged , | 1 Comment

    URL: The Uniform Resource Locator

    The basis of the entire internet might be connected to a single concept: The URL. Every website you go to, every link you click on, and every file you download relies on it. The funny thing is that most people don’t know a lot about how this jumble of slashes and dots works. Well, here’s how:

    What is a URL made up of?
    A URL is made up of several parts that each give specific information about how your web browser (or any other application) should try to connect to a server. A URL is made up the following parts:

    scheme://username:password@domain:port/path/file name?query string#fragement

    git://chacha:test12345@example.com:443/server/test.html?myVariable=hello&myOther=world#instructions

    As you can see, there are a lot of parts to a URL. But what does each individual part mean?

    • Scheme: This is the protocol to use to open this URL. While browsing the web, this is either http or https. However, there are other protocols out there generally used for specific application. Git, a code repository, uses the git scheme to transfer data back and forth.
    • Username/Password: Sometimes you might need to send a username and password to a server to access specific files/resources. On most websites you do this through a login system, but non-website based services might require you to give your credentials in the URL.
    • Domain/IP Address: The domain/IP address that you wish to connect to.
    • Port Number: This is the port number that you wish to connect to on the server. For instance, google.com:5400 will connect to port 5400 on Google’s server. For web browsing, the standard ports are 80 (http) and 443 (https).
    • Path/Filename: This is the path to the specific file on the server you want to access. For instance, example.com/test.html will open test.html.
    • Query String: The query string is a series of variables that can pass information to the server. They use the syntax variableName=value&var2=val2.
    • Fragment: The fragment tells the browser what part of the page you want to access. The fragment doesn’t ever get sent to the server, however it is used to automatically scroll to a specific position on a page.

    In a relatively small space, URLs are able to convey a lot of information to a server about what it wants to access. Some quick tips to keep in mind while using URLs:

    Always Encode URLs
    When you go to output a URL via PHP or another programming language, you should always encode them in a way that won’t mess up the document you are outputting them in.

    For instance, if you are creating a HTML page and your URL has a ‘<' or a '&' in it, HTML is going to thing that those characters are meant to be HTML and not simply text. If you have a URL like:

    http://example.com?text=5+is+<+2

    HTML will see the ‘<' and think everything after it is the opening of an HTML tag. This can be avoided by writing &gt; instead. The same thing happens with the &. & is used to create HTML entities (like &gt;), and because & is used to delimit variables in the query string of a URL, your URL could be misinterpreted.

    When possible, use a full URL
    Many people shortcut writing out full URLs by making code like:

    <a href="my/directory">Link</a>

    If you are on the homepage, this link would go to http://example.com/my/directory. However, what if this is your main navigation that you use on every page. When you get to http://example.com/hello/world and click on this link, you’ll go to http://example.com/hello/world/my/directory. This probably isn’t what you are looking for.

    Instead, always use a full URL when linking to items:

    <a href="http://example.com/my/directory">Link</a>

    If you are making a website accessed from multiple domains, you can get rid of the domain, but always start from the root directory. (That means that the URL will always start with a ‘/’.)

    <a href="/my/directory">Link</a>

    (As I accumulate more tips on using URLs, I’ll updated this page)

    Posted in Programming | Leave a comment

    Cookies: What they are, How they work

    Cookies are a marvelous feature given to browsers to allow websites to track users from page to page. They have been used for both good and evil during the short lifespan of the Internet, and here I am to provide yet another look on exactly what cookies are, how they are evil, and how they are a necessary evil.

    What are Cookies?
    Cookies are pieces of text. When a server tells a browser that it wants to store a cookie, it gives the browser a string of text and whenever the browser returns to that website, it sends that text back to the server. Along with the contents of a cookie, the browser stores:

    • Name
      A website can have multiple cookies, and the easiest way to organize these is to give each cookie a name.
    • Expiration
      When the cookie will expire. As you might imagine, once a cookie expires it is deleted.
    • Domain
      The domain that the cookie is tied to. Browsers are smart and only allow a website access to cookies from its domain.
    • Path
      The path of the website that can access the cookie. If its value is /test/, only files inside that directory (or in subdirectories) can access that cookie.
    • HTTPS
      If a cookie is HTTPS-only, the website won’t be able to access it when you are using HTTP.

    Many of these options keep cookies from being tampered with. By restricting both domain and path access to a cookie, you can tell the web browser exactly where the cookie needs to be used and can protect it from code running on any other part of the server. Furthermore, marking a cookie as HTTPS-only ensures that the only time a cookie will ever be sent to the server is over a secure connection, preventing things like Session Hijacking.

    Now that we know what cookies are, we are going to turn our head towards how they function. And to know about that, we have to know about Headers.

    Headers are meta-data that gets sent to your browser before a page is loaded, and when that page is returned. It contains information about what browser you are using, what page you are requesting, and more. A typical set of headers for requesting google.com would look like:

    Host: www.google.com
    Accept-Language:en-US,en;q=0.8
    User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.15 (KHTML, like Gecko) Chrome/10.0.612.3 Safari/534.15

    Cookies are just another set of headers. When I visit a website, my browser looks at all the cookies on my machine and based on the domain and path restrictions, makes a list of all the cookies that should be sent to the website. It then creates a header called “Cookie” with all of the cookies delimited by semi-colons, and sends it to the server. Something like:

    Cookie: rememberme=true; user=12345; views=5010

    Just for a reference, the format is cookie_name=cookie_value.

    It works almost the same in reverse. When you request a webpage, the server will send a set of header back to your computer telling about the webpage such as the size of the webpage, the language, and other information that the browser needs to know. To set a cookie, the website simply sends a Set-Cookie header with the data it wants to be saved:

    Set-Cookie: cookie_name=cookie_value; expires=Fri, 21-Dec-2012 22:25:57 GMT; path=/; domain=.domain.com

    In this case, semi-colons separate sets of parameters. The first set of data is the actual cookie. After that is the expiration time, the path restrictions , and what domain it belongs to.

    Posted in Programming | Tagged , , | Leave a comment