Monday, 28 November 2011

Open Closed Principle

Open Closed Principle (OCP) states that,



Software entities (Classes, modules, functions) should be OPEN for EXTENSION, CLOSED for MODIFICATION.

Lets try to reflect on the above statement- software entities once written shouldn’t be modified to add new functionality, instead one has to extend the same to add new functionality.

In other words you don’t touch the existing modules thereby not disturbing the existing functionality, instead you extend the modules to implement the new requirement. So your code is less rigid and fragile and also extensible.



OCP term was coined by Bertnard Meyer.

How can we confirm to OCP principle?

Its simple - Allow the modules (classes) to depend on the abstractions, there by new features can be added by creating new extensions of these abstractions.

Let me try to explain with an example:

Suppose you are writing a module to approve personal loans and before doing that you want to validate the personal information, code wise we can depict the situation as:

public class LoanApprovalHandler
{
  public void approveLoan(PersonalValidator validator)
  {
    if ( validator.isValid())
    {
      //Process the loan.
    }
  }
}
public class PersonalLoanValidator
{
  public boolean isValid()
  {
    //Validation logic
  }
}

So far so good. As you all know the requirements are never the same and now its required to approve vehicle loans, consumer goods loans and what not. So one approach to solve this requirement is to:

public class LoanApprovalHandler
{
  public void approvePersonalLoan (PersonalLoanValidator validator)
  {
    if ( validator.isValid())
    {
      //Process the loan.
    }
  }
  public void approveVehicleLoan (VehicleLoanValidator validator )
  {
    if ( validator.isValid())
    {
      //Process the loan.
    }
  }
  // Method for approving other loans.
}
public class PersonalLoanValidator
{
  public boolean isValid()
  {
    //Validation logic
  }
}
public class VehicleLoanValidator
{
  public boolean isValid()
  {
    //Validation logic
  }
}

We have edited the existing class to accomodate the new requirements- in the process we ended up changing the name of the existing method and also adding new methods for different types of loan approval. This clearly violates the OCP. Lets try to implement the requirement in a different way:

/**
 * Abstract Validator class
 * Extended to add different
 * validators for different loan type
 */
public abstract class Validator
{
  public boolean isValid();
}
/**
 * Personal loan validator
 */
public class PersonalLoanValidator
  extends Validator
{
  public boolean isValid()
  {
    //Validation logic.
  }
}
/*
 * Similarly any new type of validation can
 * be accommodated by creating a new subclass
 * of Validator
 */

Now using the above validators we can write a LoanApprovalHandler to use the Validator abstraction.

public class LoanApprovalHandler
{
  public void approveLoan(Validator validator)
  {
    if ( validator.isValid())
    {
      //Process the loan.
    }
  }
}

So to accommodate any type of loan validators we would just have create a subclass of Validator and then pass it to the approveLoan method. That way the class is CLOSED for modification but OPEN for extension.

Another example:

I was thinking of another hypothetical situation where the use of OCP principle can be of use. The situation is some thing like: “We maintain a list of students with their marks, unique identification(uid) and also name. Then we provide an option to get the percentage in the form of uid-percentage name value pairs.”

class Student
{
  String name;
  double percentage;
  int uid;
  public Student(String name, double percentage, int uid)
  {
    this.name = name;
    this.percentage = percentage;
    this.uid = uid;
  }
}

We collect the student list into a generic class:

class StudentBatch {
  private List<Student> studentList;
  public StudentBatch() {
    studentList = new ArrayList<Student>();
  }
  public void getSutdentMarkMap(Hashtable<Integer, Double> studentMarkMap) {
    if (studentMarkMap == null) {
      //Error
    } else {
      for (Student student : studentList) {
        studentMarkMap.put(student.uid, student.percentage);
      }
    }
  }
  /**
   * @param studentList the studentList to set
   */
  public void setStudentList(List<Student> studentList) {
    this.studentList = studentList;
  }
}

