background preloader

Google Guice

Google Guice

Singletons are Pathological Liars by Miško Hevery So you join a new project, which has an extensive mature code base. Your new lead asks you to implement a new feature, and, as a good developer, you start by writing a test. But since you are new to the project, you do a lot of exploratory “What happens if I execute this method” tests. testCreditCardCharge() { CreditCard c = new CreditCard( "1234 5678 9012 3456", 5, 2008); c.charge(100); } This code: Only works when you run as part of the suite.When run in isolation, throws NullPointerException.When you get your credit card bill, you are out $100 for every time the test runs. Now, I want to focus on the last point. But why do I get NullPointerException in isolation while the test works fine when run as part of the suite? testCreditCardCharge() { CreditCardProcessor.init(); CreditCard c = new CreditCard( "1234 5678 9012 3456", 5, 2008); c.charge(100); } You run the test again; still no success, and you get a different exception. Excited, you run the test again: nothing.

Calling JavaFX From Java? While experimenting with JavaFX, remember that Java is never far away. In this case, let's call out to Jim Weaver's JavaFX Calculator demo: Here we go, here's all that's needed, via the Scripting API, which is included in the JavaFX SDK: 01.package calc; 03.import java.io.InputStreamReader; 04.import javax.script.ScriptEngine; 05.import javax.script.ScriptEngineManager; 06.import javax.script.ScriptException; 08.public class CalculatorLauncher { 10. public static void main(String[] args) { 11. try { 12. 13. 14. 15. engine.eval(reader); 16. } catch (ScriptException ex) { And so, here's my whole application, calling Jim Weaver's Calculator demo: Nice.

Where Have All the Singletons Gone? by Miško Hevery In Singletons are Pathological Liars we discussed the problems of having singletons in your code. Let’s build on that and answer the question “If I don’t have singletons how do I ensure there is only one instance of X and how do I get X to all of the places it is needed?” An OO application is a graph of objects. Collaborator Graph: This is the graph of objects that would be emitted if you serialized your application. If the new operators are mixed with application logic (see: How to Think About the new Operator) then the Constructor Graph and the Collaborator Graph tend to be one and the same. The above shows the application collaborator graph. The HTTP request would come to AuthenticatorPage which would collaborate with Authenticator to make sure the user is valid and forward a valid request onto ChargePage which would then try to load the user from UserRepository and create the credit card transaction which would be processed by CrediCardProcessor.

OOP Spelprogrammering Dataspel Många dataspel kan liknas vid simuleringar av en verklig eller påhittad värld. T.ex bilspel, äventyrsspel, eller spel som SimCity och Sims. Simulera betyder efterlikna. Följande är typiskt för spel-liknande simuleringar: Det finns en värld med objekt Det finns ett tidsflöde (realtid, nedsaktad tid, uppsnabbad tid) Objekten i världen är aktiva och kan ha varierande grad av AI Världen visualiseras på bildskärmen Spelaren kan interagera med objekten i världen på olika sätt Spelprogrammering Centrala delar i ett spelprogram: Grafik ("Sprites") Uppdateringsloop (Timer) Inmatning (mus och tangentbord) Nedan diskuteras dessa. Sprite-animeringar Sprite betyder "älva". Sprites i Java Det finns två grundläggande sätt att programmera sprites i Java: Som komponenter i ett fönster (där spriteklasserna är subklasser till t.ex JComponent eller JLabel) Som egna objekt som ritas upp i via paintComponent. Null-layout Exempel där en JLabel visar en bild på koordinat 100,100: Dubbelbuffrad animering Ljud

Root Cause of Singletons Since I have gotten lots of love/hate mail on the Singletons are Pathological Liars and Where Have All the Singletons Gone I feel obliged to to do some root cause analysis. Lets get the definition right. There is Singleton the design pattern (Notice the capital “S” as in name of something) and there is a singleton as in one of something (notice the lower case “s”). There is nothing wrong with having a single instance of a class, lots of reasons why you may want to do that. However, when I complain about the Singletons, I complain about the design pattern. I would say that at this point most developers recognize that global state is harmful to your application design. The moment you traverse a global variable your API lies about its true dependencies (see: Singletons are Pathological Liars) The root problem is not the Singleton design pattern, the root problem here is the global reference to singleton. Someone pointed out that any design pattern can be abused.

Tutorial: Java Collections - CodeCall Programming Forum Collections Collections are an interface in the java.util package, and as its name suggests, it is used to define a collection of objects. There are many different classes which implement the collections interface. Each one has its unique features, some add elements in a sorted manner, others in a binary fashion. Here is how you do it 1) Declare any object you wish to insert into a Map. DummyClass1 dm2 = new DummyClass1(); 2) Now you declare a HashMap which will store the key value pair. Map m = new HashMap(); //Old method Map<DummyClass> m = new HashMap<DummyClass>(); //New method as per Java 1.5 and above 3) To add the object to a map you need to use the put function. m.put("KEY1", dm1); 4) To retrieve this object use the get method and use KEY1 to identify the object to retrieve it. DummyClass1 dm3; dm3 = (DummyClass1)m.get("KEY1"); List1) Declare the objects you wish to add in the list. DummyClass dummyClass1 = new DummyClass();DummyClass dummyClass2 = new DummyClass(); Code Output List

Dependency Injection – Why Bother? « Chris Collins dependencies by jonathanvlarocca In this post we discuss the various mechanisms of Inversion of Control (IoC) including Dependency Lookup and Dependency Injection. We look at the differences between the various IoC approaches and present the advantages and disadvantages of each. Take the following example Java code. What is wrong with this code? Firstly, we are creating a hard link between the Target class and the Dependency class. This is known as tight coupling. Lets say you want to unit test the Target instance in isolation. Loose Coupling Is there a way we can satisfy this dependency, without the tight coupling? Inversion of Control, or IoC, attempts to solve this issue by providing services by which the Target class can satisfy its dependencies without the tight coupling between them. Dependency Pull Dependency Pull is a type of Dependency Lookup. Contextualised Dependency Lookup Contextualised Dependency Lookup (or CDL to save typing) is similar to Dependency Pull. Like this:

Java Threads Tutorial Java Tutor J2EE Training Web Services Axis EJB Design patterns UML Personal Threads Introduction Thread: A thread is a line of execution of code. Lets understand what is a line of execution of code. A Java program when executed has at least one thread called main thread. JVM creates the main thread. Using Thread Class Subclass the Thread class. At times we need threads in Single Processor(with single core) machines too. How to Write 3v1L, Untestable Code July 24th, 2008 · 15 Comments · by Miško Hevery, Jonathan Wolter, Russ Ruffer, Brad Cross, and lots of other test infected Googlers This guide lists principles that will help you write impossible to tests code. Or, avoiding these techniques will help you write code that can be tested. Make Your Own Dependencies – Instantiate objects using new in the middle of methods, don’t pass the object in. Java Specific Final Methods – Use final classes and methods all the time. C++ Specific Use non-virtual methods – Unless you need to override the method in a deep and scary inheritance hierarchy, just make the method non-virtual. Tags: Advice · Rant · Testability

Java 5 för nybörjare - Programmering & spelutveckling Tillbaka till artikelarkivet Detta är en enkel nybörjarguide i Java. Guiden kommer att inrikta sig på att skapa sk Applets så att vi snabbt kan komma till de lite roligare bitarna av programmeringen. Navigation: Språket Nu har vi lekt runt lite med applets och ritat lite enkla saker. Klasser Nu har jag nämnt ordet klasser ganska många gånger, och du har troligtvis inte så bra koll på vad det är ändå. Metoder Vi har även skrivit ett par metoder. Datatyper En datatyp är en typ utav data. Returvärden Nu ska vi tillbaka till metoderna en liten stund. Konkreta tillämpningar Nu har jag svammlat massor om datatyper, variabler, objekt och så vidare. Så kan en mycket enkel klass se ut. Nu ska jag visa hur man gör ett objekt utav en klass. public class HuvudKlass { public void HuvudKlass() { NyKlass Objekt = new NyKlass();}}public class NyKlass {} Nu uppstår ju en annan intressant fråga. Okej då, detta kanske var lite svårt. int tal;tal = 5;[/source=java]Inte så knepigt va? import java.applet. Till toppen

C#, Objective-C and JavaScript Move Up in TIOBE Index - ReadWriteCloud TIOBE Software has released its programming community index for December 2011, and the numbers show that C# is gaining in popularity. According to TIOBE, the most popular languages right now are Java, C, C++, C# and Objective-C. (In that order.) JavaScript moved into the top 10, up two slots from December 2010. The TIOBE Index from the TIOBE Software Site The TIOBE ratings are based on the number of page hits for languages by searching for "languagename programming" in Google, Wikipedia, Blogger, Bing, Baidu, YouTube and Yahoo. Their long term trends are interesting to look at as well. Alternatives to TIOBE Though TIOBE is frequently cited, it's been criticized and there are a number of alternatives that are worth looking at as well. For example, the Transparent Language Popularity Index, which is an open source project that anyone can examine and run on their own. Java C Objective-C C++ PHP If you look at the top five scripting languages, it's PHP, Python, Perl, JavaScript and Ruby.

Java tutorial for beginners | freejavaguide.com These tutorials will introduce you to Java programming Language. You'll compile and run your very own Java application, using Sun's JDK. It is extremely easy to learn java programming skills, and in these parts, you'll learn how to write, compile, and run Java applications. Before you can develop corejava applications, you'll need to download the Java Development Kit (JDK). How to Install Java These instructions are to help you download and install Java on your personal computer. Downloading and Installing Java On Windows: Prevent Errors like --> 'javac' is not recognized as an internal or external command 1. 2. 4. For Windows 98 or ME, open the file AUTOEXEC.BAT in Notepad. 5. 6.

The Number One Trait of a Great Developer Note: Our very own [Tammer Saleh]( recently wrote a blog post about [hiring for judgement]( With his permission, we're reposting it here. Maybe the best programmers aren't those who spectacularly solve crazy problems, but those who don't create them, which is much more silent. – Lena Herrmann When I look around at other companies hiring Ruby on Rails developers, I see them focusing on three major traits: Super-smart; Large community following; Deep Ruby knowledge. A story about Jack and Dianne Jack is a Rockstar. Dianne is a good developer. “How many devices do we expect to have?” Dianne wrote a RESTful API endpoint in Sinatra with a MySQL DB. Will Dianne's solution scale to 10k users? It's all about trust When given what has the oportunity to be a “fun problem,” developers without judgement tend to run to their cave to craft the most elegant solution possible. Hire for Judgement Tagged:

The Java™ Tutorials The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases. The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. They include hundreds of complete, working examples, and dozens of lessons. Trails Covering the Basics These trails are available in book form as The Java Tutorial, Sixth Edition. Creating Graphical User Interfaces Creating a GUI with Swing — A comprehensive introduction to GUI creation on the Java platform.Creating a JavaFX GUI — A collection of JavaFX tutorials. Specialized Trails and Lessons These trails and lessons are only available as web pages.

Related: