Featured FREE Whitepapers

What's New Here?

software-development-2-logo

Application Scalability: Still elusive for Enterprises Apps

The advent of the Consumer Business application like Facebook, Twitter has changed the definition of Application Scalability. Decade back 10 million+ was a large user base, Facebook will touch 1Billion+ users by end of this year. There are hordes of applications in 100+ million user range. The techniques and approaches employed by these large Consumer Business Applications are different from the traditional enterprise application design and architecture techniques.If we study the architectures principles employed by these large Consumer Business Applications, then we can conclude to the followingAll the large consumer business applications are build and make use of Cloud Computing Applications are build using a combination of open source products and platforms Create solutions where the current set of solution do not meet requirement or scale up (e.g. HipHop, Hadoop, ChaosMonkey etc) Constant knowledge sharing within the community (FB/Twitter/Google open sources lot of their internal products)From the Application scalability perspective, the following key architecture patterns have emerged that are being used to scale the applicationStateless Applications – Modern Web applications maintain state, which means that they remember what you were did as part of your last request, and they remember all this data as part of the Session. The Stateful nature of the application means if the server holding that state goes down, the entire user state is lost. Traditional techniques like sync user session data across server nodes or persisting in data store do not scale very well. To overcome this shortcoming, the whole concept of creating stateless applications where the servers do not maintain state. The application uses cookies and makes use of RESTful API’s to craft the user experience. Newer frameworks like Play Framework, Node.js, Vertx.io all promote this stateless application development that scales with the increasing user load very well. Another option used is to offload session state is high throughput memory based key value store, which is common across stateless nodes. Data Sharding – Another issue encountered with scale is the increasing load on DB servers. DB Servers do employ techniques like Master/Slave or Clustering techniques coupled with large powerful boxes but beyond 100+ million users, these techniques also fail. Further, the costly hardware and software licenses make the traditional DB options very costly. So, companies have used the MySQL as the base and created lots of solutions/topologies around the same. One of those techniques is data sharding. A Data shard is a horizontal partition of the data, meaning rows of the tables are held separately. There are numerous advantages to this partitioning approach. Since the tables are divided and distributed into multiple servers, the total number of rows in each table in each database is reduced. This reduces index size, which generally improves search performance. A database shard can be placed on separate hardware, and multiple shards can be placed on multiple machines. This enables a distribution of the database over a large number of machines, allowing database performance to be spread over multiple machines, greatly improving overall performance.Many new non-relational databases (commonly known as NoSQL databases) such as Cassandra, MongoDb and Hbase have been created with database sharding as a key feature. Bring Data closer to user (Caching) – Caching has been adopted and used very well by most of the Consumer Business Apps. Open source products like memcache provide caching options across the tiers (web tier/app tier and data tier). Memcache provides a reliable alternative to the traditional caching solutions – coherence, terracotta. Further, the NoSQL solutions employ the caching engine to speed up the database read and write operations. Couchdb uses the memcache to provide an in memory read/write solution. Service provider/consumer model – Another pattern that has emerged is the Service provider and consumer. It is derivative of the SOA model but leaner and simpler. The business functionality is exposed as a set of services via RESTful API with JSON data format. The presentation layers are the consumers that use these services to build up the user experience. The technologies to build the service and provider can be completely separate. Technologies are chosen based on what is best for the use case. Contracts are enforced by Service version and definition only. Front ends are typically built using PHP or Ruby over rails. Services are built using Scala, Akka, C++, Java etc.Why Enterprises are looking at these patterns?Enterprises have started adopting cloud (public/private) by and large. Elastic scaling means responding to the changing load pattern on real time basis. In the absence of application ability to scale, all that investment into cloud is waste The traditional CPU/Core based licensing models are proving to be costly in the cloud world. Enterprise need to adopt the OSS frameworks/solutions that do not come with licensing baggage The user expectations have gone up by few notches. Enterprise applications are compared and expected to have same resiliency & performance as any other Internet Scale application Scale up model(adding more CPUs) for enterprise applications comes with its own headache of additional capital expenditure. Scale out models(add more smaller servers) that rely on commodity servers or can run over a hybrid cloud are becoming more cost effective solutions Enterprises are going global which requires the systems to be up and available 24X7. Currently tightly coupled application designs do not lend very well to the scalability patternReference: Application Scalability: Still elusive for Enterprises Apps from our JCG partner Munish K Gupta at the Tech Spot blog....
spring-data-logo

Hibernate native SQL features into your Spring Data Repository

JPA provides @NamedNativeQuery for you to use native SQL. However, the usage is not so convenient, especially when you need to map multiple entities in your native SQL. You have to define a set of SqlResultSetMapping mapping which is quite error prone. For those who have used Hibernate native SQL features before, you will find that it is much more easier to use than JPA’s @NamedNativeQuery. In recent projects, I am using Spring Data JPA. I have added hibernate native query features to my Spring Data base repostory. You can now perform native query in JPA without SqlResultSetMapping. 1. Add you cusomt annotation @NativeQueries and @NativeQuery @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface NativeQueries { NativeQuery[] queries() default {}; }@Retention(RetentionPolicy.RUNTIME) public @interface NativeQuery { String name() default ""; String sql() default ""; }2. Add the method “queryNatively” in base Spring Data Repository. If you do not know how to add custom behaviour to your Spring data JPA base repository, please see my previous post for how to customize your Spring data JPA base repository for detail. You can see in previous post that I intentionally expose the repository interface (i.e. the springDataRepositoryInterface property) in the GenericRepositoryImpl. This small tricks enable me to access the annotation in the repository interface easily. public List queryNatively(String nativeQueryName, LinkedHashMap<String,Class<?>> inEntityClasses, Map inParams ){ SQLQuery query = this.createHibernateNativeQuery( nativeQueryName, inParams ); //add entities if (inEntityClasses!=null) { for (Object key: inEntityClasses.keySet()) { String entityClassAlias = key.toString(); Class<?> entityClass = (Class<?>)inEntityClasses.get(key); query.addEntity(entityClassAlias,entityClass); } } //add parameter if (inParams != null){ for (Object key: inParams.keySet()) { String queryParamName = key.toString(); Object queryParamValue = inParams.get(key); query.setParameter(queryParamName, queryParamValue); } } return (query!=null)? query.list() : null ; }private SQLQuery createHibernateNativeQuery (String nativeQueryName, Map inParams ){ if (GenericRepository.class.isAssignableFrom(getSpringDataRepositoryInterface())) { Annotation nativeQueryAnn = getSpringDataRepositoryInterface().getAnnotation(NativeQueries.class); if(nativeQueryAnn != null){ NativeQueries nativeQueries = (NativeQueries)nativeQueryAnn; NativeQuery[] queries = nativeQueries.queries(); for (NativeQuery sqlquery : queries) { if (StringUtils.equals(nativeQueryName, sqlquery.name())) { String sql = sqlquery.sql(); Session hiernateSess = em.unwrap(Session.class); SQLQuery query = hiernateSess.createSQLQuery(sql); //add parameter if (inParams != null){ for (Object key: inParams.keySet()) { String queryParamName = key.toString(); Object queryParamValue = inParams.get(key); query.setParameter(queryParamName, queryParamValue); } } return query; } } } } return null; }3. Example Usage In your repositry interface, define which native SQL queries you want to use through your @NativeQueries and @NativeQuery annotation. The usage is just similar to calling hibernate native query features. You could just see the hibernate alias and property references. @NativeQueries ( queries = { @NativeQuery(name="query1", sql="SELECT {cat.*}, {mother.*} FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID and c.name = :catName "), @NativeQuery(name="query2", sql="SELECT {cat.*} FROM CATS where c.ID = :catName") } ) public interface CatRepository extends GenericRepository<Cat, Long> { }In your service or business class that inject your repository, you could just simply call the queryNatively() method to perform native SQL query. @Service public class CatService { @Inject private CatRepository catRepository; public List<Cat> searchCat( String catName) { List<Cat> catList; // Add entity mapping for your query HashMap<String, Object> inParams = new HashMap<String, Object>(); inParams.put("catName", "Felix"); // Prepare parameters for your native sql LinkedHashMap<String, Object> entityMap = new LinkedHashMap<String, Object>(); entityMap.put("cat", Cat.class); entityMap.put("mother",Mother.class); catList = catRepository.queryNatively( "query1", "",entityParam); return catList; } }Reference: Adding Hibernate native SQL features into your Spring Data Repository from our JCG partner Boris Lam at the Programming Peacefully blog....
android-logo

Android Voice Recognition Tutorial

You may have heard about the “ Google Now project” where you give the voice command and Android fetches result for you. It recognizes your voice and converts it into the text or takes the appropriate action. Have you ever thought how is it done? If your answer is voice recognition API, then you are absolutly right. Recently while playing with Android voice recognition APIs, I found some interesting stuffs. APIs are really easy to use with application. Given below is a small tutorial on voice/speech recognition API. The final application will look similar to that of application shown below. The application may not work on the Android Emulator because it doesn’t support voice recognition. But the same can work on the phone.Project Information: Meta-data about the project. Platform Version : Android API Level 15. IDE : Eclipse Helios Service Release 2 Emulator : Android 4.1(API 16) Prerequisite: Preliminary knowledge of Android application framework, and Intent. Voice recognition feature can be achieved by RecognizerIntent. Create an Intent of type RecognizerIntent and pass the extra parameters and start activity for the result. It basically starts the recognizer prompt customized by your extra parameters. Internally voice recognition communicates with the server and gets the results. So you must provide the internet access permission for the application. Android Jelly Bean(API level 16) doesn’t require internet connection to perform voice recognition. Once the voice recognition is done, recognizer returns value in onActivityResult() method parameters. First create project by Eclipse > File> New Project>Android Application Project. The following dialog box will appear. Fill the required field, i.e Application Name, Project Name and Package. Now press the next button. Once the dialog box appears, select the BlankActivity and click the next button.Fill the Activity Name and Layout file name in the dialog box shown below and hit the finish button.This process will setup the basic project files. Now we are going to add four buttons in the activity_voice_recognition.xml file. You can modify the layout file using either Graphical Layout editor or xml editor. The content of the file is shown below. As you may notice that we have attached speak() method with button in onClick tag. When the button gets clicked, the speak() method will get executed. We will define speak() in the main activity. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" ><EditText android:id="@+id/etTextHint" android:gravity="top" android:inputType="textMultiLine" android:lines="1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/etSearchHint"/><Button android:id="@+id/btSpeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="speak" android:padding="@dimen/padding_medium" android:text="@string/btSpeak" tools:context=".VoiceRecognitionActivity" /><Spinner android:id="@+id/sNoOfMatches" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/saNoOfMatches" android:prompt="@string/sNoOfMatches"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/tvTextMatches" android:textStyle="bold" /><ListView android:id="@+id/lvTextMatches" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>You may have noticed that the String constants are being accessed from the resource. Now add the string constants in string.xml. This file should look similar to the one shown below. <resources> <string name="app_name">VoiceRecognitionExample</string> <string name="btSpeak">Speak</string> <string name="menu_settings">Settings</string> <string name="title_activity_voice_recognition">Voice Recognition</string> <string name="tvTextMatches">Text Matches</string> <string name="sNoOfMatches">No of Matches</string> <string name="etSearchHint">Speech hint here</string> <string-array name="saNoOfMatches"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> <item>8</item> <item>9</item> <item>10</item> </string-array> </resources>Now let’s define the Activity class. This activity class, with the help of checkVoiceRecognition() method, will first check whether the Voice recognition is available or not. If voice recognition feature is not available, then toast a message and disable the button. Speak() method is defined here which gets called once the speak button is pressed. In this method we are creating RecognizerIntent and passing the extra parameters. The code below has embedded comments which makes it easy to understand. package com.rakesh.voicerecognitionexample;import java.util.ArrayList; import java.util.List;import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast;public class VoiceRecognitionActivity extends Activity { private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;private EditText metTextHint; private ListView mlvTextMatches; private Spinner msTextMatches; private Button mbtSpeak;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_voice_recognition); metTextHint = (EditText) findViewById(R.id.etTextHint); mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches); msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches); mbtSpeak = (Button) findViewById(R.id.btSpeak); checkVoiceRecognition() }public void checkVoiceRecognition() { // Check if voice recognition is present PackageManager pm = getPackageManager(); List<resolveinfo> activities = pm.queryIntentActivities(new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() == 0) { mbtSpeak.setEnabled(false); mbtSpeak.setText("Voice recognizer not present") Toast.makeText(this, "Voice recognizer not present", Toast.LENGTH_SHORT).show(); } }public void speak(View view) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);// Specify the calling package to identify your application intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass() .getPackage().getName());// Display an hint to the user about what he should say. intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText() .toString());// Given an hint to the recognizer about what the user is going to say //There are two form of language model available //1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases //2.LANGUAGE_MODEL_FREE_FORM : If not sure about the words or phrases and its domain. intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);// If number of Matches is not selected then return show toast message if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) { Toast.makeText(this, "Please select No. of Matches from spinner", Toast.LENGTH_SHORT).show(); return; }int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem() .toString()); // Specify how many results you want to receive. The results will be // sorted where the first result is the one with higher confidence. intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches); //Start the Voice recognizer activity for the result. startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); }@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)//If Voice recognition is successful then it returns RESULT_OK if(resultCode == RESULT_OK) {ArrayList<string> textMatchList = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);if (!textMatchList.isEmpty()) { // If first Match contains the 'search' word // Then start web search. if (textMatchList.get(0).contains("search")) {String searchQuery = textMatchList.get(0); searchQuery = searchQuery.replace("search",""); Intent search = new Intent(Intent.ACTION_WEB_SEARCH); search.putExtra(SearchManager.QUERY, searchQuery); startActivity(search); } else { // populate the Matches mlvTextMatches .setAdapter(new ArrayAdapter<string>(this, android.R.layout.simple_list_item_1, textMatchList)); }} //Result code for various error. }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){ showToastMessage("Audio Error"); }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){ showToastMessage("Client Error"); }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){ showToastMessage("Network Error"); }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){ showToastMessage("No Match"); }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){ showToastMessage("Server Error"); } super.onActivityResult(requestCode, resultCode, data); } /** * Helper method to show the toast message **/ void showToastMessage(String message){ Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }Here is the Android manifest file. You can see that INTERNET permission has been provided to the application because of the voice recognizer’s need to send the query to the server and get the result. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rakesh.voicerecognitionexample" android:versionCode="1" android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <!-- Permissions --> <uses-permission android:name="android.permission.INTERNET" /><application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" ><activity android:name=".VoiceRecognitionActivity" android:label="@string/title_activity_voice_recognition" > <intent-filter> <action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>Once you are done with coding then connect the phone with your system and hit the run button on Eclipse IDE. Eclipse will install and launch the application. You will see the following activities on your device screen. In the next tutorial, we will learn how to use the new voice recognition API introduced in Android Jelly Bean(API level 16) along with the examples. If you are interested in the source code, then you can get it from github. Reference: Tutorial on Android Voice recognition from our JCG partner Rakesh Cusat at the Code4Reference blog....
ignite-realtime-openfire-logo

Android: File transfer with asmack and Openfire

I have seen many peoples struggling from file transfer in asmack – Android build environment and patches for smack. I tried same library with Openfire server after some debugging got success in it. So I will like to share my problem and solution for it. I found that the problem is in Byte Stream host, it tries to connect to wrong host for initiating file transfer using byte streams. If you have not configured the file transfer proxy properly then it will choose 127.0.0.1 or localhost or any internally configured host/ip as a bytestream host, which in android is not considered as proper ip for communicating. But wait then why it is working properly with desktop client with same server. The reason is desktop clients can easily identify this ips and can use it to open socket for file transfer. The variable names used in following discussions are:Name MeaningmyHost The hostname of machine on which Openfire is running.user1@myHost File transfer initiator useruser2@myHost Recipient of fileHow to know which host is chosen for byte streams: (Following XMLs are shown as they are sent and received to the file transfer initiator.)First query other client for information about supported features:Sent: <iq id='x1ixz-13' to='user2@myHost/Smack' type='get'> <query xmlns='http://jabber.org/protocol/disco#info'></query> </iq> Received: <iq id='x1ixz-13' to='user1@myHost/Smack' type='result' from='user2@myHost/Smack'> <query xmlns='http://jabber.org/protocol/disco#info'> <!—some other items --> <feature var='http://jabber.org/protocol/bytestreams'/> <!—some other items --> </query> </iq> Here you can know that whether bytestream file transfer is supported on the client other side or not. If you see a xml like above in response then it’s supported on the other side and you can go further.Query server for disco items:Sent: <iq id='x1ixz-14' to='myHost' type='get'> <query xmlns='http://jabber.org/protocol/disco#items'></query> </iq> Received: <iq type='result' id='x1ixz-14' from='myHost' to='user1@ myHost /Smack'> <query xmlns='http://jabber.org/protocol/disco#items'> <!—some other items --> <item jid='proxy. myHost ' name='Socks 5 Bytestreams Proxy'/> <!—some other items --> </query> </iq> Here you will receive various items for different items supported by server like , file transfer proxy, search service, conference service… The item we should look for is ` Socks 5 Bytestreams Proxy `.Request for more information on proxySent: <iq id='x1ixz-19' to='proxy. myHost ' type='get'> <query xmlns='http://jabber.org/protocol/bytestreams'/> </iq> Received: <iq type='result' id='x1ixz-19' from='proxy. myHost ' to='user1@ myHost /Smack'> <query xmlns='http://jabber.org/protocol/bytestreams'> <streamhost jid='proxy. myHost ' host=' myHost ' port='7777'/> </query> </iq> Here the host in the <streamhost> is the key for the file transfer. You have to make sure that this host is accessible from your android phone. It should not be like localhost, 127.0.0.1 or any company’s internal configured server which is not accessible outside of the company. It must be a publicly accessible ip address or host. To configure proper proxy add/change these 3 properties in Openfire:xmpp.proxy.enabled – true xmpp.proxy.port – 7777 xmpp.proxy.externalip – [publicly accessible host or ip]The code for file transfer: FileTransferManager manager = new FileTransferManager(connection); OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer('usre2@myHost/Smack'); File file = new File(filenameWithPath); try { transfer.sendFile(file, 'test_file'); } catch (XMPPException e) { e.printStackTrace(); } while(!transfer.isDone()) { if(transfer.getStatus().equals(Status.error)) { System.out.println('ERROR!!! ' + transfer.getError()); } else if (transfer.getStatus().equals(Status.cancelled) || transfer.getStatus().equals(Status.refused)) { System.out.println('Cancelled!!! ' + transfer.getError()); } try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error) || transfer.getStatus().equals(Status.cancelled)){ System.out.println('refused cancelled error ' + transfer.getError()); } else { System.out.println('Success'); } And the code for file receive: FileTransferManager manager = new FileTransferManager(connection); manager.addFileTransferListener(new FileTransferListener() { public void fileTransferRequest(final FileTransferRequest request) { new Thread(){ @Override public void run() { IncomingFileTransfer transfer = request.accept(); File mf = Environment.getExternalStorageDirectory(); File file = new File(mf.getAbsoluteFile()+'/DCIM/Camera/' + transfer.getFileName()); try{ transfer.recieveFile(file); while(!transfer.isDone()) { try{ Thread.sleep(1000L); }catch (Exception e) { Log.e('', e.getMessage()); } if(transfer.getStatus().equals(Status.error)) { Log.e('ERROR!!! ', transfer.getError() + ''); } if(transfer.getException() != null) { transfer.getException().printStackTrace(); } } }catch (Exception e) { Log.e('', e.getMessage()); } }; }.start(); } }); Also configure ProviderManager to properly decode/parse bytestreams and other required xmls: ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/bytestreams', new BytestreamsProvider()); ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#items', new DiscoverItemsProvider()); ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#info', new DiscoverInfoProvider()); The asmack library I used was asmack-jse-buddycloud.jar. Reference: File transfer in android with asmack and Openfire from our JCG partner Harsh Raval at the harryjoy blog....
jboss-hibernate-logo

Hibernate lazy/eager loading example

This post will focus on why and how we use the concepts known as LAZY and EAGER loading in an application and how to use Spring’s hibernate template to load our LAZY entities in an EAGER fashion. And of course as the title itself suggests, we will show this by an example. The scenario is as such; You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time. So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys. But you are faced with another issue. When the time comes for a family trip, you want him to bring along his toys because the kid will be bored with the trip otherwise. But since you strictly enforced LAZY on the child’s toy, you are unable to ask him to bring along the toys. This is where EAGER fetching comes into play. Let us first see our domain classes. package com.fetchsample.example.domain;import java.util.HashSet; import java.util.Set;import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table;/** * Holds information about the child * * @author dinuka.arseculeratne * */ @Entity @Table(name = 'CHILD') @NamedQuery(name = 'findChildByName', query = 'select DISTINCT(chd) from Child chd left join fetch chd.toyList where chd.childName=:chdName') public class Child {public static interface Constants { public static final String FIND_CHILD_BY_NAME_QUERY = 'findChildByName';public static final String CHILD_NAME_PARAM = 'chdName'; }@Id @GeneratedValue(strategy = GenerationType.AUTO) /** * The primary key of the CHILD table */ private Long childId;@Column(name = 'CHILD_NAME') /** * The name of the child */ private String childName;@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) /** * The toys the child has. We do not want the child to have the same toy more than * once, so we have used a set here. */ private Set<Toy> toyList = new HashSet<Toy>();public Long getChildId() { return childId; }public void setChildId(Long childId) { this.childId = childId; }public String getChildName() { return childName; }public void setChildName(String childName) { this.childName = childName; }public Set<Toy> getToyList() { return toyList; }public void addToy(Toy toy) { toyList.add(toy); }}package com.fetchsample.example.domain;import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;/** * Hols data related to the toys a child possess * * @author dinuka.arseculeratne * */ @Entity @Table(name = 'TOYS') public class Toy {@Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = 'TOY_ID') /** * The primary key of the TOYS table */ private Long toyId;@Column(name = 'TOY_NAME') /** * The name of the toy */ private String toyName;public Long getToyId() { return toyId; }public void setToyId(Long toyId) { this.toyId = toyId; }public String getToyName() { return toyName; }public void setToyName(String toyName) { this.toyName = toyName; }@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((toyName == null) ? 0 : toyName.hashCode()); return result; }@Override /** * Overriden because within the child class we use a Set to * hold all unique toys */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Toy other = (Toy) obj; if (toyName == null) { if (other.toyName != null) return false; } else if (!toyName.equals(other.toyName)) return false; return true; }@Override public String toString() { return 'Toy [toyId=' + toyId + ', toyName=' + toyName + ']'; }}So as you can see, we have two simple entities representing the child and toy. The child has a one-to-many relationship with the toys which means one child can have many toys (oh how i miss my childhood days). Afterwards we need to interact with the data, so let us go ahead and define out DAO(Data access object) interface and implementation. package com.fetchsample.example.dao;import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional;import com.fetchsample.example.domain.Child;/** * The basic contract for dealing with the {@link Child} entity * * @author dinuka.arseculeratne * */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public interface ChildDAO {/** * This method will create a new instance of a child in the child table * * @param child * the entity to be persisted */ public void persistChild(Child child);/** * Retrieves a child without his/her toys * * @param childId * the primary key of the child table * @return the child with the ID passed in if found */ public Child getChildByIdWithoutToys(Long childId);/** * Retrieves the child with his/her toys * * @param childId * the primary key of the child table * @return the child with the ID passed in if found */ public Child getChildByIdWithToys(Long childId);/** * Retrieves the child by the name and with his/her toys * * @param childName * the name of the child * @return the child entity that matches the name passed in */ public Child getChildByNameWithToys(String childName);}package com.fetchsample.example.dao.hibernate;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.fetchsample.example.dao.ChildDAO; import com.fetchsample.example.domain.Child;/** * The hibernate implementation of our {@link ChildDAO} interface * * @author dinuka.arseculeratne * */ public class ChildDAOHibernateImpl extends HibernateDaoSupport implements ChildDAO {/** * {@inheritDoc} */ public void persistChild(Child child) { getHibernateTemplate().persist(child); }/** * {@inheritDoc} */ public Child getChildByIdWithoutToys(Long childId) { return getHibernateTemplate().get(Child.class, childId); }/** * {@inheritDoc} */ public Child getChildByIdWithToys(Long childId) { Child child = getChildByIdWithoutToys(childId); /** * Since by default the toys are not loaded, we call the hibernate * template's initialize method to populate the toys list of that * respective child. */ getHibernateTemplate().initialize(child.getToyList()); return child; }/** * {@inheritDoc} */ public Child getChildByNameWithToys(String childName) { return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam( Child.Constants.FIND_CHILD_BY_NAME_QUERY, Child.Constants.CHILD_NAME_PARAM, childName).get(0);}}A simple contract. I have four main methods. The first one of course just persists a child entity to the database. The second method retrieves the Child by the primary key passed in, but does not fetch the toys. The third method first fetches the Child and then retrieves the Child’s toys using the Hibernate template’s initialize() method. Note that when you call the initialize() method, hibernate will fetch you LAZY defined collection to the Child proxy you retrieved. The final method also retrieves the Child’s toys, but this time using a named query. If we go back to the Child entity’s Named query, you can see that we have used ‘left join fetch‘. It is the keyword fetch that actually will initialize the toys collection as well when returning the Child entity that qualifies. Finally i have my main class to test our functionality; package com.fetchsample.example;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.fetchsample.example.dao.ChildDAO; import com.fetchsample.example.domain.Child; import com.fetchsample.example.domain.Toy;/** * A test class * * @author dinuka.arseculeratne * */ public class ChildTest {public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( 'com/fetchsample/example/spring-context.xml');/** * First we initialize a child */ Child child = new Child();/** * A cool ben 10 action figure */ Toy ben10 = new Toy(); ben10.setToyName('Ben 10 figure');/** * A even more cooler spider man action figure */ Toy spiderMan = new Toy(); spiderMan.setToyName('Spider man figure');child.setChildName('John'); /** * Add the toys to the collection */ child.addToy(ben10); child.addToy(spiderMan);ChildDAO childDAO = (ChildDAO) context.getBean('childDAO');childDAO.persistChild(child);Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L); // The following line will throw a lazy initialization error since we have // defined fetch type as LAZY in the Child domain class. // System.out.println(childWithToys.getToyList().size());Child childWithToys = childDAO.getChildByIdWithToys(1L); System.out.println(childWithToys.getToyList().size());Child childByNameWithToys = childDAO.getChildByNameWithToys('John');System.out.println(childByNameWithToys.getToyList().size());} }Defining your base Entity as LAZY is a good practice since in many occasions, you might not want the collections within an entity, but just want to interact with the data in your base entity. But in the event of you needing the data of your collections, then you can use either of the methods mentioned before. That is about it for today. For anyone who wants to try out the example, i have uploaded it here. Reference: Lazy/Eager loading using hibernate by example from our JCG partner Dinuka Arseculeratne at the My Journey Through IT blog....
scala-logo

Scala: Missing OO and FP bridge

Scala blends functional and object-oriented programming in many nice ways. You can use both FP an OO-like constructs whichever fits the current problem better. But there’s always room for improvement! Here’s one thing I think is missing (short version at the bottom). FP side It’s easy to convert a method to a function in Scala. For example, if you have a method: def say(to: Person, what: String): String = { ... }we can get the corresponding function using the underscore notation: val sayFun: (Person, String) => String = say _Moreover, Scala supports multiple parameter lists, which is sometimes also referred to as currying, and which makes partial application easier: // Method with multiple parameter list def connect(person1: Person)(person2: person): Connection = { ... } // Function, created by partially applying the previous method val createConnectionWithAdam: Person => Connection =       connect(new Person('Adam')) _OO side One thing every class has is a constructor. But what is a constructor, really? You give values for the constructor’s arguments, and get a new instance of the class in return. So it’s really just a function! class Person(name: String, age: Int) { ... } // The 'signature' of new is (String, Int) => Person val somebody = new Person('John', 34)Link? However, that’s where the combination of OO and FP fails in Scala: you can’t use the two features of methods (convert to function, currying) mentioned above with constructors. Both of these won’t work: val makePerson: (String, Int) => Person = new Person _class Person2(name: String)(age: Int) { ... } val makeNewJack: Int => Person = new Person2('Jack') _You can get around this using companion objects and apply (or any other factory method, apply just has a nicer notation afterwards): object Person2 {    def apply(name: String)(age: Int) = new Person2(name, age)} val makeNewJack: Int => Person = Person2('Jack') _But that requires repeating the signature of the constructor in the companion object, and nobody likes code duplication, right? ;) Use-case Where can this be useful? For example in the classic factory example. Imagine you have a class which depends on some services, but also on some data available on runtime. Of course we use IoC so instances of the other services are provided to our class: // This service depends on a concrete Person instance class Service3(service1: Service1, service2: Service2)(person: Person) { ... } / Note that the multiple parameter notation above als provides a nice // separation of the parameters that should be 'injected' - services, // and the data that can be variable. // This service depends on Service1, and wants to create it having Person // instances class Service4(makeService3: Person => Service3) {   // Usage:   for (person <- persons) makeService3(person).doSomething() } class Main { // Bootstrap: (or - no-framework DI container ;) ) val service1 = new Service1 val service2 = new Service2 // That's the part that is illegal in Scala val makeService3 = new Service3(service1, service2) _ val service4 = new Service4(makeService1) ... // Today we'd have to write: val makeService3 = (person: Person) => new Service3(//service1, service2, person) }That’s also connected to my post on DI and OO, and how current DI frameworks make it hard to define services which depend on data and services that we’d like to have multiple copies of. Side note When viewing constructors as methods/functions (which they are, really ;) ), I suppose the Ruby-like notation: Person.new('John', 34)would be better and adding support for _ and multiple parameter lists would be obvious. Bottom line for TL;DR fans Why not treat class constructors as every other method/function? Make this legal: class Person(name: String, age: Int) val makePerson = new Person _ // type: (String, Int) => Personclass Person2(name: String)(age: Int) val makeNewJack = new Person2('Jack') _ // type: Int => PersonReference: Missing OO and FP bridge in Scala from our JCG partner Adam Warski at the Blog of Adam Warski blog....
eclipse-logo

Hot tips on using Eclipse effectively

Following are some tips that shall help you in avoiding potential issues and for being a little more productive while working with eclipse.Avoid installation problems Never install a new version of Eclipse on top of an older version. Rename the old one first to move it out of the way, and let the new version be unpacked in a clean directory.   Recovering your messed up workspace Corrupted workspace is a common occurrence and troublemaker for many developers. So If your Eclipse installation has startup errors or a corrupted configuration, it might be time to get a fresh start. Start Eclipse with the –clean option, and all cached framework and runtime data will be cleared out. This often helps fix plug-in issues and improve general stability. Increase the memory allocation With new plugins getting added to the core eclipse functionality and the need to use additional third party plugins, the memory requirements for your eclipse workspace increases. The default memory allocation configured in eclipse is not enough for most J2ee development projects and that causes a sluggish response from you eclipse. If you get Out of Memory errors or sluggish response, you may have to increase the defaults that are set in eclipse.ini file in the Eclipse installation directory. In particular, if you get an error about “PermGen” memory (permanent generation), add this line at the end and restart Eclipse: - XX:MaxPermSize=256m Use the lowest memory settings that work and perform well for your mix of projects.   Side by side editing By dragging editors, you can show two files side by side. You can also edit two portions of the same file by using the Window > New Editor command.Automatic code improvements Set up Eclipse to automatically format source code and organize imports on every save. Select Window > Preferences > Java Editor > Save Actions to enable these actions. This dialog also lets you configure actions like removing unnecessary casts or adding missing annotations. Configuring your eclipse with optimized Compiler, Formatter and CheckStyle settings is described in detail in the post Using Eclipse Effectively Keyboard shortcuts It is productive and convenient to use keyboard shortcuts for performing certain tasks in eclipse rather than looking for options to do the same in various navigation menus. For example looking up references of a variable, method or a class can be quickly achieved via shortcut Ctrl+Shift+g. For your reference I have included a list of the most important keyboard shortcuts in my post Eclipse Keyboard Shortcuts Reference: Hot tips on using Eclipse effectively from our JCG partner Sanjeev Kumar at the Architect’s Diary blog....
career-logo

