Tuesday, September 30, 2014

PragProg - Communicate

Ref: The Pragmatic Programmer

Having the best ideas, the finest code, or the most pragmatic thinking is ultimately sterile unless you can communicate with other people. A good idea is an orphan without effective communication.



Know What You Want to Say

Plan what you want to say. Write an outline. Then ask yourself. "Does this get across whatever I'm trying to say?". Refine it until it does.

Know Your Audience

You're communicating only if you're conveying information. To do that, you need to understand the needs, interests, and capabilities of your audience.
  • What do you want them to learn?
  • What is their interest in what you've got to say?
  • How sophisticated are they?
  • How much detail do they want?
  • Whom do you want to own the information?
  • How can you motivate them to listen to you?

Choose Your Moment

Sometimes all it takes is the simple question, "Is this a good time to talk about...?"

Choose a Style

Some people want a formal "just the facts" briefing. Others like a long, wide-ranging chat before getting down to business.

Make It Look Good

Your ideas are important. They deserve a good-looking vehicle to convey them to your audience.

Involve Your Audience

If possible, involve your readers with early drafts of your document. Get their feedback and pick their brains.

Be a Listener

There's one technique that you must use if you want people to listen to you: listen to them.
Encourage people to talk by asking questions, or have them summarize what you tell them. Turn the meeting into a dialog, and you'll make your point more effectively. Who know, you might even learn something.

Get Back to People

If you ask someone a question, you feel they're impolite if they don't respond. Always respond to e-mails, even if the response is simply "I'll get back to you later". Keeping people informed makes them far more forgiving of the occasional slip, and makes them feel that you haven't forgotten them.

TIP 10: It's Both What You Say and the Way You Say It.

 Unless you work in a vacuum, you need to be able to communicate. The more effective that communication, the more influential you become.

PragProg - Knowledge Portfolio

Ref: The Pragmatic Programmer

An investment in knowledge always pays the best interest. Benjamin Franklin

Your knowledge and experience are your most important professional assets.
Unfortunately, they are expiring assets. Tyour kowledge becomes out of date as new techniques, languages, and environments are developed.
As the value of your knowledge declines, so does your value to your company or client. We want to prevent this from ever happening.
Managing a knowledge portfolio is very similar to managing a financial portfolio:
  1. Serious investors invest regularly - as a habit.
  2. Diversification is the key to long-term success.
  3. Smart investors balance their porfolios between conservative and high-risk, high-reward investments.
  4. Investors try to buy low and sell high for max return.
  5. Portfolios should be reviewed and rebalanced periodically.


Building Your Portfolio 

  • Invest regularly. Even if it's just a small amount 
  • Divesify. The more different things you know, the more valuable you are. As a baseline, you need to know the ins and outs of the particular technology you are working with currently. The more technologies you are comfortable with, the better you will be able to adjust the change.
  • Manage risk. It's not a good idea to invest all of your money in high-risk stocks that might collapse suddenly. Don't put all your technical eggs in one basket

TIP 8: Invest Regularly in Your Knowledge Portfolio



  • Learn at least one new language every year
  • Read a technical book each quarter
  • Read nontechnical books, too
  • Take classes

Sunday, September 28, 2014

PragProg - Good Enough Software

Ref: The Pragmatic Programmer

There's an old(ish) joke about a U.S. company that places an order for 100,000 integrated circuits with a Japanese manufacturer. Part of the specification was the defect rate: one chip in 10,000. A few weeks later the order arrived: one large box containing thousands of ICs, and a small one containing just ten. Attached to the small box was a label that read: "These are the faulty ones."

Involve Your Users in the Trade-Off

The scope and quality of the system you produce should be specified as part of that system's requirements.

TIP 7: Make Quality a Requirements Issue

Often you'll be in situations where trade-offs are involved. Surprisingly, many users would rather use software with some rough edges today than wait a year for the multimedia version. Great software today is often preferable to perfect software tomorrow. If you give your users something to play with early, their feedback will often lead you to a better eventual solution. 

Know When to Stop

In some ways, programming is like painting. You start with a blank canvas and certain basic raw materials. You use a combination of science, art, and craft to determine what to do with them. You sketch out an overall shape, paint the underlying environment, then fill in the details. You constantly step back with a critical eye to view what you've done. Every now and then you'll throw a canvas away and start again.

But artists will tell you that all the hard work is ruined if you don't know when to stop. If you add layer upon layer, detail over detail, the painting becomes lost in the paint.

Don't spoil a perfectly good program by over-embellishment and over-refinement. Move on, and let your code stand in its own right for a while. It may not be perfect. Don't worry: it could never be perfect

PragProg - Stone Soup and Boiled Frogs

