CategoryProgramming

Notes on MITx: 6.005.1x Software Construction in Java (Week 1)

MITx has released a course titled “Software Construction in Java”. The course is aimed for more experienced Developers and is going to teach a couple of general principles of Software Development.

The course has the goal that you develop good code, which is defined as:

  • Safe from bugs: Correct behavior of the code, now and in the future
  • Easy to understand: Code should be easily understandable by other developers
  • Ready for change: Architectural patterns that allow you to modify the code without major rewrites.

Over the next couple of weeks I will complete this course and will publish my notes and thoughts on the material.

You can also take the course at https://www.edx.org/course/software-construction-java-mitx-6-005-1x

Why am I taking this course?

I have worked with Java in the past. I do not prefer using the language. However in the Python course from MIT was fantastic and thought very interesting concepts that apply to all languages.

My hope is that this course will teach broader concepts and the language they are using just happens to be Java.

LEcture 1: OVerview + Static Typing

The first lecture i skipped most of the videos, they seemed more like an introduction to Javas static typing, which I was already familiar with.

Lecture 2: Code Review

The second lecture takes a look at good Coding Practices.

Code Review

Lecture notes:

The purpose of a code review has two main goals:

  • Improve the code
  • Improve the programmer

Personal notes:

In reality on many programming projects the “Code Review”- Phase is cut due to budget constraints, lack of time and personal feelings. Remember when you do a code review you may hurt the feeling of another programmer, who thinks he is infallible.

This usually causes that more and more bad code is written. Making the project not maintainable and unreliable.

If it is possible for your project to do Code Reviews, you defiantly should do them, and have a very specific action plan that the other developer can learn from his mistakes.

Style Standards

Lecture notes:

You can find good style guides at https://github.com/google/styleguide

Personal notes:

Every programmer has his personal style how he likes to format and read his code. All university classes (including this one) do not provide a style guide. With the consequence that also no style guide is enforced.

In larger projects this would not be possible. The version control systems suddenly cause problems, create merge conflicts etc.

Styleguides should never be manually enforced. That would be tedious and create a lot of unnecessary work. The guide should be enforced by your build process. This prevents programmers from using their own style guide, avoids merge issues, is easier to manage, and it is psychologically better for the programmer that the machine rejects code rather than another programmer.

The best practice would be that every code commit gets checked prior to be allowed into the repository. This ensures that every developer is playing by the same rules. (To find more information on this subject google for “git hooks” and “java checkstyle”)

Code Smells

  • Don’t Repeat Yourself (DRY)
  • Comments where needed
  • Fail fast
  • Avoid magic numbers
  • One purpose for each variable
  • Use good names
  • No global variables
  • Return results, don’t print them
  • Use whitespace for readability

Personal notes:

While the lecture presents various strategies to prevent the most common beginner mistakes. These are just a select few of all the various types of code smells.

I prefer to use the IDE IntelliJ, it has a feature called “Code Inspector”. It will scan your code and suggest fixes for a lot of types of code smells.

Good code should never have obvious code smells.

Homework

For the “Java Tutor” Homework assignments you must use an Eclipse Plugin.  So sadly you have to use Eclipse with a custom built plugin and as usual I have had a lot of fun with randomly crashing Eclipse, the plugin giving me over and over again the same questions.

The “Java Tutor” is overall quite weak. The questions are more like “fill in the blanks” and only accepts a single correct answer. Usually the titles of the links to the related materials give away the correct answer.

However if you enter the wrong value, you can simply click “Show Answer”, copy the solution and progress without penalty.

Getting Started using AngularJS with Yeoman and Visual Studio Code

Typically to get started with a web-project you would start downloading libraries, configuring grunt etc. Yeoman is a project that takes care of all of this in a simple step and goes one step beyond, it also ensures that you will be using current web-standards. My editor of choice is Visual Studio Code (Other alternatives would be Atom, Sublime, Brackets etc.).

