azizkhani.net

I know that I know nothing

innovation

clock September 29, 2012 21:39 by author Administrator

  when you  only work on 100m . innovation just died there.

work on 10000000000000000000000000000000000000m for innovation



Programming Like Kent Beck

clock September 18, 2012 21:33 by author Administrator

Posted by Jakub Holý on September 12, 2012

Republished from blog.iterate.no with the permission of my co-authors Stig Bergestad and Krzysztof Grodzicki.

Three of us, namely Stig, Krzysztof, and Jakub, have had the pleasure of spending a week with Kent Beck during Iterate Code Camp 2012, working together on a project and learning programming best practices. We would like to share the valuable lessons that we have learnt and that made us better programmers (or so we would like to think at least).

 

Values Underlying the Programming Style

Most of the things that we have learnt stem from three basic values: communication, simplicity, and flexibility (in the order of importance). We will introduce them briefly here, you can find a more detailed description in Kent’s book Implementation Patterns, along with few fundamental practices such as the application of symmetry.

Communication

Programs are read much more often than written and therefore should communicate clearly their intent. Code is primarily means of communication. (For a typical enterprise system, a lot of code will be modified by many programmers over 5 – 15 years and they’ll all need to understand it.)

Simplicity

Eliminate excess complexity. Apply simplicity at all levels. Simplicity helps communication by making programs easier to understand. Communication helps simplicity by making it easier to see what is excess complexity.

Flexibility

“Making workable decisions today and maintaining the flexibility to change your mind in the future is a key to good software development.” — Implementation Patterns, Kent Beck

Programs should be flexible in the ways they change, they should make common changes easy or at least easier. Complexity can often arise from excess flexibility, but if that flexibility is not needed then it is waste. The best kind of flexibility comes from simplicity coupled with extensive tests. Trying to create flexibility through design phases or the likes usually ends up with this kind of “complex flexibility”. Most of the time you do not have enough information to make a proper design decision about where your program will need to change, so the lean mantra of postponing your decisions til the last responsible moment is a valid and useful approach. That is when you have the best grounds for any decision.

Summary

Write code that communicates well what and why is done so that your co-workers and future maintainers can take it over without too much cost. (Yet you have to assume some level of skill and knowledge in you audience.) You cannot foresee the future so keep your code simple and sufficiently flexible so that it can evolve.

Key Learnings

1. You Ain’t Gonna Need It!

What is today’s demo? What test to start with?

Before we arrived, we settled on a topic that we thought would be fun and challenging. We settled on trying our hands at prototyping a highly scalable, distributed database. We expected upon arrival to spend few hours discussing approaches to how we should actually implement this. After all, there are lot of things to consider: replication strategies, consistent hashing, cluster membership auto-discovery, and conflict resolution, to name a few. If you have just 5 days, you need to plan how to implement it in the simplest possible way. What to do. What to skip. Right? Wrong. Instead of any planning, Kent just asked us what would be the demo we would like to show at the end of the day. And his next question was what test to write.

It turned out to be a very smart approach because we actually implemented only a very small subset of the possible functionality, deciding daily what to do next based on our experiences with the problem so far. Any discussion from the beginning longer than 10 minutes would be 90% wasted time. This doesn’t mean that planning is bad (though the resulting plans are usually useless), it only means that we usually do much more of it than we actually need. Getting real feedback and basing our decisions on that, on real data, is much more practical and valuable than any speculations.

Therefore prefer on-going planning based on feedback and experience to extensive up-front planning. Ask yourself: What am I going to present at the next demo/meeting/day? What test to write to reflect that and thus guide my development effort?

2. Write High-Level Tests to Guide the Development

The goal of our second day was replication, demonstrated by writing to one instance, killing it, and reading the (replicated) data from the second instance. We started by writing a corresponding test, which follows these steps closely, nearly literally:

1 List<Graft> grafts = Graft.getTwoGrafts();
2 Graft first = grafts.get(0);
3 Graft second = grafts.get(1);
4  
5 first.createNode().put("key", "value")
6 first.kill();
7  
8 assertNotNull(second.getNodeByProperty("key", "value"));

(The API of course evolved later into something more general.)

