Friday, February 28, 2014

Immutable

immutable
Not changeable. All Java variables are by default mutable. An Object is immutable if there is no way you can change its fields after it has been constructed. Tools for creating making objects of a class immutable:
Using the final keyword.
Make variables private and provide no public accessors to the outside world to change them.
The wrapper classes, Byte, Character, Short, Integer, Long, Float and Double are all immutable. Strings are immutable, though the references to them are mutable. StringBuffers are mutable. The only way to change the value of the number inside the object wrapper is to create a new object and point to that instead.
An object can be immutable even if some of its primitive fields are not. There must be no public fields and no public methods that let you change fields. The simplest tool to ensure immutability is to use the keyword final on all of the fields and initialise them all in the constructor. You must also ensure that any objects your immutable object points are in turn immutable. Normally you would declare references to all such objects final.
Advantages of Immutability
You can share immutable objects between threads without danger of changes confusing the other thread. You don’t need any locking. Two threads can both work on an immutable object at the same time without any possibility of conflict.
Once you check the value, you know it has to stay safe. No one can pass you a value, then behind your back swap it to an unsafe one using a background thread. This is particularly important in high security situations where allowing an invalid value to sneak in could compromise system integrity, e.g. a filename. This is probably the main reason that Strings are immutable.
You can share duplicates by pointing them to a single instance. You need only one copy, e.g. String interning. This saves RAM (Random Access Memory). With mutable StringBuilders that were temporarily identical, you could not throw one away, and replace it with a reference to the other, since at any moment their values could diverge again.
You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.
Immutable objects are much better suited to be Hashtable keys. If you change the value of an object that is used as a hash table key without removing it and re-adding it you lose the mapping.
Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
Returning an Immutable Result
Let us say you wanted to return some data from your method, but you did not want the user to muck with the original. Here are six approaches to the problem:
1. Wrap the reference in an immutable wrapper class and return that.
2. Give the caller his own private copy of the data he can muck with to his heart’s content. There is high CPU (Central Processing Unit) and RAM overhead in the array copying.
3. Beg or threaten the user not to modify the data in the reference you return to him.
4. Return an immutable interface to the original data. You can then change fields in the object, but the caller cannot unless he cheats by casting. You expose only the methods you want the user to have. Doing the same with classes is trickier since a subclass must expose everything its superclass does.
5. You can turn a Collection into an immutable Collection with methods like Collections.unmodifiableCollection, Collections. unmodifiableList, Collections.unmodifiableMap, Collections. unmodifiableSet, Collections. unmodifiableSortedMap or Collections. unmodifiableSortedSet.
6. You can return an Iterator with a dummy remove method.
Of course same techniques can be used if you want to pass an Object to a method and you don’t want the method messing with it. You declare the method with an interface parameter and pass it an interface reference or a reference to an object of some class implementing that interface.


http://mindprod.com/jgloss/immutable.html

Program to an Interface

“Program to an Interface” is basically a design principle. How to design the code so that  it will be easy to modify and maintain.
The very first time this principle was defined by GoF (Gang of Four) in their classic Book(Design Patterns) in 1995.
The GoF (Gang of Four) described a basic rule of reusable object-oriented design: "Program to an interface, not an implementation."
So what does “Program to an interface” really mean?
This principle is really about dependency relationships which have to be carefully managed in a large app. – Erich Gamma ( Co- author of the book “Design Pattern”)

“Program to an interface”, really means “Program to a supertype”.

If you don’t use an Interface you are programming to the implementation not the interface.
In other words you can say that you should focus not only on developing version one, but to also think about the following versions. This doesn't mean designing in future extensibility, but just keeping in mind that you have to maintain what you produce and try to keep the API stable for a long time.
:
So the point here is that you should be loosely coupling your classes in your application. When designing your systems you should always think about the interface (coupling) between your components and make sure they make sense. I firmly believe the best way to make a maintainable system is to create loose coupling and high cohesion as a wise man once taught me. But this can and is done in many languages, and at many shops without the need for the Java Interface.

Example  :
So what am I saying? I am saying if I showed you the following code:

public class BankDelegate {
   public void debit(Account account, Amount amount) {
      account.debit(amount);
   }
}