Debate Breakdown – Advice From A JUG Leader

It’s been a week since I posted “Advice From A JUG Leader – Learn a Different Language” and it seems to have ruffled at least a few feathers in the Java community. As the article has been re-posted and bounced around on Twitter, I have had some opportunity to interact with some members of the Java community who have strong feelings about the content. None have called for my death, and the debate has been almost entirely polite thus far.I think and sincerely hope that the Java community understands that the impetus for writing this article was an observation that many in the Java community are simply not aware of the trends in the industry, and by the time those trends become standards it is too late. These are the people that, if the train does come, never heard it approaching. My purpose is not to predict or encourage the demise of Java, as that should not and will not happen. The Java community is deeply loyal to Java, perhaps even to a fault, and I hope these articles serve as a wake-up call that the most important loyalty should be to your career as a software professional and to neither an employer or language.I have noticed from these mini-debates is that defenders of Java, at least in my interactions so far, seem to primarily be highly experienced developers that perhaps have the most invested in Java. As I mentioned in my original article, I don’t expect known Java experts to feel any changes. At least a few of the comments seem to come off as rants against youth (“go play your Xbox“?) and start-up culture and not a defense of the language’s health itself. I haven’t seen the younger generation of Java pros, but I know they are out there. I don’t seem to see Java enthusiasts attacking faults in the alternative languages or praising Java for a superior feature set.Some comments seem to admit that Java has some shortcomings just like other languages, but it’s what we have for now. That is good enough for some people – particularly those that have been in Java for a long time – but not good enough for many developers who want to work with the best available. The arguments so far have been, in no particular order:  Argument #1 – Don’t Use Alternative Languages Because The Languages are Unproven, and/or Only Start-ups Use Alternative Languages“And, don’t forget, 70% of startups will fail within the first ten years. So, I’m not inclined to base my decisions on the faulty and unproven ability of start-ups to make sound business decisions for themselves.” – Comment from TSS reader, click for full contextSome of the languages are more proven than others obviously, but we can’t ignore the fairly regular news regarding established firms transitioning to alternative languages and platforms or taking a polyglot approach. I would hardly call companies like Twitter, YouTube, foursquare, LinkedIn and Google immature start-ups at this point. If you are going to argue that there are plenty of other shops that use Java, we all know that. The point is some start-ups (those most apt to use these alternative languages) have made bad decisions (as have large firms), but to call the languages themselves ‘unproven’ at this point would not be accurate. No guilt by association here.Businesses don’t make decisions, people do. I don’t think we should fall into the trap of lumping together the decisions made inside of some start-ups as any proof of language relevance at this point. When a host of start-ups fail due to their language choice alone, that conversation can be had.  If you were around back in the late nineties there were a lot of technology start-ups with funny sounding dot-com names. Many of these companies were using a three or four year-old programming language called Java. They could not have predicted that Java would grow to be as popular as it is today.Note: Python is older and Ruby is about the same age as Java, Scala has been around for 9 years, Clojure for 5 years.  Argument #2 – If You’re Bored With Java, That Is No Reason To Branch Out“Becoming “bored or frustrated with Java” is a pretty poor excuse for branching out. As a professional, I’m not paid to feel entertained and broadened in my horizons. I’m paid to get things done as efficiently and as well as I possibly can… Go home and play your Xbox to relieve boredom. Don’t make your employer pay for yet another language learning curve so that you feel less bored and frustrated.” – Comment from TSS reader, click for full contextSimply being bored with Java could be enough for someone to look for other alternatives. I think the bigger issue is that technologists who pay attention to developments in other languages are envious of the features that other languages provide. Today, I feel that a smaller percentage of the Java community explore alternative languages based either on less curiosity or less opportunity. As the Java community at large is exposed to these other languages more and more, I would expect you will see many more defectors. The early adopters of Java were the most curious C++ or C developers who were looking for something different and stumbled on Java, and the most curious of Java pros stumbled on these other languages over the past few years.  Argument #3 – The Assumption That Most or All Of These Alternative Languages Will Be Dead In 5-10 Years“If I’m off learning optional languages, I’m falling short of what I get paid to do. What’s more, I may have decided to do some development in one of the latest and greatest languages that, in a few years, will fall by the wayside, and now I’ve left my employer with a bunch of projects that will have to be re-written into a language that is currently active and supported.” – Comment from TSS reader, click for full contextMany of the early adopters of Java, as I mentioned in my article, have already been exploring some of these alternative languages for some time now. Often they were not initially paid to do so. Could some of these languages be dead in 5-10 years? Sure. Most of the languages I’m thinking of when I talk about alternative languages are already 5 years old, and some much older. Even the young Ruby/Rails combo has been around for over 5 years.Did people make the same assumption about Java back in the late nineties?  Argument #4 – Look At The Evidence That These Alternative Languages Are Not Being Adopted/Used/Sought AfterSome defenders of Java have been pointing me to various statistics as proof that these alternative languages are not being used, not being sought after by employers, or not being adopted. I would cede that none of the current crop are even close to Java in terms of popularity today. I was sent to this link from Networkworld.com that says Java developers are the “most difficult tech pros to land, followed by mobile developers“. I wonder where the demand for mobile developers was three years ago? Would mobile development be a valuable skill to learn at this point?As a recruiter, I’m also having a bit of a harder time finding Java developers now. One of the main reasons for that is pretty simple – a lot of the people that I know that used to do Java work aren’t interested in doing Java work any more. Over the years I’ve met a fair amount of experienced Java developers that were dying to get a job doing mobile work, Ruby work, Scala work, etc., but I’m not finding too many Ruby or Scala programmers with five years out of school looking for their first Java job. Maybe it’s just me, but I don’t see that…ever.Another link was given to the Tiobe Index, which is pretty widely used to highlight trends of language popularity. It is based on search engine hits. All indexes like this have some obvious flaws. If you read Tiobe’s Definition, the phrase “Java programming is dead” will actually improve Java’s position in the rankings. So absorb these ratings with that in mind. They measure chatter, which could be positive or negative. Tiobe Programming Community Index for July 2012Well, the takeaway from this graphic, for me anyway, would be that Java dropped significantly and Objective-C seems to be gaining popularity dramatically. But this could be some anomaly in a given month.Tiobe PCI 10 Year Trend“Java has slid only recently and barely while the much touted JVM languages aren’t even on the radar” – Comment from Dzone.com reader, click for full contextThe green line that is Java seems to be trending downward on a fairly regular basis since ’02. I’m not sure I’d refer to a 10 year decline as ‘recent’ in the technology industry. Again, I don’t think the Tiobe index is the ultimate indicator, but I wouldn’t point someone to this statistic to support an argument that Java is healthy.Objective-C wasn’t listed in 1997, was ranked #46 in 2007, and now stands at #3 on the index. If you had picked up Objective-C a few years ago, say in ’07 when it was not entirely popular, you would probably be doing well today as the demand for iOS work is quite high and the supply of developers is quite low. In ’97, Java was #5 – one spot behind VB and two spots behind COBOL.  ConclusionThe arguments against learning a new language or using a new language in production were probably the same back in the late nineties when Java was still new. People surely came to the defense of C and C++ saying that we didn’t need a new language then. It’s progress and subsequent resistance to change, and in the technology industry change can sneak up on you pretty quickly if you aren’t paying attention.I feel that many in the Java community may not be paying close attention.If you were a C++ programmer messing around with applets back in ’96, you’ve already been through this transition once. What I’m hearing now from experienced folks is that these alternative languages are for start-ups, “Trix are for kids!“. I know quite a few gray haired former Java developers that are getting paid to write code in other languages now, and I think they would tell you that the alternative language market isn’t just for kids. Were you using Java in a start-up back in the day – were you one of the kids?My purpose in writing these posts is to make a certain element of the Java community aware of what is out there, and that in my opinion now is an opportune time based on external market forces to explore other languages. This is not an attack on Java as a language or on the people that choose to write in Java. I’ve dedicated much of the past 12 years to the Java community and I don’t intend to change that now. I expect that I will be involved with Java professionals for several years, helping them to find jobs and scheduling great events for my JUG. I chose to change the focus of my business beyond Java, and my suggestion to Java professionals would be to at least consider and research doing the same.Reference: Advice From A JUG Leader II – Debate Breakdown from our JCG partner Dave Fecak at the Job Tips For Geeks blog....
java-logo