Now the interesting thing is that this is not a unit test. It is basically an integration test, or to use a less technical term, a story test exercising a rather high-level feature. A feature of interest to the customer. While a unit tests tells me “this class is working as intended,” a story test tells me “this feature works as intended”.

I used to think about TDD at the unit/class level but this is TDD at a much higher level. It has some interesting properties:

  • It helps measure real progress of the project because it exercises something that is actually meaningful to the customer (if you permit me to use this “customer” in a little blurry fashion)
  • It helps keep you focused on delivering business functionality (by being on its level)
  • It’s likely to stay mostly unchanged and live much longer than unit tests or actually most of the code base because it is on such a conceptual level

Now, according to the testing pyramid, there are of course fewer story tests than there are unit tests, and story tests do not test all possible cases. Does it mean that you need to do all these story tests and then do them again only in smaller unit tests? No, that is not the point. Getting back to the principle of flexibility and the way things change, create additional unit tests only when you need them. For example when you encounter some case where the first story test did not actually “capture the whole” properly, or when you discover a really important corner case, or when you want to focus on implementing a part of the overall solution. Speculating about failure points can be just as wasteful as speculating about design.

3. Best Practices for [Unit] Testing

Write Tests From the End

We normally start a test with an idea of what we want to verify, but we may be not completely sure how to arrive there. Therefore it is good practice to express what we do know, the desired end-result, first. We do this in the form of an assertion and only then shift our focus to figuring how to get there. That’s how we started the test of replication in Graft, shown above.

This is an application of the key principle of focus.

Write Implementation in Tests, Refactor Later

You know the functionality you want and so you start writing the test for it. Instead of thinking about how it should be organized (what classes to create, where to put them, whether to use a factory class or a factory method), why not initially write the code directly in the test method? You can always factor out the code later. This way you can focus on what’s really important – describing the desired functionality with a test – instead of being distracted by secondary considerations. Additionally, by postponing the decision about the internal organization of the implementation, you will have more knowledge when actually deciding it and you will likely end up with a better solution.

Key principles: Focus, avoiding premature decision-making.

Bottom-up Design

Avoids:

  • assuming too much, too early
  • locking yourself into a specific design and premature design
  • restricting yourself (you will usually end up with the design you first intended)

Start by implementing small parts of functionality. Then combine them to form more complex behavior. Don’t get distracted by dependencies, write simple stubs for them that you will replace later with real implementations. Using this technique you are not bound to design decisions taken at the beginning as in the ‘top-down’ approach. It requires a little bit of intuition and some experience, but combined with TDD it helps to make better design and implementation.

We found this technique quite useful as we didn’t know the final solution at the beginning. When developing Graft, we haven’t designed the whole application up-front. We picked a use case on the first day, implemented it, and continued by choosing and implementing other use cases each day.

Act & Assert at the Same Level of Abstraction

Our Graft DB has a telnet-like interface for receiving commands from users. Consider the following two (simplified) variations of the addComment test:

1 // Test 1
2 Graft db = ...; this.subject = new CommandProcessor(db);
3 subject.process("addComment eventId my_comment");
4  
5 assertThat(subject.process("getComments eventId")).isEqualTo("my_comment");

 

1 // Test 2 (same setUp)
2 subject.process("addComment eventId my_comment");
3  
4 assertThat(db.getComments("eventId")).containsOnly("my_comment");

The first test, while testing the addComment command, uses another command – getComments – to check the resulting state. It uses only a single API entry point – subject – during the whole test. The second test accesses directly the underlying database instance and its API to get the same data, i.e. aside of subject it uses also the underlying db.

Thus the first test is not truly “unit” test as it depends on the correctness of another method of the tested class. The second test is much more focused and potentially simpler to write as it accesses directly the target data structure and thus performs the checks right at the source.

We would argue that tests like the first one, which perform all operations at the same level, namely the level of the public API of the object under test, are better. “Better” here means easier to understand and, more importantly, much more stable and maintainable because they are not coupled to the internal implementation of the functionality being tested. The price of increased complexity of these unit-integration tests (due to relying on multiple methods in each test) is absolutely worth the gain.