Ref: The Pragmatic Programmer
Read "Stone Soup" story to see how strangers be catalyst and convince local villagers to share their resources. 

TIP 5: Be a Catalys for Change

The Villagers' Side

The stone soup story is also about gentle and gradual deception. Don't be like a boiled frog. Keep an eye on the big picture. Constantly review what's happening around you, not just what you personally are doing.

TIP 6: Remember the Big Picture

PragProg - Software Entropy

Ref: The Pragmatic Programmer

Entropy is a term from physics that refers to the amount of disorder in a system. When disorder increases in software, programmers call it "software rot".

Consider a building with a few broken windows. If the windows are not repaired, the tendency is for vandals to break a few more windows. Eventually, they may even break into the building, and if it's unoccupied, perhaps become squatters or light fires inside.

TIP 4: Don't Live with Broken Windows

PragProg - The Cat Ate My Source Code

Ref: The Pragmatic Programmer

Don't blame someone or something else, or make up an excuse. Don't blame all the problems on a vendor, a programming language, management, or your coworkers. Any and all of these play a role, but it is up to you to provide solutions, not excuse.

TIP 3: Provide Options, Don't Make Lame Excuses.

Before you approach anyone to tell them why something can't be done, is late, or is broken, stop and listen to yourself. Talk to the rubber duck on your monitor, or the cat. Does your excuse sound reasonable, or stupid? How's it going to sound to your boss?

Instead of excuses, provide options. Don't say it can't be done; explain what can be done to salvage the situation.

Friday, September 26, 2014

PragProg - What Makes a Pragmatic Programmer

Ref: The Pragmatic Programmer

Each developer is unique, with individual strengths and weakness, preferencess and dislikes. Project manager / team leader should care about positioning each team member in appropriate part of project as much as possible where he/she can show his knowledge and performance better.

However, if you are a Pragmatic Programmer, you'll share many of the following characteristics
  • Early adopter/fast adapter. You have an instinct for technologies and techniques, and you love trying things out. When given something new, you can grasp it quicly and integrate it with the rest of your knowledge. Your confidence is bor of experience.
  • Inquisitive. You tend to ask questions. That's neat - how did you do that? Did you have problems with that library? What's this BeOS I've heard about? How are symbolic links implemented?
  • Critical thinker. You rarely take things as given without first getting the facts. When celleagues say "because that's the way it's done", or a vendor promises the solution to all your problems, you smell a challenge.
  • Realistic. You try to understand the underlying nature ofeach problem you face. This realism gives you a good feel for how diffucult things are, and how things will take.
  • Jack of all trades. You try hard to be familiar with a broad range of technologies and environments, and you work to keep abreast of new developments. Although your current job may require you to be a specialist, you will always be able to move on to new areas and new challenges.
TIP 1: Care About Your Craft 
There is no point in developing software unless you care about doing it well.

TIP 2: Think! About Your Work
Think about what you are doing while you are doing it.

About "The Pragmatic Programmer"

It is not just a book for programmers and software engineers, it is for any professional to be more productive in his/her career doing it pragmatically. If you know main principles of your professional, you do it eagerly. This book enlights and shows us these principles. Not only every programmer but most of technical professionals should read this book at least once, or better every beginning of new year to start it fresh and productive :).

EJ-72 Threads should not run if they aren't doing useful work

Ref: Effective Java by Joshua Bloch

Threads should not busy-wait, repeatedly checking a shared object waiting for something to happen. Busy-waiting greatly increases the load on the processor, reducing the amount of useful work that others can accomplish. An extreme example of what not to do, consider this perverse implementation of  CountDownLatch

EJ-69 CountDownLatch for thread barrier

Ref: Effective Java by Joshua Bloch 
Synchronizers are objects that eanble threads to wait for one another, allowing them to coordinate their activities. The most commonly used synchronizers are CountDownLatch and Semaphore.

Countdown latches are single-use barriers that allow one or more threads to wait for one or more other threads to do something. The sole constructor for CountDownLatch takes an int that is the number of times the countDown method must be invoked on the latch before all waiting threads are allowed to proceed.

Lets examine following delicious code, see numbered execution steps.

 For interval timing, always use System.nanoTime in preference to System.currentTimeMillis. System.nanoTime is both more accurate and more precise, and it is not affected by adjustments to the system's real-time clock.

Thursday, September 25, 2014

EJ-69 Prefer ConcurrentHashMap to HashTable and if synchronization is required to HashMap

Ref: Effective Java by Joshua Bloch

There are lots of resources about HashTable vs HashMap vs ConcurrentHashMap . The main point is around synchronization. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. On the other hand, if you need better performing synchronization, you should use ConcurrentHashMap. In this article, it is simply explained how ConcurrentHashMap performs better than HashTable.

