Plutonium or Electric Grid to power your TV

Upon browsing the internet to find out some more about nuclear power, and watching some talks which mentioned these topics, I came to an odd question.
Namely "would Plutonium be cheaper than electricity". I had no idea about the cost of Plutonium and how much power output it actually provided - but I do know that NASA
uses plutonium for Curiosity and other space-equipment.

Thus, I set about to find out. First of all, some of the assumption I have made are important.
I decided to find out how much it would cost (In Belgium, but in dollars) to power a television for a century.
A 50" Plasma Television gives about 0.48 Kwh/h - quite a bit compared to older television actually.
Anyway, I don't know enough about TV to know wether or not Plasma is good, or bad, or whatever (don't watch TV) - I just picked a random television.

After some calculating (I did this in "Java" - so I don't mind sharing the code but I think that might be a bit boring, thus I'm leaving it out here)
I found out that powering such a television would, with the current cost of electricty in Belgium, costs about $53316.9 (for a century). A
fair bit of money, but then again, you did have 100 years non-stop top-notch Television that does not at all make you feel like you are losing braincells.

This calculation had a flaw though, I did not account for inflation. Inflation is hard to predict, but there is enough data available on this. I found out the Belgian inflation rate for the past two decades - and calculated the average inflaction rate / decade. 3 lines of code later and I had a better estimate for the cost. This time, it would cost about $55834.78. The difference really made no difference in the end.

The next part was - for me - more interesting. Find out how much energy I can get out of plutonium. It's quite cool actually, 1gr of Pu can generate ~1MW.
Anyway, we had to find out how much Plutonium we would need to keep our TV playing for 100 years straight. Pretty straightforward calculation once you know the output of 1gr of Pu.. We'd need ~10.26kg.

The shady part of this exploration - which probably got me on some government watchlists - was finding out a decent price for plutonium.
Every document I found - which said something about Plutonium, was around the $5k range. (Depending on the "quality").
Because I could not find Plutonium on amazon or another website which actually had a "buy" button, I'll have to go with the average of the documents. (Frankly, I'm assuming this, but it's a fair assumption I'd say)

Going with this assumption, we would pay 5.12*10^7 dollars. ($5127804.78, to be precise).

What does this tell us? - Don't buy Plutonium to power your TV.

Fullscreen CMD (and a glitch).

