JavaScript

JavaScript: private variable with prototype access

I was programming Java for over 6 years and I still sometimes think in object oriented fashion (you know: classes, static methods, interfaces, etc.). One of my recent problem to solve was to write an object with some private collection and public interface in JavaScript. So my first solution was like this:

var MyArray = function() {
	var array = [];
	this.add = function(item) {
		array.push(item);
	}
	this.getAll = function() {
		return array;
	}
}

var myArray = new MyArray();
myArray.add("some item");
console.log(myArray.getAll()); // ['some item']

That solution is perfectly fine is you need only couple of instances of this object. But memory usage is always my concern, so I wanted to make it better. In Java you don’t have to think about such issues, because you have classes. In JavaScript you have only objects and theirs prototypes. So maybe lets try to move methods add and getAll to prototype?

var MyArray = function() {
	var array = [];
	MyArray.prototype.add = function(item) {
		array.push(item);
	}
	MyArray.prototype.getAll = function() {
		return array;
	}
}

var myArray1 = new MyArray();
myArray1.add("some item 1");
console.log(myArray1.getAll()); // ['some item 1']

var myArray2 = new MyArray();
myArray2.add("some item 2");
console.log(myArray2.getAll()); // ['some item 2']
console.log(myArray1.getAll()); // ['some item 2'] - ERROR

As you see, this approach is wrong. Prototype will not work that way. Array in those methods is a reference to array created in last constructor call.

There are couple of options to solve this issue.

Use Safe Factory Pattern

Basically Safe Factory Pattern uses inner state variable to hold all references to objects used by prototype methods. Great description of this pattern can be found here: http://www.codeproject.com/Articles/133118/Safe-Factory-Pattern-Private-instance-state-in-Jav

There are also ready to use modules implementing this pattern:
https://github.com/dcleao/private-state/ – I didn’t use it, but if you did, please let me know in comments.

Use Safe Factory Pattern with implementation based on WeekMap

var MyArray = (function() {
  var refs = new WeakMap();

  var MyArray = function() {
    refs.set(this, []);
  };

  MyArray.prototype.add = function(val) {
    refs.get(this).push(val);
  };

  MyArray.prototype.getAll = function() {
    console.log(refs.get(this));
  };

  return MyArray;
})();

var myArray1 = new MyArray();
myArray1.add("some item 1");
console.log(myArray1.getAll()); // ['some item 1']

var myArray2 = new MyArray();
myArray2.add("some item 2");
console.log(myArray2.getAll()); // ['some item 2']
console.log(myArray1.getAll()); // ['some item 2'] - FINE!

Add methods as constructor function properties and bind them inside object

var MyArray = function() {
	var array = [];

	this.add = MyArray.add.bind(null, array);
	this.getAll = MyArray.getAll.bind(null, array);
}

MyArray.add = function(array, item) {
	array.push(item);
}
MyArray.getAll = function(array) {
	return array;
}

var myArray1 = new MyArray();
myArray1.add("some item 1");
console.log(myArray1.getAll()); // ['some item 1']
var myArray2 = new MyArray();
myArray2.add("some item 2");
console.log(myArray2.getAll()); // ['some item 2']
console.log(myArray1.getAll()); // ['some item 2'] - FINE!

This approach has small disadvantage, because for each instance of MyArray we need to bind both methods.

When I first encounter this issue I started to think that JavaScript is having problems in places, where you cannot imagine as for example Java developer used to having classes, static methods, etc. Lesson learned is that when working with other technology stack, we have to stop thinking with patterns and drop some habits.

What do you think all solution mentioned above? Which is the best? If you have any other, please let me know.

General

Becoming expert vs great programmer

Just a month ago I have changed my job. After almost 4 years in a big company I realised, that I have to move forward. It become clear because of many factors but one of most important was the title of this post: becoming expert vs great programmer.

Becoming expert

When you start new job, specially on middle or junior level, you learn a lot. You gain experience really fast and you feel satisfied. After some time you are proficient enough to handle almost all kind of task by yourself. At that moment in time you know architecture of your project, tools and techniques used during development. Of course there are cases when you need to ask more experienced developers/architects about some solutions, but you are quite confident about your skill and abilities to handle those tasks.

From that point you wave usually couple of directions in your career:

  1. Practice your craftsmanship and master in detains all nuances of language/framework used in your project.Basically it is great to become expert in usage of some framework or programming language, but it is possible that after 5-10 years nobody will use this framework anymore (just for example look what happen to YUI – Yahoo decided to stop development of this framework, because front-end development went in different direction and big, good for everything frameworks are not cool nowadays).
  2. Focus on gaining more business knowledge.That is also good if your are really interested in some area, but after time passes by developers are usually bored and in longer terms are not good business analysts. Developers are people who need technical challenges. Working as business analysts requires more focus on human relations and understanding needs of customers. Gaining more business knowledge gives you also a chance to become Lead or Manager, but there are not so many programmers, who are good as managers. Usually when they start managing they have poor results.
  3. Start looking for new job where you can learn other languages/frameworks.That solution is quite interesting. The problem is that it is not easy to get job for which you don’t fullfil requirements. There aren’t many companies, which are willing to hire and train developers. Usually interesting companies are looking for senior level developers, because it is most cost efficient.

Becoming great developer