Suppose we need to maintain the order of elements in the Map by their insertion order, so we would have to write a new method to get the map in the insertion order and for that we would be using LinkedHashMap. Instead if the method- getStudentMarkMap() was dependent on the Map interface and not the Hashtable concrete implementation, we could have avoided changing the StudentBatch class and instead pass in an instance of LinkedHashMap.

public void getSutdentMarkMap(Map<Integer, Double> studentMarkMap) {
    if (studentMarkMap == null) {
      //Error
    } else {
      for (Student student : studentList) {
        studentMarkMap.put(student.uid, student.percentage);
      }
    }
  }

PS: I know that Hashtable is an obsolete collection and not encouraged to be use. But I thought this would make another useful example for OCP principle.

Some ways to keep your code closer to confirming OCP:

Making all member variables private so that the other parts of the code access them via the methods (getters) and not directly.
Avoiding typecasts at runtime- This makes the code fragile and dependent on the classes under consideration, which means any new class might require editing the method to accommodate the cast for the new class.

Really good article written by Robert Martin on OCP.

Tuesday, 9 August 2011

Java Compilation Process

Java is "semi-interpreted" language and it differs from C/C++ and the process described above. What do we mean by "semi-interpreted" language? Java programs execute in the Java Virtual Machine (or JVM), which makes it an interpreted language. On the other hand Java unlike pure interpreted languages passes through an intermediate compilation step. Java code does not compile to native code that the operating system executes on the CPU, rather the result of Java program compilation is intermediate bytecode. This bytecode runs in the virtual machine. Let us take a look at the process through which the source code is turned into executable code and the execution of it.


Figure : The Java Compile/Execute Path
The Java Compile/Execute Path

Java requires each class to be placed in its own source file, named with the same name as the class name and added suffix .java. This basicaly forces any medium sized program to be split in several source files. When compiling source code, each class is placed in its own .class file that contains the bytecode. The java compiler differs from gcc/g++ in the fact that if the class you are compiling is dependent on a class that is not compiled or is modified since it was last compiled, it will compile those additional classes for you. It acts similarly to make, but is nowhere close to it. After compiling all source files, the result will be at least as much class files as the sources, which will combine to form your Java program. This is where the class loader comes into picture along with the bytecode verifier - two unique steps that distinguish Java from languages like C/C++.

The class loader is responsible for loading each class' bytecode. Java provides developers with the opportunity to write their own class loader, which gives developers great flexibility. One can write a loader that fetches the class from everywhere, even IRC DCC connection. Now let us look at the steps a loader takes to load a class.

When a class is needed by the JVM the loadClass(String name, boolean resolve); method is called passing the class name to be loaded. Once it finds the file that contains the bytecode for the class, it is read into memory and passed to the defineClass. If the class is not found by the loader, it can delegate the loading to a parent class loader or try to use findSystemClass to load the class from local filesystem. The Java Virtual Machine Specification is vague on the subject of when and how the ByteCode verifier is invoked, but by a simple test we can infer that the defineClass performs the bytecode verification. (FIXME maybe show the test). The verifier does four passes over the bytecode to make sure it is safe. After the class is successfully verified, its loading is completed and it is available for use by the runtime.

The nature of the Java bytecode allows people to easily decompile class files to source. In the case where default compilation is performed, even variable and method names are recovered. There are bunch of decompilers out there, but a free one that works well is Jad. FIXME: add a link. Because of this we will not discuss how to reverese engineer software written in Java.
               

Thursday, 7 April 2011

99 ways to make your computer blazingly fast.

Here are probably a lot of great tweaks and performance hacks that I’ve missed here, so feel free to chime in with comments! Enjoy!

1. Defragment your computer hard disk using free tools like SmartDefrag.

2. You should also defragment your Windows pagefile and registry.

3. Clean up hard drive disk space being taken up by temporary files, the recycle bin, hibernation and more. You can also use a tool like TreeSize to determine what is taking up space on your hard drive.

