Thursday, July 28, 2011

Good Programmers Make Bad Designers


 Good Programmers Make Bad Designers

Do Not Get a Good Programmer to be a Systems Analyst, Software Engineer or Software Architect
When you are on the lookout for someone who will occupy the coveted position of Software Architect or Designer in your team or company, the first thing that usually comes to mind is to hire the best programmer that you can afford. Don’t. Avoid hiring good programmers for the position. Promoting one of your senior programmers for it is just as bad.
It might sound weird at first. Why should I not get a good programmer to design solutions? After all, she will be designing programs, won’t she? Actually, yes, she will be. But the thing to remember is that designing programs requires a totally different skillset than writing programs or programming.
Let us see why a good programmer will not be a good software designer. But first, let us ask ourselves what makes a programmer good, or even brilliant. To be a good programmer, you must be able to implement real world, critical software. Being able to write a simple text editor is simply not enough.
To be capable of implementing non-trivial, complex programming problems, a programmer needs to have years of experience in a particular programming language. This means she has to focus on this language in order to be fluent in it and to be familiar with its idioms. Herein lies the problem.
To Someone Who Only Has a Hammer, Every Problem Begins to Resemble a Nail
If you focus only on one language to gain proficiency in it, you will be restricted to the paradigm of the problem domain for which your language was designed. In short, if all you know is PHP, then every programming problem starts to look like Web development problems. In the same manner, if Java is all you know, you will try to approach every problem from the object-oriented standpoint even if the problem is better solved using procedural programming as in the majority of systems programming.
Knowing only one or even two programming languages as good programmers should, will severely limit your capability to solve problems. For example, if your language is C, you will find it very difficult to think of the problem at hand in an object-oriented way because your programming language does not readily provide that functionality. Unlike Haskell programmers, C++ programmers cannot approach a problem the functional way either. Whether your programming language offers structs and enums or not can greatly affect how you attempt to dissect the problem. If your language is inadequate or if you only know a few languages, your ability to solve problems efficiently will likewise be hampered.
Language Shapes the Way We Think
Some say that our language shape how we think and perceive the world. I tend to agree. A speaker whose language requires that the gender of nouns be specified obviously thinks differently than someone who thinks that the police are not feminine. Someone who speaks a language that does not distinguish the color Blue from the color Green obviously perceives the world differently compared to a person whose language does.
If we look back at the Trivium, they are described as follows: Grammar deals with how concepts and objects are represented in writing and in speech so that they may be dissected in thought using Logic and thereafter communicated to another mind with the aid of Rhetoric. For our purposes, grammar is the syntax of our programming language. If our language is inadequate, we will also have an incomplete view of objects and concepts and how they are represented.
Language, the kind we use to talk to humans and to computers, clearly affects how we think. The richness and number of the languages we know can either aid or hinder our problem solving capability.
So, Who Would Be a Better Fit?
Therefore, a good programmer, who is a specialist in one or two programming languages, will have limitations in approaching a problem. She is restricted to what her programming language allows her to do. As such, she cannot be a good designer or analyst.
But if we shouldn’t hire a good programmer, who could we call upon to design our software? Certainly not someone who doesn’t know programming at all? Certainly not, but we need someone who is a generalist. A good designer must be familiar with procedural, object-oriented, functional, and logic programming languages—not to mention good software engineering practices. She must not be tied to a single paradigm like the specialist. Of course, she cannot write a complex program herself because of her broad but shallow approach to learning programming languages; nevertheless, she can properly determine the right tool for the task. If the problem is a nail, she can bring someone in who is well versed with a hammer; if the problem is a boulder, well, she could call in the explosive ordnance division instead of pounding it up futilely with a hammer.

Tuesday, July 26, 2011

Principles of Good Programming