List Of Greatest Programmers

EJ-68 Prefer executors and tasks to threads

Ref: Effective Java by Joshua Bloch

In release 1.5,  java.util.concurrent was added to the Java platform. This package contains an Executor Framework, which is a flexible interface-based task execution facility. Creatin a work queue and submitting a task is as easy as

Choosing  the executor service for a particular application can be tricky. Executors.newCachedThreadPool is generally good choise if you writing a small lightly loaded program, letting ExecutorService "does the right thing". But it is not a good choice for heavily loaded production servers, because this type of executor service creates a new thread whenever it does not find an idle one. So more task arrive, more threads will be created, which will only make matters worse. Therefore, in a heavily loaded production server, it is much better off using Executors.newFixedThreadPool.

There are two kinds of tasks: Runnable and its close cousing Callable (which is like Runnable except it returns a value).

The Executor Framework also has a replacement for java.util.Timer, which is ScheduledThreadPoolExecutor. While it is easier to use a timer, a scheduled thread pool executor is much more flexible. A timer uses only a single thread for task execution, which can hurt timing acuracy in the presence of long running tasks. If a timer's sole thread throws an uncaught exception, the timer ceases to operate. A scheduled thread pool executor supports multiple threads and recovers gracefully from tasks that throw unchecked exceptions.

Wednesday, September 24, 2014

EJ-65 Don't Ignore Exceptions

Ref: Effective Java by Joshua Bloch

I think, this is the most important advice related with exceptions, which might cause to put your hands around your head for hours while debugging a problem otherwise.

An empty catch block defeats the purpose of exception. Whenever you see an empty catch block, alarm bells should go off in your head. At the very least, the catch block should contain a comment explaining whit it is appropriate to ignore the exception.

Adblock Plus - An Add-On to Block Ads

Are you irritated with ads in beginning of or cluttered inside of youtube videos? Try that amazing firefox add-on: Adblock Plus. It is enough Kibariye Abla, no more you will bother me :)

EJ-61 Exception Chaining: Throw Exceptions Appropriate to the Abstraction

Ref: Effective Java by Joshua Bloch

It is disconcerting when a method throws an exception that has no appropriate connection to the task that it performs. Higher layers should catch lower-level exceptions and in their place, throw exceptions that can be explained in terms of the higher-level abstraction. This idiom is known as exception translation:

 A special form of exception translation called exception chaining is appropriate in cases where the lower-level exception might be helpful to someone debugging the problem that caused the higher-level exception.

EJ-60 Favor the use of standart exceptions

Ref: Effective Java by Joshua Bloch

One of the attributes that most strongly distinguishes expert programmers from less experienced ones is that experts strive for and usually achieve a high degree of code reuse. The Java platform libraries provide a basic set of unchecked exceptions that cover a large fraction of the exception-throwing needs of most APIs.

Reusing preexisting exceptions has several benefits.
  • makes your API easier to learn because it matches established conventions with which programmers are already familiar.
  • programs using your API are easier to read because they aren't cluttered with unfamiliar exceptions
Some of the more commonly used exception types are:
NullPointerException : Parameter value is null where prohibited
IllegalArgumentException : Non-null parameter value is inappropriate
IllegalStateException : Object state is inappropriate for method invocation
IndexOutOfBoundsException : Index parameter is out of range
UnsupportedOperationException : Object does not support the method

EJ-59 Avoid Unnecessary Use of Checked Exceptions

Ref: Effective Java by Joshua Bloch

Checked exceptions are a wonderful feature of the Java programming language. Unlike return codes, they force  the programmer to deal with exceptional conditions, greatly enhancing reliability. That said, overuse of checked exceptions can make an API far less pleasent to use. It places a nontrivial burden on the programmer.

The burden is justified if the exceptional condition can not be prevented by proper use of the API and the programmer using the API cantake some useful actions once confronted with the exception. Unless both of these conitionshold, an unchecked exception is more appropriate. As litmus test, ask yourself how the programmer will handle the exception, Is this the best that can be done?

How about this?

If the programmer using the API can do no better, an unchecked exception would be more appropriate.

Monday, September 22, 2014

EJ-58 Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

Ref: Effective Java by Joshua Bloch

The Java programming language provides three kind of throwables:
  • Checked Exceptions
  • Runtime Exceptions (Unchecked)
  • Errors
The cardinal rule in deciding whether to use a checked or an unchecked exception is this: use checked exceptions for conditions from which the caller can reasonably be expected to recover. By throwing a checked exception, you force the caller to handle the exception in a catch clause or to propagate it to out-ward.

Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations.