Tests similar to the second one are none the less more common, either accessing directly the underlying layers (an object, property, database, …) or using mocks to gain the possibility of direct verification of side-effects. These techniques often lead to coupled and hard to maintain tests and should be limited to the “private unit tests,” as described and argued in Never Mix Public and Private Unit Tests!

4. Focus!

  • Put tasks that pop up on a Later list instead of doing them at once
  • Focus on fixing the test first – however ugly and simple (and refactor later)
  • Focus on the current needs – no premature abstraction

One thing that really caught our attention is Kent’s focus on what he is doing at any moment. Being focused means concentrating on finishing that one thing you’re currently doing without getting distracted by other concerns, however important or simple to fix. (Side note: Never say never.) When having a failing test, focus on making it pass quickly, no matter how ugly the (temporary) solution is or that it “cuts corners.” If you notice along the way something else that needs to be done – giving a method a better name, removing a dead code, fixing an unrelated bug – don’t do it, put it on a task list and do it later. Otherwise you risk losing your attention and the current context. Do one thing at a time. When making a test pass, focus just on that, and leave concerns such as good code til the subsequent refactoring (which should follow shortly). (This reminds me of the Mikado method for large-scale refactorings, whose main purpose is also to keep focus and not getting lost in many sidetracks.)

A related practice is to focus on the current needs when implementing a feature, without speculatively designing for tomorrow’s needs (possibly literally tomorrow). Focus on what is needed right now, to finish the current task, and make the solution simple so that it will be easy to refactor and extend for both known and unforseen future needs. As Kent argues in Implementation Patterns (and others elsewhere), we’re very bad at speculative design, i.e. the future needs are usually quite different from what we expected and therefore it’s better to create solutions that are simple and with that also flexible. You of course need to pay some attention to the future needs but far less than we tend to do. Admit to yourself that you cannot predict the future. Even if you know what else is going to be required, how can you know that no new requirements that would change or delay that (up til infinity) will appear?

Some other stuff we learned

Parallel Design

Parallel design means that when changing a design, you keep the old design as long as possible while gradually adding the new one and then you gradually switching to the new design. This applies both at large and also (surprisingly) small scale. Though it’s costly – you have to figure out how to have them both run and it requires more effort to have them both – it often pays off because it’s safer and it enables resumable refactoring, discussed below.

An example of a high-level parallel design is the replacement of a RDBMS with a NoSQL database. You’d start by implementing the code for writing into the new DB, then you would use it and write both to the old and the new one, then you would start also reading from the new one (perhaps comparing the results to the old code to verify their correctness) while still using the old DB’s data. Next you would start actually using the NoSQL DB’s data, while still writing to/reading from the old DB (so that you could easily switch back). Only when the new DB proves itself would you gradually remove the old DB.

An example of a micro-level parallel design is the replacement of method parameters (message etc.) with the object they come from (an Edge), as we did for notifyComment:

1 - public void notifyComment(String message, String eventName, String user) {
2 -    notifications.add(user + ": commented on " + eventName + " " + message);
3 ---
4 + public void notifyComment(Edge target) {
5 +    notifications.add(target.getTo().getId() + ": commented on " + target.getFrom().getId() + " " + target.get("comment"));

The steps were:

  1. Adding the Edge as another parameter (Refactor – Change Method Signature)
  2. Replacing one by one usages of the original parameters with properties of the target Edge (Infinitest running tests automatically after each change to verify we’re still good)
  3. Finally removing all the original parameters (Refactor – Change Method Signature)

The good thing is that your code always works and you can commit or stop at any time.

Resumable Refactoring

If you apply the practices described below when performing a larger-scale refactoring then your code will always be buildable and you will be able to stop in the middle of the refactoring and continue (or not) at any later time.

The practices are parallel design and going forward in small, safe steps i.e. steps that provably do not break anything. In essence it’s about keeping the oversight and control, at each step you know exactly what you did which broke the test and this way you can not only quickly put the application back in a working state, but also quickly hone in on what exactly caused the problem.

(The Mikado method mentioned above is a great guide for refactoring systems where every change reveals a number of other changes required to make it possible. Of course the ultimate resource for refactoring legacy systems is Michael Feathers’s Working Effectively with Legacy Code).

Refactor on Green, at Will

The dogmatic TDD practitioners claim that you cannot change the behavior of production code unless some test forces you to do so. Thus it might be refreshing to hear that Kent doesn’t hesitate to generalize the code (e.g. by replacing fakes with a real implementation) even though there are no tests that require the generalization to pass.

On the other hand it doesn’t mean that forcing a generalization by tests is a bad thing or that you should not do it. This is basically a question of the economics of software development, of balancing the cost (of writing and maintaining tests) with the benefits (defect and regression prevention). It’s a question of the risk involved and of your confidence in your coding skills. Kent has rightfully much more confidence in his coding skills (and much more experience with it) than many of us. Our confidence is quite low based on past experiences and therefore we’ll probably go on enforcing generalizations with tests.

We’d close this topic by quoting Kent speaking about how much testing to do:

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it. I do tend to make sense of test errors, so I’m extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong.

Different people will have different testing strategies based on this philosophy, but that seems reasonable to me given the immature state of understanding of how tests can best fit into the inner loop of coding. Ten or twenty years from now we’ll likely have a more universal theory of which tests to write, which tests not to write, and how to tell the difference. In the meantime, experimentation seems in order.

Symmetry in the Code

Symmetry is an abstract concept, more specific than the values of communication, simplicity, and flexibility, but still rather general. In Implementation Patterns Kent refers to symmetry as a programming principle.

Code with symmetries is easier to grasp than code that is asymmetric. It’s easier to read and understand. So what, more specifically, is symmetric code? To quote Kent again:

Symmetry in code is where the same idea is expressed the same way everywhere it appears in the code.

Imagine a code where the some idea, like “getting the last updated document from the DB,” is implemented several times. The code is asymmetric if the method names differ, if they do things in different order, if there are some important differences between them. When you ask yourself “what does this method do” and you arrive at pretty much the same answer for all methods in spite of all the differences, then you have some violation of symmetry. An example of symmetry in code is keeping the abstraction level consistent within a code block, like a method. if the block is a mix of low level assignments and method calls, you may want to see if you can abstract away the assignments with a method. The astute reader have probably noticed that consistency is a large part of symmetry: being consistent with abstraction levels, consistent with method naming, and so on. But symmetry is more abstract in that it deals more with ideas, not rules (such as the rule that class and method names should be in camel-case).

And What Do you Know, Even Some More …

  • Manage your energy – be aware of your energy and stop before becoming tired. Don’t forget to take breaks. A rested developer is multiple times more productive than a tired one. (J.B. Rainsberger in The Economics of Software Design shares the story of working so intensively that he became exhausted and totally unproductive).
  • Pair-programming is a skill one must consciously learn (and it may be more challenging for some personality types, which shall to be respected)
  • Prefer IDE’s refactorings to manual changes – f.ex. none of us had ever before used the “inline” refactoring while Kent uses it all the time. Once you master the refactorings, they’ll become much more efficient than changing things manually and, more importantly, they avoid the small but non-zero probability of breaking something (remember that Murphy guy who said – what can break will break)

Code

You can find code for Iterate Code Camp 2012 on GitHub – bit.ly/codecamp2012

Conclusion

We hope that you, our dear reader, find some of these ideas interesting and have got inspired to try them in your daily practice, as we did.

Related Resources

  • Jakub’s blog post Principles for Creating Maintainable and Evolvable Tests summarizes some complementary principles for writing tests that he learnt from Kent
  • Rich Hickey: Simple Made Easy – a great talk that explains the crucial difference between “simple” (vs. complex) and “easy” and how our languages and tools aren’t as simple as they should be, often because they try to be easy

- Krzysztof, Stig, and Jakub, June 2012 -



کلاه قرمزی

clock September 14, 2012 21:33 by author Administrator



links

clock September 12, 2012 14:05 by author Administrator

Common sense and Code Quality

Resource Bundle Tricks and Best Practices

Common sense and Code Quality

 

Computer Programming Is Still an Art 

Understanding and Explaining “Iterative Development”

 



captcha

clock September 11, 2012 21:22 by author Administrator

 C ompletely A utomated P ublic T est to tell C omputers and H umans A part



JAVA INTERVIEW QUESTIONS PAGE :D

clock September 3, 2012 22:35 by author Administrator

1. What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults

2. What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.

Differences are as follows:

* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

* Neither Abstract classes or Interface can be instantiated.

How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:

abstract class testAbstractClass { 
    protected String myString; 
    public String getMyString() { 
    return myString; 

public abstract string anyAbstractFunction();
}

How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:

public interface sampleInterface {
    public void functionOne();
    public long CONSTANT_ONE = 1000;
}

3. Question: How you can force the garbage collection?

Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

4. What's the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

5. Can you call one constructor from another if a class has multiple constructors

Yes. Use this() to call a constructor from an other constructor.

6. Explain the usage of Java packages.

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

7. Explain in your own words the "bottom line" benefits of the use of an interface.

The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.

8. What are some advantages and disadvantages of Java Sockets?

Some advantages of Java Sockets: 
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network   Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

9. Explain the usage of the keyword transient?

Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

10. What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

11. What would you use to compare two String variables - the operator == or the method equals()?

I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

12. Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

13. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package access level.

14. Can an inner class declared inside of a method access local variables of this method?

It's possible if these variables are final.

15. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}

A single ampersand here would lead to a NullPointerException.

16. What's the main difference between a Vector and an ArrayList?

Java Vector class is internally synchronized and ArrayList is not synchronized.

17. Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean  - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

18. How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

19. How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;

20. When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

21. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

22. What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

23. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

24. Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

25. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

ArrayList

26. When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

27. How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

28. What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
    // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
    // Synchronized code here.
  }
}

29. What's the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

30. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

31. If you're overriding the method equals() of an object, which other method you might also consider?

hashCode()

32. What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

33. How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().

34. How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

35. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

36. Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 

37. Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. 

38. Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods". 
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

* Method overloading
* Method overriding through inheritance
* Method overriding through the Java interface

39. Is Iterator a Class or Interface? What is its use?

Iterator is an interface which is used to step through the elements of a Collection. 

40. Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:

class myCustomException extends Exception {
     / The class simply has to exist to be an exception
}


41. What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. 

39.  Read the following program:

public class test {
public static void main(String [] args) {
    int x = 3;
    int y = 1;
    if (x = y)
        System.out.println("Not equal");
   else
        System.out.println("Equal");
  }
}

What is the result?
The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

# Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

# Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}



JOB INTERVIEW QUESTIONNAIRE

clock September 3, 2012 22:30 by author Administrator

General Questions:

  • Are you on Twitter?
    • If so, who do you follow on Twitter?
  • Are you on Github?
    • If so, what are some examples of repos you follow
  • What blogs do you follow?
  • What version control systems have you used?
  • What is your preferred development enviroment? (OS, Editor, Browsers, Tools etc.)
  • Can you describe your workflow when you create a web page?
  • Can you describe the difference between progressive enhancement and graceful degradation?
    • Bonus points for the answer “no one can”
    • Extra bonus points for describing feature detection
  • Explain what “Semantic HTML” means.
  • What does “minification” do?
  • Why is it better to serve site assets from multiple domains? 
    • How many resources will a browser download from a given domain at a time?
  • If you have 8 different stylesheets for a given design, how would you integrate them into the site?
    • Looking for file concatenation.
    • Points off for @import, unless it works in conjunction with a build system.
  • If you jumped on a project and they used tabs and you used spaces, what would you do?
    • issue :retab! command
  • Write a simple slideshow page
    • Bonus points if it does not use JS.
  • What tools do you use to test your code’s performance?
  • If you could master one technology this year, what would it be?
  • Name 3 ways to decrease page load. (perceived or actual load time)
  • Explain the importance of standards.

HTML-Specific Questions:

  • What’s a doctype do, and how many can you name?
  • What’s the difference between standards mode and quirks mode?
  • What are the limitations when serving XHTML pages?
    • Are there any problems with serving pages as application/xhtml+xml?
  • How do you serve a page with content in multiple languages?
  • Can you use XHTML syntax in HTML5? How do you use XML in HTML5?
  • What are data- attributes good for?
  • What are the content models in HTML4 and are they different in HTML5?
  • Consider HTML5 as an open web platform. What are the building blocks of HTML5?
  • Describe the difference between cookies, sessionStorage and localStorage.