Project Lambda: To Multicore and Beyond

The presentation “Project Lambda: To Multicore and Beyond” (Session 27400 and not to be confused with Brian Goetz’s presentation of the same name) was given in the Hilton San Francisco Grand Ballroom B in the early afternoon on Monday at JavaOne 2011. Even with Grand Ballroom A closed off, this is an extremely large venue for a non-keynote session and there is a large camera (with camera operator) poised to film the presentation. This can probably be construed to mean that the conference organizers anticipated huge interest in coverage of Java SE 8 (JSR 337) and Project Lambda. Alex Buckley (Specification Lead for Java Language and Virtual Machine) and Daniel Smith (Project Lambda Specification Lead) were the presenters and their abstract for this presentation is shown next.This session covers the primary new language features for Java SE 8 – lambda expressions, method references, and extension methods – and explores how existing as well as future libraries will be able to take advantage of them to make client code simultaneously more performant and less error-prone.A functional interface is “an interface with one method.” A lambda expression is “a way to create an implementation of a functional interface.” Lambda expression allows “meat” of functionality to be simply and concisely expressed, especially when compared to the bloat of an anonymous class. Several slides included code examples showing how we’d do it today versus the more succinct representation supported by lambda expressions.Lambda expressions “can refer to any effectively final variables in the enclosing scope.” This means that the final keyword is not required, but rather than it needed to be treated as final (reference not assigned) in the method to be referenced by lambda expression. Some more rules of lambda expressions were announced: the this pointer references enclosing object rather than lambda expression. There is “no need for parameter types in a lambda expression” because they are “inferred based on the functional interface’s method signature” (no dynamic typing necessary). Method references support the “reuse” of “a method as a lambda expression.”Buckley talked about external iteration as the current predominate approach in Java libraries. In this idiom, the “client determines iteration” and is “not thread-safe.” He talked about disadvantages of introduction of a parallel for loop for solving this issue, but extracted some concepts from the parallel for approach: a “filter” and a “reducer.” Buckley introduced the idea that “internal iteration facilitates parallel idioms” because it does not need to be performed serially and is thread-safe.One of the issues Java 8 faces is the need to retrofit libraries to use lambda expressions, but they already have defined interfaces heavily used in the libraries and collections. One approach that might be used to deal with this issue is the use of static extension methods in Java similar to those available in C#. There are numerous advantages to this approach, but there are also some major disadvantages such as not being able to use reflection. The decision was made to revisit the “rule” that one “can’t add an operation to an interface.” Based on thism the subsequent decision was made to add virtual extension methods which provide default implementation in the interface that is used only when the receiver class does not override the method with a default implementation.The slide titled “Are you adding multiple inheritance to Java?!” stated that “Java always had multiple inheritance of types” and “now has multiple inheritance of behavior,” but still does not support “multiple inheritance of state, which causes most problems.” The slide added that “multiple inheritance of behavior is fairly benign” and is really a problem only when compilation occurs in multiple steps. It was emphasized in this presentation that extension methods are a language feature and a virtual machine feature (“everything else about inheritance and invocation is a VM feature!”). As part of this, a bullet stated, “invokeinterface will disambiguate multiple behaviors if necessary.” The non-Java JVM languages can “share the wealth” of extension methods and there was a slide providing three examples of this.Daniel Smith took over the presentation with the topic of parallel libraries. He showed a slide “Behold the New Iterable” which showed an Iterable interface with methods such as isEmpty(), forEach, filter, map, reduce, and into. He also showed a slide on a Parallelterable interface available from Iterable via extension method parallel().Smith provided references to JSR 335, JSR 166, and Project Lambda as part of his slide on community contributions. He also cited four additional sessions at JavaOne 2011 regarding lambda expressions and closely related topics. Smith ended with a quote from Brian Goetz on Project Lambda: …we believe the best thing we can do for Java developers is to give them a gentle push towards a more functional style of programming. We’re not going to turn Java into Haskell, nor even into Scala. But the direction is clear.  ConclusionSmith’s examples made it clear that lambda expressions will provide tremendous benefits to Java developers in their daily tasks. He showed the types of loops we’ve all had to write many hundreds or thousands of times and the cleaner, more concise syntax that lambda expressions make possible. This presentation has made it clear that, with the introduction of lambda expressions, Java will gain many of the benefits enjoyed by dynamically typed languages in terms of fluency and conciseness.Reference: JavaOne 2011: Project Lambda: To Multicore and Beyond from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
software-development-2-logo