While the Java Language Specification does not require it, there is a strong convention that errors are reserved for use by the JVM to indicate resource deficiencies, invariant failures, or other conditions that make it impossible to continue execution. Given the almost universal acceptance of this convention, it's best not to implement any new Error subclass. Therefore, all of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly). See its subclasses from java doc to have an idea about conditions of RuntimeExceptions:

AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DataBindingException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, FileSystemAlreadyExistsException, FileSystemNotFoundException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, IllformedLocaleException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, ProviderNotFoundException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException, UndeclaredThrowableException, UnknownEntityException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException, WrongMethodTypeException
Here is subclasses of Error
AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError, LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError

EJ-57 Use Exceptions only for Exceptional Conditions

Ref: Effective Java by Joshua Bloch

When used to best advantage,exceptions can improve a program's readability, reliability, and maintainability. When used, inappropriately, they can have the opposite affect.

Exceptions, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow.

This principle also has implications for API design. A well-designed API must not force its clients to use exceptions for ordinary control flow.

EJ-55 Optimize Judiciously

Ref: Effective Java by Joshua Bloch

Strive to write good programs rather than fast ones. If a good program is not fast enough, its arhitecture will allow it to be optimized. Good programs embody the principle of information hiding: where possible, they localize design decisions within individiual modules, so individual decisions can be changed without affecting the remainder of the system.

Luckily, it is generally the case that good design is consistent with good performance. It is very bad idea to warp a design to achieve good performance.

Thursday, September 18, 2014

EJ-48 Avoid Float And Double If Exact Answers are Required

Ref: Effective Java by Joshua Bloch

The float and double types are designed primarily for scientifc and engineering calculations. They perform binary floating point arithmetic. The float and double types are particularly illsuited for monetary calculations. Following unit test illustrates the problem and the right way to solve this problem by using BigDecimal.

In summary, don't use float or double for any calculations that require an exact answer. Use BigDecimal if you want the system to keep track of the decimalpoint and you don't mind the inconvenience and cost of not using a pritimitive type.

EJ-47 Know and Use The Libraries

Ref: Effective Java by Joshua Bloch

By using a standart library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you.
Every programmer should be familiar with the contents of
To summarize, don’t reinvent the wheel. If you need to do something that seems like it should be reasonably common, there may already be a class in the libraries that does what you want. If there is, use it; if you don’t know, check. Generally speaking, library code is likely to be better than code that you’d write yourself and is likely to improve over time.

EJ-45 Minimize the Scope of Local Variables

Ref: Effective Java by Joshua Bloch

This principle is similar in nature to "Minimize the accessibility of classes and members". By minimizing the scope of local variables, you increase the readibility and maintainability of your code and reduce the likelihood of error.

The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.

Lets demonstrate this principle with for and while loops which will show why to prefer for loops to while loops.

To see why these for loops are preferable to a while loop, consider the following code fragment, which contains two while loops and one copy-and-paste bug:

EJ-43 Return Empty Arrays or Collections, Not Nulls

Ref: Effective Java by Joshua Bloch

Commonly, there is no reason to return null from an array or collection returned method which would require extra null check instead of returning empty array or collections. 

Sunday, September 07, 2014

EJ-42 Use Varargs Judiciously

Ref: Effective Java by Joshua Bloch

A simple use of varargs:

The WRONG way to use varargs to pass one or more arguments

The right way to use varargs to pass one or more arguments

EJ-41 Use Overloading Judiciously

Ref: Effective Java by Joshua Bloch

A safe conservative policy is never to export two overladings with the same number of parameters.
For example, consider the class ObjectOutputStream. It has a variant of its write method for every primitive type and for several reference types. Rather than overloading the write method, these variants have signature like writeBoolean(boolean), writeInt(int), writeLong(long) etc. An added benefit of this naming pattern, when compared to overloading, is that it is possible to provided read methods with correspoing names, for example readBoolean(), readInt().

For constructors, you don't have the option of using different names: multiple constructors for a class are always overloaded. You do, in many cases,have the option of exporting static factories instead of constructors.

EJ-40 Design Method Signatures Carefully

Ref: Effective Java by Joshua Bloch

Considering following disciplines will help make your API easier to learn and use and less prone to errors.
  • Choose method names carefully.
  • Don't go overboard in providing convenience methods: Every method should "pull its weight." Too many methods make a class difficult to learn, use, document, test and maintain.
  • Avoid long parameter list: Aim for four parameters or fewer. Long sequences of identically typed parameters are especially harmful.
  • Prefer two-element enum types to boolean parameters: It makes your code easier to read and to write.
public enum TemperatureScale {FAHRENHEIT, CELCIUS }

Not only does Thermometer.newInstance(TemperatureScale.CELCIUS) make a lot more sence than Thermometer.newInstance(true) but you can add KELVIN to in a future release without adding a new static factory method.