JS-Specific Questions

  • Which JavaScript libraries have you used?
  • How is JavaScript different from Java?
  • What are undefined and undeclared variables?
  • What is a closure, and how/why would you use one?
    • Your favorite pattern used to create them? argyle (Only applicable to IIFEs)
  • What’s a typical use case for anonymous functions?
  • Explain the “JavaScript module pattern” and when you’d use it.
    • Bonus points for mentioning clean namespacing.
    • What if your modules are namespace-less?
  • how do you organize your code? (module pattern, classical inheritance?)
  • What’s the difference between host objects and native objects?
  • Difference between:
    function Person(){}
    var person = Person()
    var person = new Person()
  • What’s the difference between .call and .apply?
  • explain Function.prototype.bind?
  • When do you optimize your code?
  • Can you explain how inheritance works in JavaScript?
    • Bonus points for the funny answer: “no one can”
    • Extra bonus points if they take a stab at explaining it
  • When would you use document.write()?
    • Correct answer: 1999 – time to weed out the junior devs
  • What’s the difference between feature detection, feature inference, and using the UA string
  • Explain AJAX in as much detail as possible
  • Explain how JSONP works (and how it’s not really AJAX)
  • Have you ever used JavaScript templating, and if so, what/how?
  • Explain “hoisting”.
  • What is FOUC? How do you avoid FOUC?
  • Describe event bubbling.
  • What’s the difference between an “attribute” and a “property”?
  • Why is extending built in JavaScript objects not a good idea?
  • Why is extending built ins a good idea?
  • Difference between document load event and document ready event?
  • What is the difference between == and ===?
  • Explain how you would get a query string parameter from the browser window’s URL.
  • Explain the same-origin policy with regards to JavaScript.
  • Explain event delegation.
  • Describe inheritance patterns in JavaScript.
  • Make this work: 
    [1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]
  • Describe a strategy for memoization in JavaScript.
  • Why is it called a Ternary statement, what does the word “Ternary” indicate?
  • What is the arity of a function?

JS-Code Examples:

~~3.14

Question: What value is returned from the above statement?
Answer: 3

"i'm a lasagna hog".split("").reverse().join("");

Question: What value is returned from the above statement?
Answer: “goh angasal a m’i”

( window.foo || ( window.foo = "bar" ) );

Question: What is the value of window.foo?
Answer: “bar”

var foo = "Hello";
(function() { 
  var bar = " World"
  alert(foo + bar); 
})(); 
alert(foo + bar);

Question: What is the outcome of the two alerts above?
Answer: ”Hello World” & ReferenceError: bar is not defined

jQuery-Specific Questions:

  • Explain “chaining”.
  • What does .end() do?
  • How, and why, would you namespace a bound event handler?
  • What is the effects (or fx) queue?
  • What is the difference between .get(), [], and .eq()?
  • What is the difference between .bind(), .live(), and .delegate()?
  • What is the difference between $ and $.fn? Or just what is $.fn.
  • Optimize this selector:
    $(".foo div#bar:eq(0)")

CSS-Specific Questions:

  • Describe what a “reset” CSS file does and how it’s useful.
  • Describe Floats and how they work.
  • What are the various clearing techniques and which is appropriate for what context?
  • Explain CSS sprites, and how you would implement them on a page or site.
  • What are the differences between the IE box model and the W3C box model?
  • What are your favourite image replacement techniques and which do you use when?
  • CSS property hacks, conditionally included .css files, or… something else?
  • How do you serve your pages for feature-constrained browsers?
    • What techniques/processes do you use?
  • What are the different ways to visually hide content (and make it available only for screenreaders)?
  • Have you ever used a grid system, and if so, what do you prefer?
  • Hav you used or implement media queries or mobile specific layouts/CSS? 
  • Any familiarity with styling SVG?
  • How do you optimize your webpages for print?
  • What are some of the “gotchas” for writing efficient CSS?
  • Do you use LESS?
  • How would you implement a web design comp that uses non-standard fonts? (avoid mentioning webfonts so they can figure it out)
  • Explain how a browser determines what elements match a CSS selector?