4. Load up Windows faster by using Startup Delayer, a free program that will speed up the boot time of Windows by delaying the startup of programs.

5. Speaking of startup programs, many of them are useless and can be turned off. Use the MSCONFIG utility to disable startup programs.

6. By default, the size of the paging file is controlled by Windows, which can cause defragmentation. Also, the paging file should be on a different hard drive or partition than the boot partition. Read here on the rules for best paging file performance.

7. In Windows XP and Vista, the Windows Search indexing service is turned on for all local hard drives. Turning off indexing is a simple way to increase performance.

8. If you don’t care about all the fancy visual effects in Windows, you can turn them off by going to Performance Options.

9. You can optimize the Windows boot time using a free program called Bootvis from Microsoft.

10. Clean your registry by removing broken shortcuts, missing shared DLLs, invalid paths, invalid installer references and more. Read about the 10 best and free registry cleaners.

11. One of the main reasons why PC’s are slow is because of spyware. There are many programs to remove spyware including Ad-Aware, Giant Antispyware, SUPERAntiSpyware, and more.

12. If you have a deeper spyware infection that is very hard to remove, you can use HijackThis to remove spyware.

13. Remove unwanted pre-installed software (aka junk software) from your new PC using PC Decrapifier.

14. Disable unnecessary Windows services, settings, and programs that slow down your computer.

15. Tweak Windows XP and tweak Windows Vista settings using free programs

16. Disable UAC (User Account Control) in Windows Vista

17. Tweak your mouse settings so that you can copy and paste faster, scroll faster, navigate quickly while browsing and more. Read here to learn how to tweak your mouse.

18. Delete temporary and unused files on your computer using a free program like CCleaner. It can also fix issues with your registry.

19. Delete your Internet browsing history, temporary Internet files, cookies to free up disk space.

20. Clean out the Windows prefetch folder to improve performance.

21. Disable the XP boot logo to speed up Windows boot time.

22. Reduce the number of fonts that your computer has to load up on startup.

23. Force Windows to unload DLLs from memory to free up RAM.

24. Run DOS programs in separate memory spaces for better performance.

25. Turn off system restore only if you regularly backup your Windows machine using third party software.

26. Move or change the location of your My Documents folder so that it is on a separate partition or hard drive.

27. Turn off default disk performance monitors on Windows XP to increase performance.

28. Speed up boot time by disabling unused ports on your Windows machine.

29. Use Process Lasso to speed up your computer by allowing it to make sure that no one process can completely overtake the CPU.

30. Make icons appear faster while browsing in My Computer by disabling search for network files and printers.

31. Speed up browsing of pictures and videos in Windows Vista by disabling the Vista thumbnails cache.

32. Edit the right-click context menu in Windows XP and Vista and remove unnecessary items to increase display speed.

33. Use the Windows Performance Toolkit and the trace logs to speed up Windows boot time.

34. Speed up your Internet browsing by using an external DNS server such as OpenDNS.

35. Improve Vista performance by using ReadyBoost, a new feature whereby Vista can use the free space on your USB drive as a caching mechanism.

36. If you have a slow Internet connection, you can browse web pages faster using a service called Finch, which converts it into simple text.

37. Use Vista Services Optimizer to disable unnecessary services in Vista safely.

38. Also, check out my list of web accelerators, which are programs that try to prefetch and cache the sites you are going to visit.

39. Speed up Mozilla Firefox by tweaking the configuration settings and by installing an add-on called FasterFox.

40. Learn how to build your own computer with the fastest parts and best hardware.

41. Use a program called TeraCopy to speed up file copying in Windows XP and Vista.

42. Disable automatic Last Access Timestamp to speed up Windows XP.

43. Speed up the Start Menu in Vista by hacking the MenuShowDelay key in the registry.

44. Increase the FileSystem memory cache in Vista to utilize a system with a large amount of RAM.