So what to do, when you feel a little bit bored in your current job and looking for challenges? In my opinion there are couple of things worth mentioning:

  1. Read books about programming in general, like: Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin), The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin), Refactoring to Patterns (Addison-Wesley Signature)
    etc. Those books will help you become better developer without being tidied to particular language/framework.
  2. Learn designs patters (Design patterns : elements of reusable object-oriented software
    )
  3. Learn Test Driven Development (Test Driven Development (The Addison-Wesley Signature Series) and Behaviour Driven Development.
  4. If you have some gaps in you basic knowledge – fix that. Many times on interviews I ask people if they know how HTTPS works, what is the difference between TCP and UDP or between functional and procedural programming . It is surprising how many developers don’t have wider background. I know that it may look that this knowledge is not important during day to day development. But it is really important if you want to understand nature of some problems.
  5. Focus you work on creating solution with great quality and treat all of your tasks as exercises in applying things learned from points above.
  6. Learn some new languages/frameworks by going through tutorials and some pet projects.

Those steps will lead you to a place, where languages and frameworks are only tools and you focus on finding solution to a problem. From here you can switch your tools and be quite proficient in any other technology. Maybe you will not become expert in it in one week, but you will be able to create clean, maintainable solutions. And if you look from other perspective – stakeholder are not interested if you know how JVM handles integers smaller than 128. They are interested in getting their problems solved.

In my opinion great developer is a person who knows, that some tools better feet some problems. But in order to see this you have to get wide knowledge and this is harder if you focus only on business area or only on one language.
Moreover in the time of microservices and lean development, it is important for each developer to be able to switch tools as requirements change. It is fine if you are great Java developer, but maybe next week your boss will tell you to use Python to build a REST service. Are you able to learn new language and develop clean, maintainable solution after few days?

I think that way for becoming great developer somehow relates to Dreyfus learning model. In this model Expert is a person, who wants to get context in order to talk about some problem. He doesn’t use hammer and doesn’t see all problems as nails. He is free from thinking by his tools. He thinks about problems and solutions. I will come back to this model in future, but for now you can read more about this: here.

Becoming expert is not bad, but how many COBOL experts do you know today?

Agile General

Types of leaders by Roy Osherove


In my previous post The three team phases – from Notes to a Software Team Leader: Growing Self Organizing Teams by Roy Osherove  I was looking at team phases. Now lets check what types of leaders we can become according to Roy Osherove.

Command and control

We’ve all seen or have been this type of leader at some point. You tell people what to do. You are the “decider.” You take one for the team, but you also have the team in your pocket in terms of hierarchy, decision making, and control over everyone’s actions.

The command and control leader might also solve everyone’s problem for them. I once had a team leader who, on the first day that I joined the team, set up my laptop while typing blazingly fast on the keyboard and not sharing with me anything he was doing. When I asked questions, he muttered something along the lines of “Don’t concern yourself with this now. You have more important things to do.” (read that sentence with a heavy russian accent for better effect.)

With a controlling leader, there is little room for people to learn, take sole ownership of anything, or take initiative that might go against the rules. And that’s just the way things are.

This approach won’t work if your team already knows what they’re doing or if they expect to learn new things and be challenged to become better.

Coach

The coach is also known as “the teacher” and is great at teaching new things to others. The opposite of the controlling leader, the coach is great at teaching others to make decisions while letting them make the wrong decisions as long as there is an important lesson to be learned.

Time is not an issue for a coach because time is meant for learning. It’s like teaching your kid to put on their shoes and tie their shoelaces—it takes time, but it’s an important skill, so you’d be making a mistake not taking the time to let your kid to go through this exercise on their own, cheering them from the sidelines.

This approach won’t work if you and your team don’t have enough free time to actually practice and do any learning. So if you’re busy putting out fires all day, and you’re already behind schedule anyway, you won’t have time to also learn or try new things like refactoring or test-driven development.

Facilitator

The facilitator stays out of everyone’s way. Whereas the coach challenges people to stop and learn something, the facilitator simply makes sure that the current environment, conditions, goals, and constraints are such that they will drive the team to get things done. The facilitator doesn’t solve the team’s problems but instead relies on the team’s existing skills to solve their own problems.

This whole approach won’t work if the team does not have sufficient skills to solve their own problems (such as slow machines, talking to customers, and so on).

 

That was one of many great thoughts from Roy Osherove book. I will post some more soon. If you would like to read this book, please follow this link:

Java

Unable to read jar manifest from pom

Few days ago I was trying to use Spring Boot to implement some small project and I encounter strange problem. When running command

mvn eclipse:eclipse

I was getting this error:

[INFO] Unable to read jar manifest from C:\Users\Maciek\.m2\repository\org\springframework\boot\spring-boot-dependencies\1.1.1.RELEASE\spring-boot-dependencies-1.1.1.RELEASE.pom

My pom.xml was like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	...
	<dependencies>
		<dependency>
			<!-- Import dependency management from Spring Boot -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>1.1.1.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>

</project>

I was a bit surprised, but after some googling I found out that it was my stupid mistake with copy/paste. On the Spring Boot Reference Guide it was:

<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.1.2.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Skipping dependencyManagement was root cause of error mentioned at the beginning.

Be aware of copy/paste failures!

Eclipse Java

Eclipse/JUnit: CreateProcess error=206, The filename or extension is too long

If you encounter problems with running junit test in Eclipse and you get following exception:

Exception occurred executing command line.
Cannot run program "C:\Program Files\Java\jdk1.7.0\bin\javaw.exe" (in directory "C:\......"):
CreateProcess error=206, The filename or extension is too long

please download patch for Eclipse.

For Eclipse Juno and newer:
https://bugs.eclipse.org/bugs/attachment.cgi?id=216593
For older Eclipse:
https://bugs.eclipse.org/bugs/attachment.cgi?id=219900

After download back up existing eclipse/plugins/org.eclipse.jdt.launching_3.*.jar
Copy and paste classes in the patch to org.eclipse.jdt.launching JAR (replace existing files).
Restart Eclipse.

For me it worked.

In bug report Bug 327193 it is considered fixed, but it happen to me recently with Eclipse Kepler 4.3.2.