Optional fun Questions:

  • What’s the coolest thing you’ve ever coded, what are you most proud of?
  • Do you know the HTML5 gang sign?
  • Are you now, or have you ever been, on a boat.
  • Tell me your favorite parts about Firebug / Webkit Inspector.
  • Do you have any pet projects? What kind?
  • Explain the significance of “cornify”.
  • On a piece of paper, write down the letters A B C D E vertically. Now put these in descending order without writing one line of code.
    • Wait and see if they turn the paper upside down
    • This should make the laugh and is a fine way to relieve some tension at the end of the interview.
  • Pirate or Ninja?
    • bonus if it’s a combo and a good reason was given (+2 for zombie monkey pirate ninjas)
    • If not Web Development what would you be doing?
    • Where in the world is Carmen Sandiego?
      • (hint: their answer is always wrong)
    • What’s your favorite feature of Internet Explorer?


20 +2 Subjects Every Software Engineer Should Know … and the books you need

clock September 3, 2012 22:07 by author Administrator

I recently read an extremely interesting and useful article about the 20 subjects that every software engineer should know or learn….
What is really cool is that it’s not restricted to products, languages but it describes generally accpepted technologies, methodologies and practices.
It applies both to  junior and exeperienced software engineers. The former have a guideline about the fields that need to focus whereas the latter have the chance to re-evaluate their knowledge.
What’s missing, IMHO, is to give the reader a clue about which are the best book(s) related to these subjects so in this post I give my advices on that. Of course the list of books is not complete and it’s just my opinion based on my experience.

Hope you find it useful as well!

1. Object oriented analysis & design

2. Software quality factors

3. Data structures & algorithms: Basic data structures like array, list, stack, tree, map, set etc. and useful algorithms are vital for software development. Their logical structure should be known.
 
6. Software processes and metrics
8. Operating systems basics
10. Network basics
 
13. Dependency management
15. ORM (Object relational mapping)
 
18. Internationalization (i18n)
 
19. Architectural patterns
20. Writing clean code

21. Web Services

22. XML 



open source platform measuring software quality

clock September 3, 2012 22:00 by author Administrator

Sonar (by SonarSource.com) is getting more and more popular among developer teams. It’s an open source platform measuring software quality in the following 7 axes

  1. Architecture and Design 
  2. Comments 
  3. Coding Rules 
  4. Complexity 
  5. Code Duplication 
  6. Potential Bugs 
  7. Unit Tests 