you would have no idea if account was an Interface, Abstract Class, or Concrete Class. And furthermore, I would suggest that it doesn’t matter. Let’s say my bank only has a single account type. This would work great. Now what happens when I need to add a second account type? I can either create a base class, that both my accounts extend from, or I can create an Interface. Either solution will work, and I don’t need to change the code in my delegate. Which means my interface has remained the same.
That is what it means to program to an interface. Because if I had originally wrote the BankDelegate class like this:

public class BankDelegate {
   public void debit(CheckingAccount account, Amount amount) {
      account.debit(amount);
   }
}

Then my interface is only good for classes that are of type CheckingAccount. So let’s apply the same logic as before. I could write this as an Interface, Abstract Class, or Concrete Class and you would have no idea based on the above code. But of course, had I written it as an Interface it would be loosely coupled, and therefore I would be able to change it extremely easy at a later time…Oh wait, errrrr…It doesn’t make sense for a SavingsAccount to extend Checking account. I need to add a new base class or interface of Account and extend that. It will take the same amount of work to change this to accept a SavingsAccount regardless of what notation I used to create the CheckingAccount type.
Because of that I would argue that programming to an interface is more about thinking about the names of your classes and methods than using a special notation to declare them.
Example 2:
Program to an interface means do not tie relationships to classes, instead tie them to interfaces. For example, I have a class C1 which is a parameter to method M2 in class C2. I code M2 method as follows :-
M2( C1 c )
I cannot use M2( C1 ) for processing any other class. Instead if an interface I1 is created and which is implemented by class C1, I can change the method signature to
M2( I1 i )
and this will be able to process objects of any class ( including C1 ) which implement this I1 interface.
Its desirable to always have classes implement interfaces and public methods of the class are always from interfaces ( this is mentioned in some Java coding standards on the net ), but this programming standard / guideline is not strictly followed in realtime projects.

http://www.artima.com/lejava/articles/designprinciples.html
http://www.fatagnus.com/program-to-an-interface-not-an-implementation/
http://www.coderanch.com/t/178299/java-SCJA/certification/describe-apply-program-interface-principle

Friday, February 14, 2014

Fault Exception

What If There's No Error Handling?

Suppose I write a WCF web service with no try-catch blocks and no error handling. What happens when my web service throws an exception? Since I don't have any error handling, WCF catches the exception for me. It sends the client (the program that called my web service) a FaultException with the following message:

"The server was unable to process the request due to an internal error."

Whenever there's an unhandled exception, that's all the information the client gets. WCF doesn't send the client the exception message or the stack trace or any of the other information that was contained in the exception.

There are a number of reasons why WCF does this. One reason is that the Exception class is specific to .Net. WCF was designed to make web services that can be called by anyone, including clients that are not written in .Net. The client program can be written in Java or PHP or a variety of other languages. So WCF doesn't assume that the clients were written in .Net, and it doesn't send them .Net specific responses.

Another reason WCF doesn't send the client more information is that this might not be safe. It's not safe to provide the stack trace to anyone that may call. Detailed error messages are also risky. For example, it's not safe to inform the caller that the database insert failed because user name "andrew.fenster" is already in use. The safer practice is to write this information to an error log and provide much less detailed error information to the caller.

Providing More Information With FaultExceptions

A bare FaultException may be safe, but it doesn't provide enough information. I may not want to pass the full stack trace, but I want to provide at least basic information about what went wrong. WCF provides multiple ways to do this.

The FaultException class itself includes several ways to provide more information. The FaultException class includes these constructors (among others):
public FaultException(string reason);
public FaultException(string reason, FaultCode code);
public FaultException(FaultReason reason);
public FaultException(FaultReason reason, FaultCode code);

The simplest way to provide information is the first of these:
try
{
    // do something
}
catch (Exception ex)
{
  myLogger.LogException(ex);
     throw new FaultException("Your request timed out. Please try again later.");
}

The client can capture the FaultException and read the message as follows:
try
{
     // call the web service
}
catch (FaultException ex)
{
     Console.WriteLine(ex.Message);
}

As you can see from the FaultException constructors, you can create a FaultException with a string, a FaultCode, a FaultReason or some combination of these.

The FaultReason class lets you provide the same error message in multiple languages. If you look at the list of FaultException constructors, you will see that you can either provide an error message in a string or a collection of error messages in a FaultReason. You don't need both.