45. Install more RAM if you are running XP with less than 512 MB or Vista with less than 1 GB of RAM.

46. Shut down XP faster by reducing the wait time to kill hung applications.

47. Make sure that you have selected “Adjust for best performance” on the Performance tab in System Properties.

48. If you are reinstalling Windows, make sure that you partition your hard drives correctly to maximize performance.

49. Use Altiris software virtualization to install all of your programs into a virtual layer that does not affect the registry or system files.

50. Create and install virtual machines for free and install junk program, games, etc into the virtual machines instead of the host operating system. Check out Sun openxVM.

51. Do not clear your paging file during shutdown unless it is needed for security purposes. Clearing the paging file slows down shutdown.

52. If your XP or Vista computer is not using NFTS, make sure you convert your FAT disk to the NTFS file system.

53. Update all of your drivers in Windows, including chipset and motherboard drivers to their latest versions.

54. Every once in a while run the built-in Windows Disk Cleanup utility.

55. Enable DMA mode in Windows XP for IDE ATA/ATAPI Controllers in Device Manager.

56. Remove unnecessary or old programs from the Add/Remove dialog of the Control Panel.

57. Use a program click memtest86 or Prime95 to check for bad memory on your PC.

58. Determine your BIOS version and check the manufactures website to see if you need to update your BIOS.

59. Every once in a while, clean your mouse, keyboard and computer fans of dust and other buildup.

60. Replace a slow hard drive with a faster 7200 RPM drive, SATA drive, or SAS drive.

61. Changing from Master/Slave to Cable Select on your hard drive configuration can significantly decrease your boot time.

62. Perform a virus scan on your computer regularly. If you don’t want to install virus protection, use some of the free online virus scanners.

63. Remove extra toolbars from your Windows taskbar and from your Internet browser.

64. Disable the Windows Vista Sidebar if you’re not really using it for anything important. All those gadgets take up memory and processing power.

65. If you have a SATA drive and you’re running Windows Vista, you can speed up your PC by enabling the advanced write caching features.

66. Learn how to use keyboard shortcuts for Windows, Microsoft Word, Outlook, or create your own keyboard shortcuts.

67. Turn off the Aero visual effects in Windows Vista to increase computer performance.

68. If you are technically savvy and don’t mind taking a few risks, you can try to overclock your processor.

69. Speed up the Send To menu in Explorer by typing “sendto” in the Run dialog box and deleting unnecessary items.

70. Make sure to download all the latest Windows Updates, Service Packs, and hot fixes as they “normally” help your computer work better.

71. Make sure that there are no bad sectors or other errors on your hard drive by using the ScanDisk orchkdsk utility.

72. If you are not using some of the hardware on your computer, i.e. floppy drive, CD-ROM drive, USB ports, IR ports, Firewire, etc, then go into your BIOS and disable them so that they do not use any power and do not have to be loaded during boot up.

73. If you have never used the Recent Documents feature in Windows, then disable it completely as a long list can affect PC performance.

74. One basic tweak that can help in performance is to disable error reporting in Windows XP

75. If you don’t care about a pretty interface, you should use the Windows Classic theme under Display Properties.

76. Disable short filenames if you are using NTFS by running the following command: fsutil behavior set disable8dot3 1. It will speed up the file creation process.

77. If you have lots of files in a single folder, it can slow down Explorer. It’s best to create multiple folders and spread out the files between the folders.

78. If you have files that are generally large, you might want to consider increasing the cluster size on NTFS to 16K or even 32K instead of 4K. This will help speed up opening of files.

79. If you have more than one disk in your PC, you can increase performance by moving your paging file to the second drive and formatting the volume using FAT32 instead of NTFS.

80. Turn off unnecessary features in Vista by going to Control Panel, choosing Uninstall a program, and then clicking on Turn Windows features on and off. You can turn off Remote Differential Compression, Tablet PC components, DFS replication service, Windows Fax & Scan, Windows Meeting Space, and lots more.