Immediate gratification v/s delayed gratification in context of Software

This topic cuts across many different disciplines. But here I want to discuss it in context of software development and its process. Its a proven fact that when an individual focuses his efforts on long term goals he is laying down a foundation for quality life for far and near future. Actions that give immediate returns can hardly give any benefits in the long run. Few examples to put this in context of software process – 1. When an individual starts learning a new tool/process/method which is better than current one he/she faces slump in productivity (for e.g. TDD). This leads to an environment where managers starts thinking that change is not helping. Or simply they don’t have courage to face the initial loss of productivity for the sake of increased long term quality benefits. 2. Focus on process rather than product – Its not unusual that supervisor of a development team will over-emphasize on the product delivered rather than question the quality of process by which product is produced. What they are (un)conciously doing is, focusing on short term goal – they want to see a piece of functionality in action – immediately. If they delay the gratification and say, allow technical team to enforce processes/tools then that will ensure that all future deliverables are indeed quality deliverables. Because they are investing in something which will improve the process – which is responsible for the product. 3. Similar but one which has more drastic implications – before requirements can “sink” in, start the development/design. Today’s software methods and RAD tools allow requirements to change constantly during the project, but its important that requirements “sink” in the psyche of the technical team. I believe there is always a motive for coming up with a particular software requirement. That motive hardly changes, if developers are able to study and interact enough with requirements or producers of that requirements(client ?) they will catch the motive which is alway hidden and never communicated. If design/development happens focusing on that motive, the deliverables will be able to better accommodate requirement changes. Obviously the catch lies in deciding in when to stop being invested and take the yield. But unfortunately software teams today try to take the yield way before they have invested enough and hence they don’t get good enough yield. Reference: Immediate gratification v/s delayed gratification in context of Software from our JCG partner Advait Trivedi at the CoolCode blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books