As people who use CMD are well aware, the maximum size of the command prompt is rather limited. In fact, on a decent resolution it will not even cover 50% of your screen. This can be a bit of a nuissance when you want to pin two programs to the left and right of your screen, creating this gap. (This probably doesn't bother you as much as it bothered me).

The 'trick' to get CMD full-screen is rather easy and can be done with just two commands.

wmic
exit

After that, you can fullscreen the window. Unfortunately when you script this, the glitch is that it closes the CMD running on the background of WMIC, so you don't exit WMIC. Afterwards, typing exit will close WMIC, and CMD already being closed, it closes the whole window.

(Or, you can just wait for Windows10, which has a fullscreen CMD build-in).

g++.exe results in 'no disk in drive' error.

When using MinGW on Windows machines, after setting up your environment variables in the proper way you might want to test the installation by running the following from CMD.

g++ --version

This can result in the error message 'There is no disk in the drive, Please insert a disk into drive X' where X can be any acceptable drive (Note that this would also happen if you try to compile code. It's just a good idea to check if everything works using CMD as to avoid interference from other software which might cause an error). This is due to MinGW looking at that location - on which it can not find anything. (In my case, the drive in question wasn't even a storage drive). The fix for this is rather simple, go to your 'Disk Manager' under windows (Right-click on 'Computer' -> Manage -> Disk Manager), find the drive corresponding to the letter g++ is complaining about and now change this letter to any other letter (that is available).

This will resolve the problem. Though it seems that the good people developing MinGW are aware of this issue, and are fixing it. So by the time you read this, you might just want to try getting a more recent version of MinGW first. πŸ™‚

Pascal's triangle w/ one dimensional array

Pascal's triangle has a well known construction method shown in the image below.

When you see this, the initial response is to create a two-dimensional array, as you need the numbers of row 'n-1' to create row 'n'. In C++ code, this would look like the following.


void pascalTriangle(unsigned size)
{
	int tri[size][size];

	for (int r = 0; r < size; r++)
	{
		for (int c = 0; c < size; c++)
		{
			tri[r][c] = 0;
		}
	}

	tri[0][0] = 1;
	std::cout << tri[0][0] << std::endl;
	for (int rows = 1; rows < size; rows++)
	{
		for (int columns = 0; columns < size; columns++)
		{
			if (columns >= 1)
			{
				tri[rows][columns] = tri[rows - 1][columns]
						+ tri[rows - 1][columns - 1];
			} else
			{
				tri[rows][columns] = 1;
			}
			if (tri[rows][columns] != 0)
				std::cout << tri[rows][columns] << " ";
		}
		std::cout << std::endl;
	}
}

However, you can create Pascal's triangle using only one array. To generate a specific row of pascal's triangle, you can use the following formula:
Thus, when you translate this to code you only need one array, this is my solution:

void pascalTriangle2(const unsigned size)
{
	std::cout << "1" << std::endl;
	for (int row = 1; row < size; row++)
	{
		std::cout << "1 ";
		double arr[size];
		arr[0] = 1;
		double n = row;
		double k = 1;
		for (int i = 1; i < row; i++)
		{
			arr[i] = arr[i - 1] * ((n + 1 - k) / k);
			std::cout << arr[i] << " ";
			k++;
		}
		std::cout << "1\n";
	}

}

You know it has to start with "1" and end with "1", so you only need to find the ones in between.
The code is a literal translation of the formula.

Dine With Me: Two (Facade design)

I am adapting the "Dine With Me" application to eventually become a full-fledged web-application. One of the issues I am facing is where to store the database information, in the current model the data is hardcoded in the Database class. I have not yet decided how I will solve this, and this blog is in part to help me think about the problem, write down my thoughts and possible solutions.

The core of the application has a facade (DineWithMeFacade), which provides a single-point-of-access, from which all other actions can be executed on the program. Pretty standard facade-pattern and nothing much interesting going on, the Swing-desktop application uses this to add friends, retrieve recipes, login, encrypt and encode information, just as you would expect. However, when developing for android, I extended the DineWithMeFacade to add android-specific features, revealing some of the caching-system methods. In addition, the "AndroidDineWithMeFacade" is singleton. This made passing data between activities easier, as well as avoid creating a new instance of the facade for every activities. (Activities don't have a very long lifetime in the app).

During this, the data was still hardcoded in the core, the Android application simply used an external jar to talk to the core. I never like to choose the "singleton" way to solve a problem, though I believe sometimes it is the right choice occasionally. Now I'm making a web-app I thought of refactoring the DineWithMe Core a little, having stopped working on the project for a month or two gave me some new insight in things I could have done better. (Honestly, putting down your code and not looking at it for a while, then picking it up, is a great way to see how easy your code is to understand!)

The refactor

Stacking the preliminary building blocks of the web-app gave me a reason to change the core. When building a web-app, I keep my project's properties in the web.xml file and thus would like to store all the database information there. After thinking about this for a while, I realised it's probably a good idea to use a database.properties file in the Swing application, as to avoid having hardcoded passwords scattered throughout the application. This doesn't come as a shock, but it is something I didn't consider when coding hours on end to reach the deadline for the mobile application project.

The key problem is 'Where to set the database parameters'. The facade exposes the setters of the database class, so any class with access to the facade can change this. So far, there is no problem to be found. The android and desktop applications can both use a properties file to read out the data, and pass it to the facade. Meanwhile, the web-app's Servlet can read the data from web.xml and pass it on through the facade, right?

This would work for the android application, but not for the desktop application. The reason? Well if the DWMAndroidFacade extends the normal Facade, but is a singleton. Thus, I could tell the facade to set the parameters for every service and finito, the work is done!
Now I am left wondering, what I should do. I can have the desktop application and web-app extend the normal facade into a "SwingFacade" and "WebFacade", which are singletons. Now the problem is gone but I'm left with more singletons (though only one singleton in the each project).

After doing a quick search through the swing application, for "new DineWithMeFacade()" the results hinted at a rather small refactor. (Well, that's relative, but it's a rather large project!)

searchresults

After writing this post I'm quite convinced that going the singleton-desktopfacade/webfacade way might be the right way. Singletons pose quite the conundrum, but for a facade I think even the GoF might agree it's acceptable! πŸ™‚

Dine With Me: One

Over the course of the past few months, I have been working on an application titled "Dine With Me". The next few weeks I will write blogs about this project, design patterns, interesting algorithms or other related subjects.

This is the first of those blogs, and I'll explain what the application is, how it came to be and what the current state of the project is.

The past

It started around october-november, when, for a course in 'Mobile Applications' we had to create an android application. We were given complete freedom in what the application would do, but had a few requirements regarding features, such as working both online and offline, using at least one hardware feature, and being responsive (work on android phones as well as tablets).

Enter: Dine With Me.

The idea for this application came from both Vasco Freitas and myself. Vasco was an exchange student at my university, but was only part of the initial part of the project. We worked out the idea for Β the application together, and created some mockups regarding the user interface. All the actual code, both SQL and Java has been written by me, as well as creating the actual user interface.

The motivation for this project was: 'When we are at our dorm, we sometimes cook for everyone, but it's hard to know who will cook when, and whom will attend'. After a while this evolved into 'When someone cooks, either at dorm or at home, whom of the "family" can attend this? Will the eldest son be joining for dinner, or will he be at university, if the dad is cooking, what is the recipe and is it something his family likes?'

With our application, users can keep a list of recipes and a list of friends. They can then create an 'Event', which they can give a name, choose a recipe they are making, and set a date/time for the event. Afterwards, people on their friends-list can get an invite and respond by either accepting or declining the offer.

 

Tools for the job

This is a short list of some tools that came in handy during this project.

  • Eclipse EE
  • PostgreSQL server
  • pgAdmin III
  • Genymotion
  • Github

pgAdmin III is a nifty tool to quickly execute queries on a postgres database, making life just a little easier by providing an easy way to alter the database structure, check where a query goes wrong, and the usual you'd expect from an 'IDE' for database administration. Genymotion is an emulator for Android phones, it's much (much!) faster than the standard emulator you get when installing the Android SDK for Eclipse, and offers some nice features as well such as a screenshot button, emulating tablets and phones of various resolution, and disabling/enabling network connectivity (Handy for the online/offline-requirement!).

The current

At this moment, the android application is finished. My course of 'Mobile Applications' is finished. (Scored 90%, or 18/20 as per Belgian university marks, I lost two marks due to my UI. I'm a software engineer, love back-end software, have zero taste in UI.). In addition to an android application, I made a Swing desktop application just for fun during the semester. It made it easy to test two accounts simultaniously, ergo it was easy to 'send a friend request from A to B with android, accept on B with swing, check friend-list update on A,...

I generated both Javadoc and Code Metrics for the core and swing application. It seems redundant to post some facts about the code here with all the metrics available, so you can check those out if you're interested in seeing how the project looks like.

Furthermore, both the 'swing' and 'android' application are available on github. Note that the swing application is really just a UI wrapper around the core, therefor the swing is included in 'DWMCore' and is packaged into a jar file for the 'DWMAndroid' application.

The UML at the current state is shown below. It's updated frequently (as it provides a good way for our lecturers to see what's going on as wel).

The future

Currently I am following a course called 'Internet Programming', for which we have to make a (distributed) web-application using Java EE as main programming language. For this course, I am extending 'Dine With Me' to a full-fledged web application, adding some features such as chatting with other users and uploading images for the recipes. This is all in the baby-phase, if you checked the github commits right now, it would say 'reboot' in which the changes made to the project are for a more flexible online-offline strategy. (Using the strategy-design pattern, instead of using a caching mechanism under android).

I'm very exited for this project, at some point I might publish it on a tomcat server, together with another application I'm working on which uses the steam-API. This one, Dine With Me, will always remain opensource software though, and anyone willing can contribute to the github project.

Creating swing buttons based on model methods.

It's hard to find a concise title for what I'm writing about today, so feel free to suggest better ones. What I'm showing today is how you can create JButtons on a JFrame based on methods defined in a model class. This has some problems ofcourse, mainly your model "telling" your view which methods to bind to, and there is no direct use I can imagine. Thus the million dollar question: "Why"? Well, because it's fun.

We only need a few classes to try this, the ones I have used are

  • Operations - A 'model' class of which we want to call the methods
  • Generator - Also 'model', used to generate buttons based on methods in 'Operations'
  • SimpleUI - A JFrame to which we want to add the buttons

Those are the core classes we need, but to make it a bit 'better' in terms of MVC (however odd this may sound as the model is giving buttons to the view), We can also use the following two classes

  • SimpleController - A controller for our UI as in MVC
  • SimpleFacade - A facade (pattern) class to access the generator

The 'magic' actually happens in our generator, but before we get there we need the operations class. This is just a class of which you want to call the methods, to demo this my Operations class has the CRUD methods that simply print out their operations.

package core;

/**
 * Simple class representing some actions to be bound to buttons
 * @author Dylan
 *
 */
public class Operations
{
	
	public Operations()
	{
		
	}
	
	
	public void actionCreate()
	{
		System.out.println("Create!");
	}

	public void actionRead()
	{
		System.out.println("Read!");
	}
	
	public void actionUpdate()
	{
		System.out.println("Update!");
	}
	
	public void actionDelete()
	{
		System.out.println("Delete!");
	}
	

}

This class is the most boring in the project, the most important thing about this class is that each method has the prefix "action". We are only going to generate buttons for methods which have this prefix. Even though there are no other methods visible without the action-prefix, it's important to note that if we would not filter for this in our generator, a lot more buttons would be generated. Because in Java, every class is actually a subclass of "Object", we would generate buttons for methods such as notify() and hashCode().

But now, on to our generator class, where the real work happens. Just as the previous blogpost I have made, we will be using Java's Classloader-system.

The main idea is this: We will use the classloader to load the Operations class, next we will fetch the methods from this class. Next for each method we have found in this class, we will create a JButton and set the label to the name of the method - minus the prefix. (Thus actionRead becomes Read). After we have done this we will attach an ActionListener to this button, and invoke the method with the corresponding name from the Operations class (by again adding the prefix to the name, otherwise we'd compare 'Read' with 'actionRead').

To make this a bit less cumbersome, it may be a good idea to split the fetching of the names and the creating of the buttons up in two methods. The first method will simply return a list of methods whose name matched the signature. (As a sidenote, my 'model' classes are in a package called 'core', it matters for the ClassLoader!)

	public ArrayList<String> listActionMethods()
	{
		ArrayList<String> methodNames = new ArrayList<String>();

		try
		{
			Class x = ClassLoader.getSystemClassLoader().loadClass(
					"core.Operations");
			Method[] methods = x.getMethods();
			for (int i = 0; i < methods.length; i++)
			{
				if (methods[i].getName().contains("action"))
				{
					methodNames.add(methods[i].getName());
				}
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}

		return methodNames;
	}

Now we have a list of names, this could already help us to create simple buttons that have no action hooked up to them - but that would be a bit boring.

Without hooking up an ActionListener to our JButtons, the code would resolve to the following bit.

	public ArrayList<Button> generateButtons()
	{
		ArrayList<String> names = listActionMethods();
		ArrayList<Button> buttons = new ArrayList<Button>();

		for (String method : names)
		{
			Button b = new Button(method.substring("action".length()));
			buttons.add(b);
		}

		return buttons;
	}

Getting that is easy enough. Now to add the actions we can break this down in simple steps again. First, we use the ClassLoader to load our Operations class. Next, we get the methods of this class. Afterwards, we loop over the methods and see if the name matches the prefix+label of our JButton. If this is the case, we can invoke the method we have found with an instance of our Operations class and some arguments (we will just pass an empty object array for this, we could pass null but we'll get warnings).

In code this looks like the following (together with the earlier code of getting the right name on the button).

	public ArrayList<Button> generateButtons()
	{
		ArrayList<String> names = listActionMethods();
		ArrayList<Button> buttons = new ArrayList<Button>();

		for (String method : names)
		{
			Button b = new Button(method.substring("action".length()));
			b.addActionListener(new ActionListener()
			{
				@Override
				public void actionPerformed(ActionEvent arg0)
				{
					// Bind the action
				   try
				   {
				   Class x = ClassLoader.getSystemClassLoader().loadClass(
				 			"core.Operations");
				   Method[] methods = x.getMethods();
					for(int i = 0; i < methods.length; i++)
					{
 	                 	          if(methods[i].getName().equals("action"+b.getLabel()))
			                  {	
					     Object varargs[] = {};
					     methods[i].invoke(x.newInstance(), varargs);
					     break;
					  }
					}
									
				  }
				  catch(Exception ex)
				  {
				 	ex.printStackTrace();
				  }
				}
			});
			buttons.add(b);
		}

		return buttons;
	}

When we have these classes, all that is left to do is make sure the buttons we have generated appear on our JFrame. Our JFrame will ask our SimpleController for a list of JButtons, and our SimpleController will ask our SimpleFacade for them. The SimpleFacade then returns them to the controller, and the controller to the JFrame. The only reason I have used the facade pattern here is because I like having a single-point-of-access to the model from our controllers. The Facade class in this case could have easily been omit and instead just a call to the generateButtons() method of our Generator class would have done. The Facade code:

Breaking the Singleton in Java.

The singleton pattern is arguably one of the easiest design patterns to understand, and many people can probably implement it in their favourite object-oriented language in a matter of minutes.

In Java the implementation of a singelton is just as trivial at first sight as any other language, yet there is a problem which lies in the core of how the JVM works.

There is ofcourse an obvious way of breaking a singleton, multithreading scenarios can cause problems though these are trivial to solve by means of eager initialization, or synchronizing the class before creating a new instance. These will not be discussed as they are problems almost everyone who has worked with Java knows about.

The problem I am talking about lies in the use of reflection, and to demonstrate this consider the following piece of code.

I have a singleton class, named singleton in which I ignore the fact that multiple threads could break the singleton.

public class Singleton implements SingletonInterface
{
	private static Singleton singleton;
	private int value;

	private Singleton()
	{

	}

	public static Singleton getSingleton()
	{
		if (singleton == null)
			singleton = new Singleton();
		return singleton;
	}

	public void setValue(int _value)
	{
		value = _value;
	}

	public int getValue()
	{
		return value;
	}
}

This is a very simple singleton which just holds an integer value. Now if we were to instantiate two of these singletons by calling getSingleton() in the normal way, we would get the same instance. To convince yourself of this fact you can execute the following code.

	public static void main(String[] args)
        {
		Singleton one = Singleton.getSingleton();
		Singleton two = Singleton.getSingleton();
		one.setValue(100);
		System.out.println(two.getValue());
		two.setValue(102);
		System.out.println(one.getValue());

        }

When getting the value of the second singleton, this prints 100, after setting the value of the second singleton to 102, both will print out 102. So far, nothing unusual is going on.

However, the following method found in java.lang.Class, can cause some trouble.

public static Class<?> forName(String className)
                        throws ClassNotFoundException

This should be familiar to you if have ever worked with JDBC, as the JDBC drivers are loaded using class.forName("locationOfDriverJar").

We could however ask this to create a new instance of the singleton class for us, and what will happen is that a new object gets returned rather than the existing object.

try
		{
			Class<?> singletonClass = Class.forName("demo.Singleton");
			Constructor constructor = singletonClass.getDeclaredConstructors()[0];
			constructor.setAccessible(true); // Normally private thus not accessible
			Singleton three = (Singleton) constructor.newInstance(null);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

That code will first call forName to return an instance of the class with that name, I have a class called Singleton in the package demo, this that will be returned. Next we have to find that constructor, it has just one (private) constructor which is returned by calling the getDeclaredConstructors method and accessing the first item in the returned array.

The next line of code is where the problem begins, we set the constructors accessibility to true, meaning that the main class now has access to what once was private in the singleton.

Now the harm is done, and we just ask for a new instance which the constructor will give us.

If we refactor the code a bit we end up with a nice demo in the main class.


public class Launcher
{
	public static void main(String[] args)
	{
		Singleton one = Singleton.getSingleton();
		Singleton two = Singleton.getSingleton();
		Singleton three = null;
		one.setValue(100);
		two.setValue(-1001);

		try
		{
			Class<?> singletonClass = Class.forName("demo.Singleton");
			Constructor constructor = singletonClass.getDeclaredConstructors()[0];
			constructor.setAccessible(true); // Normally private thus not accessible
			three = (Singleton) constructor.newInstance(null);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		three.setValue(0xDEAD);
		System.out.println("one: " + one.getValue());
		System.out.println("three: " + three.getValue());
		

	}

}

Running this code will produce the following output.

one: -1001
three: 57005

When quickly running javap -c (the command to decompile the code) on the launcher class we can see the following bytecode which has been generated.

Compiled from "Launcher.java"
public class Launcher {
  public Launcher();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: invokestatic  #16                 // Method demo/Singleton.getSingleton:()Ldemo/Singleton;
       3: astore_1
       4: invokestatic  #16                 // Method demo/Singleton.getSingleton:()Ldemo/Singleton;
       7: astore_2
       8: aconst_null
       9: astore_3
      10: aload_1
      11: bipush        100
      13: invokevirtual #22                 // Method demo/Singleton.setValue:(I)V
      16: aload_2
      17: sipush        -1001
      20: invokevirtual #22                 // Method demo/Singleton.setValue:(I)V
      23: ldc           #26                 // String demo.Singleton
      25: invokestatic  #28                 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
      28: astore        4
      30: aload         4
      32: invokevirtual #34                 // Method java/lang/Class.getDeclaredConstructors:()[Ljava/lang/reflect/Constructor;
      35: iconst_0
      36: aaload
      37: astore        5
      39: aload         5
      41: iconst_1
      42: invokevirtual #38                 // Method java/lang/reflect/Constructor.setAccessible:(Z)V
      45: aload         5
      47: aconst_null
      48: invokevirtual #44                 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;
      51: checkcast     #17                 // class demo/Singleton
      54: astore_3
      55: goto          65
      58: astore        4
      60: aload         4
      62: invokevirtual #48                 // Method java/lang/Exception.printStackTrace:()V
      65: aload_3
      66: ldc           #53                 // int 57005
      68: invokevirtual #22                 // Method demo/Singleton.setValue:(I)V
      71: getstatic     #54                 // Field java/lang/System.out:Ljava/io/PrintStream;
      74: new           #60                 // class java/lang/StringBuilder
      77: dup
      78: ldc           #62                 // String one:
      80: invokespecial #64                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
      83: aload_1
      84: invokevirtual #67                 // Method demo/Singleton.getValue:()I
      87: invokevirtual #71                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      90: invokevirtual #75                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      93: invokevirtual #79                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      96: getstatic     #54                 // Field java/lang/System.out:Ljava/io/PrintStream;
      99: new           #60                 // class java/lang/StringBuilder
     102: dup
     103: ldc           #84                 // String three:
     105: invokespecial #64                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
     108: aload_3
     109: invokevirtual #67                 // Method demo/Singleton.getValue:()I
     112: invokevirtual #71                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
     115: invokevirtual #75                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
     118: invokevirtual #79                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     121: return
    Exception table:
       from    to  target type
          23    55    58   Class java/lang/Exception
}

Here the problem exposes itself in bytecode. Where we first would have an invokestatic to invote the getSingleton() method which returned us the singleton instance held in the class if there was one, and otherwise gave us a new instance, there is now an invokevirtual on the constructor. Which normally would have resulted in the JVM throwing an error, namely:

java.lang.IllegalAccessException: Class Launcher can not access a member of class demo.Singleton with modifiers "private"
	at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
	at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
	at java.lang.reflect.Constructor.newInstance(Unknown Source)
	at Launcher.main(Launcher.java:25)

Does this mean singleton is unsafe? Well, partly. You can trust your colleagues to not instantiate the singleton like this, but if software engineering has taught us anything over the years it's that you should not anyone, in fact not even yourself as you might instantiate the singleton like that yourself if you haven't worked on the project in a while. (Though I don't see it happening as it's easier to just quickly call getInstance, but you never know!)

There are some solutions to this problem that involve some workaround, to make sure your singleton is completely safe from people calling forName would not even be enough frankly, as there are other ways of breaking the singleton pattern using the ClassLoader and playing around with that.

To conclude: Should we still use singletons?
Well, I sometimes use a singleton because it's a quick fix to a problem, but there are numerous reasons not to use singletons. There is the good blogpost Why Singletons are Evil about it. If you're still not convinced, see what they can cause in a large project (4787 classes, 15% singleton). Though as with anything, if you know what you're doing you might get some use out of them, though slightly modified. πŸ™‚

In Microsoft Mathematics 8+1=10

The next version of Windows will be called Windows 10, but why is that? Surely people working at microsoft are capable of simple addition, but people whom wrote code in the nineties might have made the mistake of not making their programs "Future Proof".

Take the following piece of code.

if(version.StartsWith("Windows 9")
{
}
 else 
{
}

This would be an easy way of checking for Windows 95 and 98, and back then maybe no one expected microsoft to make it to version 9. I don't know why they didn't just use a name like Windows XP / Windows Vista for this release, and then have the next one be called Windows10. But, why do the expected when you can do the unexpected? πŸ™‚

EDIT: Similar code can be found in A lot of places.

How the mind works - kinship.

View the code on github

In the book 'How the mind works' by Steven Pinker , an example is given for how our reasoning can be explained through the use of demons.

Demons can be thought of as knee-jerk reflexes, reactions that just perform one task. In his book, he explains how you could create a computer program which solves problems in a similar way as the demons would in our mind.

The question posed to the program is one that humans can solve in much less than a second, namely: "Is X my uncle?". In his book, he explains that a group of demons could solve this problem, with each having a specific task. For a full overview of how the workings of our mind can be explained using demons, you'll have to read the book. However, my code functions as a computer implementation of the "demon algorithms", exploiting some of the power of object oriented programming. The book, which was written in 1997, omits these details, either for clarity for the reader or because Steven isn't a programmer.

An overview of the program can be seen with this UML, outlining just the model part of the program. The actual program on github has the full MVC pattern, but I omit those as the GUI is not part of what I aim to explain.

Model class diagram
class diagram of model

There are 5 classes representing demon behaviour in the program.

  • GoalReached
  • ParentOf
  • SiblingOf
  • UncleOf
  • DistinguishGender

Each behaviour represents a different type of demon explained in the book. Although, in fact, all demons can be thought of as the same "object", with different "behaviour". Thus, in my code, you'll recognize the Strategy Pattern being used. I have created a demon class which outlines the generic behaviour to every demon, but the explicit implementation of the demon depends on the behaviour we give him. Every demon has a "trigger", which can be thought of as "new information entered our short-term memory, thus we need to see if it's information we need to act upon". You can tell our demon observes the mind, as it is registered of an Observer to the BulletinBoard class

Our demon class looks like this

public class Demon implements Observer
{
	public DemonFunctions demonBehaviour;
	
	public Demon(DemonFunctions behaviour)
	{
		demonBehaviour = behaviour;
	}

	@Override
	public void update() 
	{
		System.out.println("Demon-activated");
		if(demonBehaviour.isTriggered())
		{
			demonBehaviour.respond();
			Bulletin b = Bulletin.getBulletin();
			b.printBulletin();
		}

	}
}

As you can tell, the demon class doesn't tell exactly what to do, but asks it's behaviour to perform the actual task. Inside each of the five demon behaviours, we implement the algorithm. To give an example, here is the ParentOf implementation.

package net.itca.core.htmw.kinship.demontypes;

import java.util.ArrayList;

import net.itca.htmw.kinship.core.Bulletin;
import net.itca.htmw.kinship.interfaces.DemonFunctions;

public class ParentOf implements DemonFunctions
{
	String trigger = "Find parents";
	String foundGoal;
	Bulletin bulletin = Bulletin.getBulletin();
	ArrayList<String> goals;
	public ParentOf()
	{
		
	}
	@Override
	public boolean isTriggered()
	{
		goals = bulletin.getGoals();
		boolean triggered = false;
		for(String goal : goals)
		{
			String[] split = goal.split(" ");
			if(split[0].equals("Find") && split[2].equals("parents"))
			{
				foundGoal = goal;
				triggered = true;
			}
		}
		
		return triggered;
	}
	@Override
	public void respond() 
	{
		String[] split = foundGoal.split(" ");
		String person = split[1]; // Person = the 'person' of whom we want to find the parents.
		int limit = person.indexOf("'");
		person = person.substring(0,limit); // to filter the " 's of me"
		
		// Find all the parents
		ArrayList<String> LTMem = bulletin.getLongTermMemory();
		for(String memory : LTMem)
		{	
			String[] memsplit = memory.split(" ");
			if(memsplit.length >= 3) // If it's less, it's a gender statement
			{
				if(memsplit[1].equals("parent-of") && memsplit[2].equals(person))
				{
					bulletin.addShortTermMemory(memory);
				}
			}
		}
		
		bulletin.removeGoal(foundGoal);
		// Alter the bulletin board
		// Copy parents to short-term memory
		// Remove goal
	}
	
}

The ParentOf demon is triggered by a Find-Parents inscription in our mind.

To understand the data our mind deals with, we have to look at the BulletinBoard class and NOT the Mind class .
In "How the mind works", the brain is described as having a special BulletinBoard, on which memories can be stored in three seperate areas. One area for the long-term memories, one for short-term and one for goals. Goals are essentially a part of short-term memory where we know what we want to achieve.

A singleton class, named BulletinBoard is used for this.
The BulletinBoard is a simple class to understand, it holds some Lists of Strings, which represent a "memory". It's a Singleton and an Observable. Whenever the bulletinboard gets updated (i.e: memory is updated by adding / removing a string), the bulletinboard sends a notification to all listenening observers.

If you have read the book, I'm sure that the code on github is easily understood from the outlines I have given here. In case you do have another question, or I overlooked some key part, don't hesitate to contact me.