I will be using Windows as my Operating system, all Software is available cross-platform for Mac and Linux. Some commands need to be adjusted for the platform you are using.

Software needed:

Now it may seem odd that python and git is listed here. However while I was trying to get yeoman to work I discovered that bower requires git to be added to the path and since python was missing from my path, some odd errors occurred while creating the initial project.

Getting Started with Yeoman

Working with Yeoman requires you to work with the terminal.

Open Powershell (Powershell is the newer version of the console and emulates more a linuxlike shell) by searching for “Windows Powershell” in the StartMenu

  1. Install a lot of node stuff you need for yeoman
    npm install -g yo bower grunt-cli gulp
  2. Now you need to install the yeoman generator for angularjs
    npm install -g generator-angular

Your first Yeoman project

Simply because you are anyway in the console change the directory to your project directory (something like cd c:/projects)

You can create a new directory using the mkdir-command like:

mkdir angularProject

Finally run

yo angular

to create your project.

You have to answer a couple of questions which (modern) tools&frameworks you would like to use:

Sass (with Compass): Yes

Bootstrap: Yes

Bootstrap Sass Version: Yes

More information about the official yeoman generator-angular can be found here.

If everything goes smoothly the generator-angular created for you an entire modern webapplication project that uses angularjs.

The generated Gruntfile

Grunt is a taskrunner, when properly defined it can automate a lot of tedious work. Yeoman essentially does the work of properly defining the gruntfile.

A lot of tasks are to optimize your various files, like css, js and image files. It also takes care of running the preprocessors like sass or less.

It even runs your javascript tests with karma.js. (and now that grunt takes care of most of your repetitive tasks you maybe even have time to write some tests).

What do you need to know?

There are three commands you can use on the console:

  • “grunt” – simply runs all the tasks and provides a working webapp in the “dist” folder
  • “grunt serve” – starts a webserver and automatically updates your browser while you are working on the source files
  • “grunt test” – runs all of your tests

 Visual Studio Code Setup

Well there is not much to do. You need to open the folder of your project.

And out of the Box you can already run the build and test tasks.

To additionally run the “serve” task in Code

  1. Ctrl-Shift-P > Configure Task Runner
  2. In the tasks.json add a new task
     {"taskName": "serve", "isWatching": true } 

 To use the Visual Studio Code Debugger you need to adjust the Debug Configuration

  1. Ctrl-Shift-P > Debug: Configure
  2. Change the line “program” : “app.js” into “program”: “app/scripts/app.js”.

Conclusion

The power of this setup is mostly that most of the stuff comes out of the box, and provides you with a great foundation to create a high quality code project.

You can and should extend the gruntfile to suit your specific needs like to push your project onto your webserver.

Maximum Memory by Windows Services Configuration (BlackViper Settings)

There are a lot of tips and tricks on how to optimize your system memory. One of the main ways to get the most out of your system is to configure the “Windows Services”, essentially tasks and programs that windows starts and stops in the background. These services are needed by other programs, changing this configuration can result in that some programs cannot start or behave in a strange manner. If you mess around with the services, you could disable your access to the internet and its a pain to figure out which service you accidentally stopped that should have been running.

There are only two situations in which you should configure the services

  1. You are desperate and want to optimize a very old pc without having to buy new ram
  2. You are a gamer and want the speediest most lightweight computer

Service Configurations

Fortunately smart people have already played around with various configurations. BlackViper provides on his website a list of “tweaked”, “safe” and “default” settings. However the table on his website is interesting, but not very useful. If you would want to apply these settings you would have to open up “services.msc” and apply each setting manually.

Thankfully I found a way to convert the table into a powershell script.

  1. Head over to his site  http://www.blackviper.com/service-configurations/
  2. Go to your Version of Windows
  3. Use the websites Copy function and save the tap separated table into a textfile
  4. Execute following python code in the same folder

Alternatively you can download the resulting Powershell Scripts for Windows7SP1:  Win7SP1 – BlackViperPowerShell

Note: During the execution of the script errors appear for services that are not installed on your system – just ignore them.