If you’re a Sonar newbie then you might find this blog post very useful. On the other hand if you’re an experienced user then you can refresh your memory and what you’ve learned so far. Sonar’s Alphabet is not a user manual. It’s a reference to help you learn (and teach others) some basic terms and words used in the world of Sonar.

  • A for Analysis : Sonar’s basic feature is the ability to analyse source with various ways (Maven, Ant, Sonar runner, trigger by CI system ) . You can have static and/or dynamic analysis if supported by the analyzed language. 
  • B for Blockers : These are violations of the highest severity. They are considered real (not potential bugs ) so fix them as soon as possible 
  • C for Continuous Inspection : Continuous Inspection requires a tool to automate data collection, to report on measures and to highlight hot spots and defects and yes, Sonar is currently the leading “all-in-one” Continuous Inspection engine. 
  • D for Differential Views : Sonar’s star feature let you compare a snapshot analysis with a previous analysis. Fully customizable and dynamic makes continuous inspection a piece of cake. 
  • E for Eclipse. If you’re an Eclipse fan then did you know that you can have most of Sonar’s features in your IDE without leaving it. If not then you should give a try the Sonar’s Eclipse plugin. 
  • F for Filters : Filters are used to specify conditions and criteria on which projects are displayed. They can be used in dashboards or in widgets that require a filter. 
  • G for Global Dashboards : Global dashboards are available at instance level and can be accessed through the menu on the left. One of those global dashboards is set as your home page.Any widget can be added to a global dashboard. Thus, any kinds of information from a project or from the Sonar instance can be displayed at will. 
  • H for Historical Information : Knowing the quality level of your source code in a specific time instance is not enough. You need to be able to compare it with previous analysis. Sonar keeps historical information that can be viewed with many ways such as Timeline widget, Historical table widget or metric tendencies. 
  •  I for Internationalization : Sonar (and some of the open source plugins) supports internationalization. It’s available in 7 languages. 
  • J for Jenkins : Although jenkins is not a term of Sonar, you’ll read it in many posts and articles. A best practice to run Sonar analysis and to achieve Continuous Inspection is to automate it by using a CI server. Sonar folks have created a very simple, still useful plugin, that integrates Sonar with Jenkins 
  • K for Key : If you want to dive in Sonar’s technical details or write your own plugin then don’t forget that most of core concepts are identified by a key ( project key, metric key, coding rule key etc. ) 
  • L for Languages : Sonar was initially designed to analyze Java source code. Today, more than 20 languages are supported by free or commercial plugins. 
  • M for Manual Measures : You can even define your own measures and set their values when automated calculation is not feasible ( such as team size, project budget etc. ) 
  • N for Notifications : Let Sonar sends you an email when Changes in review assigned to you or created by you New violations on your favorite projects introduced during the first differential view period. 
  • O for Opensource : Sonar core as well as most of the plugins are available in CodeHaus or GitHub. 
  • P for plugins. More than 50 Sonar plugins are available for a variety of topics. New languages, reporting, integration with other systems and many more. The best way to Install / update them through the Update Center. 
  • Q for Quality Profiles. Sonar comes with default Quality profiles. For each language you can create your own profiles or edit the existing ones to adjust sonar analysis according to your demands. For each quality profile you activate/deactivate rules from the most popular tools such as PMD, FindBugs, Checkstyle and of course rules directly created by Sonar guys. 
  • R for Reviews : Code Reviews made easy with Sonar. You can assign reviews directly to Sonar users and associate them with a violation. Create action plans to group them and track their progress from analysis to analysis. 
  • S for Sonar in Action book. The only Sonar book that covers all aspects of Sonar. For beginners to advanced users even for developers that want to write their own plugins. 
  • T for Testing : Sonar provides many test metrics such as line coverage, branch coverage and code coverage. It’s integrated with most popular coverage tools (jacoco, emma, cobertura, clover). It can show also metrics on integration tests and by installing opensource plugins you can integrate it with other test frameworks ( JMeter, Thucycides, GreenPepper etc.) 
  • U for User mailing list. Being an active member of this list I can assure you that you can get answers for all your issues and problems. 
  • V for Violations : A very popular term in Sonar. When a source code file (tests files apply also) doesn't comply with a coding rule then Sonar creates a violation about it. 
  • W for Widgets : Everything you see in a dashboard is a widget. Some of them are only available only for global dashboards. You can add as many as you want in a dashboard and customize them to fit your needs. There are many Sonar core widgets and usually plugins may offer some additional widgets. 
  • X for X-ray : You can consider Sonar as your x-rays glasses to actually see IN your code. Nothing is hidden anymore and everything is measured. 
  • Y for Yesterday’s comparison : One of the most common differential views usages is to compare the current analysis snapshot with the analysis triggered yesterday. Very useful if you don’t want to add up your technical debt and handle it only at the end of each development cycle. 
  • Z for Zero values : For many Sonar metrics such as code duplication, critical/blocker violations, package cycles your purpose should be to minimize or nullify them that means seeing a lot of Zero values in your dashboard.

When I was trying to create this alphabet in some cases/letters I was really in big dilemma which word/term to cover. For instance the Sonar runner, which is not mentioned above, is the proposed and standard way to analyze any project with Sonar regardless the programming language.

If you think that an important Sonar term is missing feel free to comment and I’ll adjust the text.



before check in the code

clock September 1, 2012 22:16 by author Administrator

Before checking in the code, each developer should make sure that:
1. Should have a Unit/Integration Test for the change/new feature
2. Run Code Quality Checking tools(FindBugs/PMD/Sonar) on the changed code
3. The changes should comply with the existing architecture/design of the application.



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In