The principles of good programming are closely related to principles of good design and engineering. The following programming principles have helped me over the years become a better programmer, and I believe can help any developer become more efficient and to produce code which is easier to maintain and that has fewer defects.
DRY - Don’t repeat yourself - This is probably the single most fundamental tenet in programming is to avoid repetition. Many programming constructs exist solely for that purpose (e.g. loops, functions, classes, and more). As soon as you start repeating yourself (e.g. a long expression, a series of statements, same concept) create a new abstraction. http://en.wikipedia.org/wiki/Don%27t_repeat_yourself
Abstraction Principle - Related to DRY is the abstraction principle “Each significant piece of functionality in a program should be implemented in just one place in the source code.” http://en.wikipedia.org/wiki/Abstraction_principle_(programming)
KISS (Keep it simple, stupid!) - Simplicity (and avoiding complexity) should always be a key goal. Simple code takes less time to write, has fewer bugs, and is easier to modify. http://en.wikipedia.org/wiki/KISS_principle
Avoid Creating a YAGNI (You aren’t going to need it) - You should try not to add functionality until you need it. http://en.wikipedia.org/wiki/YAGNI
Do the simplest thing that could possibly work - A good question to ask one’s self when programming is “What is the simplest thing that could possibly work?” This helps keep us on the path towards simplicity in the design. http://c2.com/xp/DoTheSimplestThingThatCouldPossiblyWork.html
Don’t make me think - This is actually the title of a book by Steve Krug on web usability that is also relevant in programming. The point is that code should be easily read and understood with a minimum of effort required. If code requires too much thinking from an observer to understand, then it can probably stand to be simplified http://www.sensible.com/dmmt.html
Open/Closed Principle - Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. In other words, don't write classes that people can modify, write classes that people can extend. http://en.wikipedia.org/wiki/Open_Closed_Principle
Write Code for the Maintainer - Almost any code that is worth writing is worth maintaining in the future, either by you or by someone else. The future you who has to maintain code often remembers as much of the code, as a complete stranger, so you might as well always write for someone else. A memorable way to remember this is “Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.” http://c2.com/cgi/wiki?CodeForTheMaintainer
Principle of least astonishment - The principle of least astonishment is usually referenced in regards to the user interface, but the same principle applies to written code. Code should surprise the reader as little as possible. The means following standard conventions, code should do what the comments and name suggest, and potentially surprising side effects should be avoided as much as possible. http://en.wikipedia.org/wiki/Principle_of_least_astonishment
Single Responsibility Principle - A component of code (e.g. class or function) should perform a single well defined task. http://en.wikipedia.org/wiki/Single_responsibility_principle
Minimize Coupling - Any section of code (code block, function, class, etc) should minimize the dependencies on other areas of code. This is achieved by using shared variables as little as possible. “Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability” http://en.wikipedia.org/wiki/Coupling_(computer_programming)
Maximize Cohesion - Code that has similar functionality should be found within the same component. http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Hide Implementation Details - Hiding implementation details allows change to the implementation of a code component while minimally affecting any other modules that use that component. http://en.wikipedia.org/wiki/Information_Hiding
Law of Demeter - Code components should only communicate with their direct relations (e.g. classes that they inherit from, objects that they contain, objects passed by argument, etc.) http://en.wikipedia.org/wiki/Law_of_Demeter
Avoid Premature Optimization - Don’t even think about optimization unless your code is working, but slower than you want. Only then should you start thinking about optimizing, and then only with the aid of empirical data. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" - Donald Knuth. http://en.wikipedia.org/wiki/Program_optimization
Code Reuse is Good - Not very pithy, but as good a principle as any other. Reusing code improves code reliability and decrease development time. http://en.wikipedia.org/wiki/Code_reuse
Separation of Concerns - Different areas of functionality should be managed by distinct and minimally overlapping modules of code. http://en.wikipedia.org/wiki/Separation_of_concerns
Embrace Change - This is the subtitle of a book by Kent Beck, and is also considered a tenet of extreme programming and the agile methodology in general. Many other principles are based on the concept that you should expect and welcome change. In fact very old software engineering principles like minimizing coupling are related directly to the requirement of making code easier to change. Whether or not you are an extreme programming practitioner, this approach to writing code just makes sense.

Thursday, July 21, 2011

Style of android app


Styles and Themes

October 27th, 20090 Comments and 0 Reactions
Hello coders,
Lets look at a fairly simple example of creating a transparent theme and how to apply it to a Dialog……
Step 1> Create a colors.xml file in the ‘values’ folder under ‘res’ and add the following line..
<drawable name="transparent">#00000000</drawable>
Step 2> Create a styles.xml file in the ‘values’ folder under ‘res’ and the following lines…
<style name="Transparent">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">
@android:style/Animation.Translucent
</item>
<item name="android:windowBackground">@drawable/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#fff</item>
</style>
( I guess the tags and attributes are self explanatory …. )
Step 3> Actually thats it……………………
Let’s add this to a dialog…..
Step 4> Create a class with the following lines……
public class DialogBox extends Dialog {