Results

To consistently measure the memory usage I did a clean install of Win 7SP1 on a VirtualBox.

  • Default  39 Processes using  600MB Ram
  • “Safe Configuration”:  29 Processes using 500MB.

While the safe configuration ‘saves’ you 100MB of Memory. The amount of effort of testing if all your programs are still running correctly etc. Does not make a lot of sense – especially when typically you are anyway have 8GB+ RAM in Computers these days.

Image:

Forcing IE 10 to render pages as IE 10

Web Design designed by Simple Icons from the thenounproject.com

Now isn’t that a silly title, sadly it’s one of those things I never thought I would have to deal with. Especially as Internet Explorers market-share is down to 8.8% in June. And seriously people switch to something that supports most of the web standard.

As a matter of fact Internet Explorer 10 defaults to render Webpages with its built in Compatibility Mode (IE 7) when displaying Intranet Websites.

Basically the thinking behind it is, we have an Advanced Browser (mostly) capable of rendering HTML5 Websites, but our Corporate Partners are so backwards that they are still running age-old Websites that possibly could be displayed incorrectly. In matter of fact they call this stupid Feature “Smart Defaults“.

Now as a HTML5 developer you would think, well yeah whatever I’ll just add a meta-tag to the <head></head>

<meta http-equiv="X-UA-Compatible" content="IE=edge">

Well IE 10 looks at it and says “That can’t be right, I am in the intranet, and we don’t have cool HTML 5 sites here! I better render this in compatibility mode!!!”

So the only way to force Internet Explorer to do the right thing is to actually modify the settings of your webserver to add the exact same meta information to the HTTP Response object; Only then IE 10 will say, ok fine ill render it with my weird IE 10 render engine.

You can verify this using the Chrome Developer Tools

  1. Open Chrome, Press F12 to view the Development Tools
  2. Switch to the tab ‘Network’
  3. Navigate to the specific Page
  4. Verify that in the Get Request, the response Header “X-UA-Compatible: IE=10” or “IE=edge”Chrome-IE10-Header

Java: Multiple Functions and one ErrorHandler

Y2K Bug by Cards Against Humanity from The Noun Project

Let’s say you have function fooA() and function fooB() both functions are very similar and throw similar errors.

 public static void fooA(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }

     public static void fooB(){
         try{
             throw new FileNotFoundException();
         }
         catch (Exception e){
             exceptionHandler(e);
         }
     }
 

If you have the possibility to avoid duplicating code you could write a single Error handler and pass the Error to the Error handling function. However you still want to be able to distinguish between different types of Exception and for logging purposes you should mention which function actually caused Exception. The easiest way to figure the Method name is to use e.getStackTrace()[0].getMethodName();
Alternatively you can pass the method name to the Errorhandlerfunction. To do that you can figure out the method name via:

 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
 

To determine the various Exceptions there are two possibilities:

Method 1: Use instanceof

The downside to this method is that it is not as readable and identifiable as ErrorHandling function. (However this depends on personal preferences)

     public static void exceptionHandler(Exception e){
         if (e instanceof FileNotFoundException){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         } else if (e instanceof Exception) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }
 

Method 2: re-throw the Error

Well you are still throwing around with errors, but it is clearly identifiable as Error handler.

  public static void exceptionHandler(Exception e){
         try {
             throw e;
         }
         catch (FileNotFoundException e){
             System.out.println(e + " " + e.getStackTrace()[0].getMethodName());
         }
         catch(Exception e) {
             System.out.println(e.getStackTrace()[0].getMethodName());
         }
     }
 

Google App Engine: Import CSV to Datastore

Processing CSV Data with the Google App Engine is a two step process.
First you need to upload the data and store it in the blobstore.
Then you retrieve the file and process the information and save it to the Datastore(Database).
You can process the csv data with the standard python tools from the csv module, however instead of parsing a file you must parse a BlobReader.

© 2017 Neal Bürger

Theme by Anders NorénUp ↑