Showing posts with label Josh. Show all posts
Showing posts with label Josh. Show all posts

Monday, January 29, 2018

Java: Switches

Throughout my time programming, there have been many times where I needed to get an input from a user, and depending on what they inputted, I needed to run different code. There are multiple ways of accomplishing this, however some methods are faster than others and much easier to work with.

In most programming, the way to do this would be to use a lot of if and else statements, chained together. The first if statement checks if a certain value is true, and if so, it runs the following code. However, if the value is false, it goes on to the else statement, or else if statement. The else statement runs the next code without question, however the else if statement acts just like the first if statement. This means that you can chain lots of these together to test for different possible inputs, and only the code for the user's input will be run.

As you can see, this option will get long and confusing as more options are added due to the difficulty to read the code. There is so much extra code that is required that the code that is more important is easily lost. Barry Burd, a computer science educator with a PhD, wrote that lots of if statements seems wasteful and "why not create a statement that checks the value of [a variable] just once and then takes an action based on the value it finds?" (Burd 132). Luckily, there is a simple solution to the problem. Several years ago, a new feature was implemented into Java that allowed switches to replace the complex if and else statements. This new method was short, simple and easy to use and understand, plus it was scalab.e This meant that if there was anything that needed changes, it would be easy to change.

As you can see in the second image, each if statement has been replaced by a case statement inside of the switch. The switch defines what variable to check, and the cases define what options the variable can be. Burd explained that "the computer checks the value of the [inputted] variable. When the computer determines that the [inputted] variable's value is 2, the computer checks the case of the switch statement. The value 2 doesn't match the topmost case, so the computer proceeds to the middle of the three cases. The value posted for the middle case (the number 2) matches the value of the [inputted] variable, so the computer executes the statements that come immediately after case 2" (Burd 133). This was still a problem for me, because if a user inputted text such as "strONGly agRee", the code wouldn't recognize it. To solve this, I decided to first make the variable lowercase, then checked for all lowercase answers as there is no way to ignore the case of each answer as I could in the first method.

Other than that, this method is extremely useful and much easier to use! The code is simpler, easier to understand and easier to add on to if future changes are necessary. All of this adds up to make switches a great addition to the programming language, and something that should be taken full advantage of!

Have you ever tried to repeat a task over and over, only to get tired of it before you were even done?

Works Cited:
Burd, Barry. Java for Dummies. 7th ed., John Wiley & Sons, 2017.

Wednesday, January 24, 2018

Java: Databases and Data Storage

When writing code in any language, it is almost always important to be able to store lots of data. Depending on the scenario, there are many ways of keeping your data safe in Java.

A very popular data organization and storage method is to use an external database, such as a MySQL server. Your program can then connect to this server and send it data, as well as retrieve data from it in huge quantities. This is great for things such as storing lots of user accounts, details on a library of files, or other various data in large amounts. To demonstrate this, I created a simple function that when run, will connect to the specified database and will create a table to store data in.

The database can be thought of as a library full of books, each book being a table. Within each table, there are spreadsheets of data, with columns to label the data, and individual rows of data spanning across the columns. This is just like spreadsheets in programs such as Excel!

Data storage is such an important part of programming, that throughout Barry Burd's career, the general consensus about programming from his students was that "We don't need to make attractive-looking layouts. No glitzy GUIs for us. We need to access databases. Yup, just show us how to write Java programs that talk to databases" (Burd 445).

While this piece of code only creates a new table, the same code can be reused to add, remove and get data from the database as well because of the SQL standard that most databases follow in order to simplify things.

Another way of storing data is to use collections. However, collections won't persist across restarts of the program. By using this in conjunction with databases, the program can be much faster and easier to use. The program can start by storing data in a collection, and it can periodically update the database to make sure it's data matches what is inside the local collections. This will ensure that the data is saved, but by reducing the amount of times the database has to be accessed, it makes the program faster. Comparing this to the library from earlier, it wouldn't be very efficient to drive to the library and write down the details of a user into a book every time they submitted a change. Instead, by driving to the library only at the end of each day, lots of time and money is saved.