    public DialogBox(Context context, int theme) {
        super(context, theme);
        setContentView(R.layout.dialog);
        okButton = (Button) findViewById(R.id.dialog_OkButton);
        setListeners();
    }
}
(Make sure you create a layout for the dialog )
Step 5> Next create an activity class as follows….
public class T_Temp extends Activity {

    private DialogBox dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dialog = new DialogBox(this, R.style.Transparent);
        dialog.show();
    }
}
When creating the dialog just add the transparent theme ……
Step 6> That’s it …
( don’t forget to add the activity in the android manifest file..)
When you add the widgets and background it will look something like this..
before
Before
after
After
Step 7> Another trick is you can make the background blurred ….
just add the following line in the dialog box…
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
Output looks somthing like this…….
blurred
So the final code is:
public class DialogBox extends Dialog {

    public DialogBox(Context context, int theme) {
        super(context, theme);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
        setContentView(R.layout.dialog);
        okButton = (Button) findViewById(R.id.dialog_OkButton);
        setListeners();
    }
}

Create Thumbnail image in android



ImageThumbnailsActivity is the main Activity.

AndroidManifest.xml
--------------------
<?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="image.Thumbnails" android:versionCode="1" android:versionName="1.0.0">
      < uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
      < application android:icon="@drawable/icon" android:label="@string/app_name">
            < activity android:name=".ImageThumbnailsActivity"
                  android:label="@string/app_name">
                  < intent-filter>
                        < action android:name="android.intent.action.MAIN" />
                        < category android:name="android.intent.category.LAUNCHER"/>
                  </intent-filter>
            </activity>
            < activity android:name=".ViewImage">
                  < intent-filter>
                        < action android:name="android.intent.action.VIEW" />
                        < category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </activity>
      </application>
</manifest>

package image.Thumbnails;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class ImageThumbnailsActivity extends Activity {
      /** Called when the activity is first created. */
      private Cursor imagecursor, actualimagecursor;
      private int image_column_index, actual_image_column_index;
      GridView imagegrid;
      private int count;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            init_phone_image_grid();
      }
      private void init_phone_image_grid() {
            String[] img = { MediaStore.Images.Thumbnails._ID };
            imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
            image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            count = imagecursor.getCount();
            imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
            imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
            imagegrid.setOnItemClickListener(new OnItemClickListener() {
                  public void onItemClick(AdapterView parent, View v,
int position, long id) {
                        System.gc();
                        String[] proj = { MediaStore.Images.Media.DATA };
                        actualimagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
                        actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToPosition(position);
                        String i = actualimagecursor.getString(actual_image_column_index);
                        System.gc();
                        Intent intent = new Intent(getApplicationContext(), ViewImage.class);
                        intent.putExtra("filename", i);
                        startActivity(intent);
                  }
            });
      }


      public class ImageAdapter extends BaseAdapter {
            private             Context mContext;
            public ImageAdapter(Context c) {
                  mContext = c;
            }
            public int getCount() {
                  return count;
            }
            public Object getItem(int position) {
                  return position;
            }
            public long getItemId(int position) {
                  return position;
            }
            public View getView(int position,View convertView,ViewGroup parent) {
                  System.gc();
                  ImageView i = new ImageView(mContext.getApplicationContext());
                  if (convertView == null) {
                        imagecursor.moveToPosition(position);
                        int id = imagecursor.getInt(image_column_index);
                        i.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ id));
                        i.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        i.setLayoutParams(new GridView.LayoutParams(92, 92));
                  }
                  else {
                        i = (ImageView) convertView;
                  }
                  return i;
            }
      }
}

// By selecting the thumbnails user can view the actual image.
package image.Thumbnails;

import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ViewImage extends Activity {
      private String filename;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            Intent i = getIntent();
            Bundle extras = i.getExtras();
            BitmapFactory.Options bfo = new BitmapFactory.Options();
            bfo.inSampleSize = 2;
            filename = extras.getString("filename");
            ImageView iv = new ImageView(getApplicationContext());
            Bitmap bm = BitmapFactory.decodeFile(filename, bfo);
            iv.setImageBitmap(bm);
            setContentView(iv);
      }
}



//main.xml

< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
< GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/PhoneImageGrid" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:numColumns="auto_fit"
android:verticalSpacing="10dp" android:horizontalSpacing="10dp"
android:columnWidth="90dp" android:stretchMode="columnWidth"
android:gravity="center" />
< /LinearLayout>

Wednesday, July 20, 2011

list view with images beside

This is a simple tutorial on how to populate android list view, with text and image as shown in figure. If in your application image and text come from web services, then you should make it dynamic. For simplicity i have taken static data, but you can using this method make it dynamic. First create a new project as shown below.
Click File -> New -> Project and select the ‘Android Project’ wizard, Click next and fill out form you can give name main activity like “listActivity”, Once you have filled out all the necessary data you can click finish.
Your new project has just been created. Now lets modify it a bit to display our custom made list. Open main.xml amd make changes as shown below.





<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

make sure that id of ListView be ‘list’ otherwise it will cause error. Now, open listActivity.java or main Activity. Define necessary member variables, we will use that later in our class as shown below.
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
Vector is an implementation of List, backed by an array and synchronized. All optional operations including adding, removing, and replacing elements are supported. LayoutInflater class is used to instantiate layout XML file into its corresponding View objects. Use getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example,
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
The whole listAvtivity.java should be like following,
public class listAvtivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
     "*New*Apple iPad Wi-Fi (16GB)", "7 Touch Tablet -2GB Google Android", 
"Apple iPad Wi-Fi (16GB) Rarely Used ","Apple iPad Wi-Fi (16GB) AppleCase"     };
static final String[] detail = new String[] {
  "1h 37m Shipping: $10.00","1h 39m Shipping: Free","58m 6s Shipping: 
$10.00","59m 30s Shipping: $10.95" };
private Integer[] imgid = {
  R.drawable.bsfimg,R.drawable.bsfimg4,R.drawable.bsfimg2,
  R.drawable.bsfimg5
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
  rd = new RowData(i,title[i],detail[i]);
    } catch (ParseException e) {
     e.printStackTrace();
   }
   data.add(rd);
}
   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.title, data);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,
                                                                long id) {         
   Toast.makeText(getApplicationContext(), "You have selected "
                    +(position+1)+"th item",  Toast.LENGTH_SHORT).show();
}
       private class RowData {
       protected int mId;
       protected String mTitle;
       protected String mDetail;
       RowData(int id,String title,String detail){
       mId=id;
       mTitle = title;
       mDetail=detail;
    }
       @Override
       public String toString() {
               return mId+" "+mTitle+" "+mDetail;
       }
}
  private class CustomAdapter extends ArrayAdapter<RowData> {
  public CustomAdapter(Context context, int resource,
                        int textViewResourceId, List<RowData> objects) {               
 super(context, resource, textViewResourceId, objects);
}
      @Override
       public View getView(int position, View convertView, ViewGroup parent) {   
       ViewHolder holder = null;
       TextView title = null;
       TextView detail = null;
       ImageView i11=null;
       RowData rowData= getItem(position);
       if(null == convertView){
            convertView = mInflater.inflate(R.layout.list, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
 }
             holder = (ViewHolder) convertView.getTag();
             title = holder.gettitle();
             itle.setText(rowData.mTitle);
             detail = holder.getdetail();
             detail.setText(rowData.mDetail);                                                     
             i11=holder.getImage();
             i11.setImageResource(imgid[rowData.mId]);
             return convertView;
}
            private class ViewHolder {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row) {
            mRow = row;
 }
         public TextView gettitle() {
             if(null == title){
                 title = (TextView) mRow.findViewById(R.id.title);
                }
            return title;
         }     
         public TextView getdetail() {
             if(null == detail){
                  detail = (TextView) mRow.findViewById(R.id.detail);
                    }
           return detail;
         }
        public ImageView getImage() {
             if(null == i11){
                  i11 = (ImageView) mRow.findViewById(R.id.img);
                                      }
                return i11;
        }
     }
   } }
You will need list.xml, that will generate the layout of our application as shown in image. it is as shown below. If you have any query then please write comment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/img"
android:scaleType="centerCrop"
android:layout_width="70dp"
android:layout_height="70dp"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="fill_parent"
android:id="@+id/title"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16sp" />
<TextView
android:layout_width="fill_parent"
android:id="@+id/detail"
android:textColor="#ffffff"
android:layout_height="wrap_content"
</LinearLayout>
</LinearLayout>
 ------------Basha______________
basha0543@gmail.com