81. Install a free or commercial anti-virus program to help protect against viruses, etc. Make sure to use an anti-virus program that does not hog up all of your computer resources.

82. Completely uninstall programs and applications using a program like Revo Uninstaller. It will get rid of remnants left behind by normal uninstalls.

83. If you know what you are doing, you can install several hard drives into your machine and set them up in RAID 0, RAID 5, or other RAID configurations.

84. If you are using USB 1.0 ports, upgrade to 2.0. If you have a Firewire port, try to use that instead of a USB port since Firewire is faster than USB right now.

85. Remove the drivers for all old devices that may be hidden in Device Manager that you no longer use.

86. A more extreme option is to choose a faster operating system. If you find Vista to be slow, go with Windows XP. Switching to Mac or Linux is also an option.

87. One of the easiest ways to speed up your PC is to simply reformat it. Of course, you want to backup your data, but it is the best way to get your computer back to peak performance.

88. Speed up Internet browsing in IE by increasing the number of max connections per server in the registry.

89. If you use uTorrent to download torrents, you can increase the download speeds by tweaking the settings.

90. If you have a desktop background, make sure it’s a small and simple bitmap image rather than a fancy picture off the Internet. The best is to find a really small texture and to tile it.

91. For the Virtual Memory setting in Windows (right-click on My Computer, Properties, Advanced, Performance Settings, Advanced, Virtual Memory), make sure the MIN and MAX are both the same number.

92. If you search on Google a lot or Wikipedia, you can do it much faster on Vista by adding them to the Vista Start Menu Instant Search box.

93. If you have a custom built computer or a PC that was previously used, make sure to check the BIOS for optimal settings such as enabled CPU caches, correctly set IDE/SATA data transfer modes, memory timings, etc. You can also enable Fast/Quick boot if you have that option.

94. If you have a SCSI drive, make sure the write cache is enabled. You can do so by opening the properties of the SCSI drive in Windows.

95. If you have a machine with an older network card, make sure to enable the onboard processor for the network card, which will offload tasks from the CPU.

96. If you are using Windows Vista, you can disable the Welcome Center splash screen that always pops up.

97. If you already have anti-spyware software installed, turn off Windows Defender protection.

98. If you are running a 32-bit version of Windows and have 4GB of RAM or more, you can force Windows to see and use all of the RAM by enabling PAE.

99. Buy a new computer!!! ;) Pretty easy eh?

I’m sure I have missed out on lots of performance tweaks, tips, hacks, etc, so feel free to post comments to add to the list! Enjoy!

Friday, 1 April 2011

Cloud Computing

Now a days lots of people are talking about cloud computing. But do u really know what the cloud computing means? Here is a simple video clip which mack you understand the basic idea of cloud computing.


Thursday, 31 March 2011

James A. Gosling


James A. Gosling, OC (born May 19, 1955 near Calgary, Alberta, Canada) is a software developer, best known as the father of the Java programming language.

In 1977, Gosling received a B.Sc in Computer Science from the University of Calgary. In 1983, he earned a Ph.D in Computer Science from Carnegie Mellon University, and his doctoral thesis was titled "The Algebraic Manipulation of Constraints". His thesis advisor was Raj Reddy. While working towards his doctorate, he wrote a version of emacs (gosmacs), and before joining Sun Microsystems he built a multi-processor version of Unix while at Carnegie Mellon University, as well as several compilers and mail systems.

Between 1984 and 2010, Gosling was with Sun Microsystems.

On April 2, 2010, Gosling left Sun Microsystems which had recently been acquired by the Oracle Corporation. Regarding why he left, Gosling wrote on his blog that "Just about anything I could say that would be accurate and honest would do more harm than good." He has since taken a very critical stance towards Oracle in interviews.

On March 28, 2011, James Gosling announced on his blog that he had been hired by Google.