Here, I wrote a simple class with a collection called an ArrayList. To put it simply, an ArrayList is just a list of values. The collection, called names, stores a list of all usernames. There's a function to add a name, to remove a name and to check if a name is already in the collection. While this is just a simple example, the concept can scale very well and be easily expanded to suit the needs of almost any program. The benefit to collections over simpler data storage methods such as arrays, is that if you're keeping track of your users and you have an array, the array has a set maximum value. Similarly to a hotel with a limited number of rooms. For example, if you have 100 rooms, "All is well until, one day, customer number 101 shows up. As your program runs, you enter data for customer 101, hoping desperately that the array with 100 components can expand to fit your growing needs. No suck luck" (Burd 322). Collections expand on this simple concept and are scalable, easily expanding and shrinking to fit your needs and to minimize the usage of the limited space on the computer.

Have you ever tried storing lots of data somewhere and keep it nicely organized? Or even tried to organize your room and keep it that way for longer than a month? Is it a challenge, or does it just come naturally to you?

Works Cited:
Burd, Barry. Java for Dummies. 7th ed., John Wiley & Sons, 2017.

Sunday, December 31, 2017

Java: Abstract Classes and Interfaces

Building on what I learned previously, Java also makes use of abstract classes. These special objects can't be used on their own, but are more of a building block that other, more complex objects are built upon. "An abstract class has no life of its own. In order to use an abstract class, you have to create an ordinary (non-abstract) class that extends the abstract class" (Burd 419).

From the last example, I made an abstract class called Command. This object can't be made on it's own, as it has no actual function, but is what makes sure that all future commands based on this will follow the same hierarchy.

These abstract classes are important because without the class being abstract, someone, including yourself, might accidentally try to create an instance of the abstract class, which shouldn't happen. Adding abstract ensures that the code won't be misused accidentally. By adding abstract methods, or functions, this means that all classes that are based on it must create their own code for those methods. The benefit to using abstract classes to be extended over other similar types of classes such as interfaces is that a child can only inherit from one abstract class, but can inherit from many interfaces. This means you can limit the inheritance of a child, preventing a mess of many different inherited methods and variables.

However, with interfaces, a child can inherit from many different interfaces at the same time. This means that you can have an interface for commands that are for staff and commands that are only allowed to be used in certain groups. As an example, "[Barry is] an instance of  a Person class with all the fields that any person has - name, address, age, height, weight, and so on. He can also implement more than one interface: Because Barry implements a Professor interface, he must have methods named teachStudents, adviseStudents, and gradePapers. Because he implements an Author interface, he must have methods named writeChapters, reviewChapters, answerEmail, and so on" (Burd 411).

Here I made a command that is used to change the prefix that is used before a command in chat so that the program can tell the difference between a chat message and a command. The command extends a command, so it inherits the structure of a command, and also implements StaffCommand and RestrictedCommand. The StaffCommand inheritance requires the permissionLevel function which gives a number used to represent a hierarchical system where the lower the number, the less permissions the user has. Therefore, this command requires a user with permissions of 4 or greater. The RestrictedCommand inheritance requires the canUseCommand function. This takes the chat channel that the message was sent in and if the channel's ID matches the one provided, the command can be used. Otherwise, the command will not be run.




Do you think that having multiple systems of inheritance is more confusing, or is it nice to have a greater variety of tools to work with in order to keep everything organized and categorized?

Works Cited:
Burd, Barry. Java for Dummies. 7th ed., John Wiley & Sons, 2017.

Friday, December 29, 2017

Java: Working with Objects

When programming, it is important to use objects to help reduce the amount of redundant code and make the program faster. It is also useful as reducing redundancies will help organizing the code to make it easier to read and understand, especially when dealing with many different instances, such as multiple users. "The question is, when writing a computer program to deal with accounts, how do I separate my balance variable from your balance variable?" (Burd 162).

On the popular chat service, Discord, I created a program that can have different commands the users  can use to make the program do different things such as showing data or statistics about a user. To make the software simpler, I made a single type of object called Command. Then all commands I make can be based on that generic Command object. This means that if I wanted to substitute one command for another, I can easily do so without changing much of the code if I base everything off the generic object rather than specific commands.