A FaultCode allows you to provide a code (a string) to tell the client what went wrong. For example:
try
{
      // do something
}
catch (Exception ex)
{
  myLogger.LogException(ex);
     FaultCode code = new FaultCode("Invalid Operation");
     throw new FaultException("Customer name cannot be null.", code);
}
The client can catch the FaultException and read the FaultCode as follows:
try
{
     // call the web service
}
catch (FaultException ex)
{
     Console.WriteLine("FaultCode: " + ex.Code);
     Console.WriteLine("Message: " + ex.Message);
}
The FaultException class

The FaultException class gives you several ways to inform the client about what went wrong. Sometimes, however, you may want more.

The FaultException class is derived from the FaultException class. As with the FaultException class, you can pass in some combination of string, FaultCode and FaultReason. You can also pass in some additional value T. T can be a value or an entire class object. For example, you could define your own error class:
[DataContract]
public class ErrorMessage
{
      private Guid ticketNumber;
       [DataMember]
      public Guid TicketNumber
  {
           get { return ticketNumber; }
           set { ticketNumber = value; }
  }

      [DataMember]
      public string Message
  {
           get { return "An error has occurred. For more information,
                             call us and tell us your ticket number."; }
      }   public ErrorMessage(Guid newTicket)
  {
        ticketNumber = newTicket;
  }
}
You could use this as follows:
try
{
      // Do something
}
catch (Exception ex)
{
      Guid ticket = myLogger.LogException(ex);    
  ErrorMessage message = new ErrorMessage(ticket);
      throw new FaultException(message);
}
The client can catch this FaultException as follows:
try
{
      // call the web service
}
catch (FaultException ex)
{
      Guid ticket = ex.Detail.TicketNumber;
      string message = ex.Detail.Message;
}
Of course you could also throw in a FaultCode or a FaultReason, since FaultException is derived from FaultException. FaultException includes these constructors:
public FaultException(T detail);
public FaultException(T detail, string reason);
public FaultException(T detail, FaultReason reason);
public FaultException(T detail, string reason, FaultCode code);
public FaultException(T detail, FaultReason reason, FaultCode code);
When you use the FaultException class, T can be any type, provided in can be serialized. If you are going to use your own custom class, you should define a DataContract for your class, as shown above.

FaultContracts

If you are going to use the FaultException class, you need to create a FaultContract. The FaultContract tells the client program what type of Faults each method can throw. For example:

    [ServiceContract]
        interface IMyService
    {
        [OperationContract]
        [FaultContract(typeof(ErrorMessage))]
            int DoSomething();
    }

This FaultContract informs the client that when it calls DoSomething( ) it may receive a fault of type FaultException.

You can specify more than one fault type. For example:

    [ServiceContract]
        interface IMyService
    {
         [OperationContract]
          [FaultContract(typeof(ErrorMessage))]
         [FaultContract(typeof(Guid))]
             int DoSomething();
    }

Now my method can throw either FaultException or FaultException.

If a web service throws a FaultExeption of a type not declared in the ServiceContract, it will not reach the client. For example, if the ServiceContract says I will throw a FaultException, and my service instead throws a FaultException, WCF will block my fault. Instead, it will send the client a bare FaultException with the generic message "The server was unable to process the request due to an internal error." 

Best Practices

There are no shortage of people offering their own advice about error handling. I have only a few points to make.

First and most important, you should be very cautious about providing detailed information to the client about what went wrong. Most error details are either a security risk or simply irrelevant to the client. For example, the Stack Trace contains details about your code which should not be revealed. Even if the client is another division within your own company, they don't need you to send them the Stack Trace. If you sent them the Stack Trace, what would they do with it? Likewise, it's not a good idea to simply catch exceptions and pass the exception Message to the client.

There are only a few types of messages that the client may care about. For example, if the client did not provide a required field, informing the client might be useful. If the system is down temporarily, you could tell the client to try later. Error messages that reveal details about your code, however, don't help the client but do provide security risks.

Using an ErrorMessage class like the one shown above may be sufficient. The client is informed that something went wrong. It anyone needs more information, they can provide you with a ticket number, and you can look up the error in the error log.

One other suggestion: if you are going to provide any significant error information, it would be best to have a FaultContract. Even though the basic FaultException class allows you to pass a message and a FaultCode and a FaultReason (and a few other things not discussed in this article), it makes sense to forego these and use a FaultException, with all your error information inside the detail object T. That way the client knows exactly what to expect and doesn't try reading a value from the FaultReason when there's no FaultReason provided.

In conclusion, WCF provides you with a lot of options for error handling. As long as you think carefully about what information you are providing and the format in which you provide it, you should come out fine.

Followers

Link