Here's a simple Command object with 3 functions. There is the onCommand function, that I can run with some variables to make the command run it's unique code that varies between commands. There is also the getDesc function that just returns a description about what the command does, and finally the isHidden function that returns whether or not to hide the command from the help menu.
From the example in the book with bank accounts, Burd says that "the Account class... defines what it means to be an Account. In particular, [the code] tells you that each of the Account class's instances has three variables: name, address and balance" (Burd 163). Anything that is an account must have the same three variables no matter what.

Here's a sample command I wrote called ping. When it is run, it will display the program's current ping in the chat. The ping is the amount of latency or time between when it contacts the Discord servers and when the Discord servers can send information back to the program, so the lower the ping, the faster and more responsive the program can be. The sample command "extends", or inherits the basic structure of the generic Command object. Then it has the onCommand function which sends a message back to the user who executed the command with the ping. The getDesc function gives t he description, "Pong!", as the return message from a ping is known as a pong message. And finally, the isHidden function will return false, as the command should not be hidden from the help menu.
Finally, putting this all together, the code gets another object called the CommandManager, which keeps a list of all commands, and it searches for a command based on what the user inputs. If no command is found, it stops there. However, if a command is found, it can run the onCommand function with the proper variables because any code for a command will always have an onCommand function as the generic Command object defines the structure of any command.

What do you think of the simplicity of having a single "parent" object that all "children" objects must inherit traits from? Does it make the code simpler as all child objects are alike, or is it more complex for child objects to be forced to conform to the parent's traits?

Works Cited:
Burd, Barry. Java for Dummies. 7th ed., John Wiley & Sons, 2017.

Thursday, November 30, 2017

Java: Classes and Code Organization

I have been programming in Java for over 6 years now, but because I was never formally taught the language, there are likely some things that I do that aren't part of the official standards, or things that may cause the code to be inefficient or hard to work with. In Java for dummies by Barry Burd, the basics of Java are covered as well as more complex topics and how to keep the code organized and effective without becoming a nuisance to work on.

Small sample program that is
easy to understand and work with.
Output of above program.
When learning programming, people start with very basic programs that don't do much. In these small programs, inefficiencies and confusing code don't matter very much, but as the program grows and gets increasingly complex, these small problems add up making future changes more difficult and causing the program to be slow. "For years, companies were buying prewritten code, only to discover that the code didn't do what they wanted it to do... Their programmers dug deep into the program files, changed variable names, moved subprograms around, reworked formulas and generally made the code worse" (Burd 198). This emphasizes the importance of keeping the code neat and easy to work with from the start because if the code is difficult to understand, even the programmer will eventually be unable to figure out what's going on.

More complex part of a program that
determines what code to run next.
As shown in the picture on the right, code can quickly become more complex and difficult to understand.

To organize this code, Java has classes which are used to put related code all in one file, while keeping less relevant code in another file. This helps with organization, similarly to how a book is divided into chapters.
Code all put into a single class
without being properly organized.
 



On the left is part of the original code when all of it is in a single class. As you can see, it's long and confusing with so much there that you can't easily see all of it at once.
Simplified code that is properly organized
and distributed throughout multiple classes.

However, below that image is a simplified version where I have put the code responsible for loading add-ins into a separate class. It is now easy to see that the single
Code for "loadJars()" method shown above.
function, known as a method in Java, "loadJars()" will load the add-ins from the other class.

Below that is a third image, which shows the code that is run when the "loadJars()" method is used. This is much easier to understand and won't result in as much confusion down the road. As you can see, even the "loadJars()" method contains another method, "loadJar(f, false)" that loads each specific file.

By putting methods within other methods, the code is even neater and simpler to understand! This is known as object-oriented programming, where "all the functionality that's associated with an [object] is collected inside the code for the [Object] class" (Burd 170).






What do you think of the organization used in modern, object-oriented programming languages? Does it make the code look neater and less confusing, or is the condensed form easier to follow as the code doesn't jump around?

Works Cited:
Burd, Barry. Java for Dummies. 7th ed., John Wiley & Sons, 2017.