Ping Blog Easy Techs!

Pages

Saturday, December 22, 2012

Observer Design Pattern: A better approach to OOP


Object oriented programming makes it way too easy to model real world processes and put them in the programmer’s language, the source code. The source code of any application is the black box for the state and behavior of an application in the real time. Although OOP is a great leap towards programming in real time, it could be made way too easier if we could think of few important aspects of programming. One of the important features of OOP is inheritance, which is a powerful tool to manage and manipulate behavior in large, enterprise class applications. But, inheritance too could be tiresome if we have a better way to reduce the code and make it easier to manage.

Signatures via interfaces:

While we are onto implementing code reusability in our program, we are required to create a base class from which every other class could be inherited. This would be like making a ‘mama-class’ in our object and then making her give birth to a new class, every time we need, just to suit our context and purpose. But this concept of signatures makes the use of an interface, which is basically a class with the behaviors mentioned in it without the precise definition of each behavior. You could think of it as this, in an application of vehicles, we define a vehicle interface with the functions of Start(), GoForward(), GoBackward(), Stop() etc. These functions are just what we need of a vehicle. For now, in an interface, we just mention what is required of the vehicle object and not the specifications of how and what-if conditions. Later on, on every new object such as cars, jeeps or SUVs, we will define how each of the functions is accomplished.

A classical OOP genius would argue this method of being long and tedious as we are required to put up the definition in every object that we create of the vehicle type. Inheritance would just require the definition of the function only once, in the base class, and later it could be used directly. But, if I made a abject, Motorcycle then simply inheriting would allow the Motorcycle object to move backwards as well, while in the real world, motorbikes DO NOT have the reverse gear system. Bam!

Okay, now while we agree to use signatures over inheritance, it would be better if we would not require the functions to define in each new object that we define along the way, wouldn’t it? And that is just what could be done using segregation process.

Code segregation:

If you’ve got some aspect of your code that is changing, say with every new requirement, then you know you have got a behavior that needs to be pulled out and separated from all the stuff that doesn’t change. (Head First Design Pattern, Freeman & Freeman, 2004). This means to tell us that things could be made a lot simpler if we separated the varying features of our class and each of the features that varies be given a signature. Hence, in the above example, the GoBackward() method is redefined in a new interface, say ReverseMovement(). Now, what we could do is, design a class that implements the ReverseMovement() behavior down to its details. In this way, now if we needed GoBackward() function at any instance of our class, all we need to do is inherit the ReverseMovement() class, just as in classical OOP approach. This way, the changeable feature is now only a few blocks away than being locked up in the base class ‘vehicles’.

Ding! While I talk about the signatures and interfaces, a thing might pop-up in your brains called the “Abstact Class”. There is a question, could this implementation not be done using abstract classes? One possible answers could be why waste $100 in an Xbox if you can get it for 15 bucks? Defining interfaces ensures the CUP is least utilized and the memory is optimally occupied by other relevant processes. Interfaces allow us to remain care free about the type of object that is required to be instantiated at runtime, thus giving us the dynamic flexibility.


 

Wednesday, December 19, 2012

Timer demo in Windows 8 Application using C#

I needed a timer to pop in one of my windows 8 applications and I tried to get sample codes on the web. The codes in there were helpful but way too difficult to track down. So, I thought of writing a small code snippet of my own and sharing it to whoever it may concern to!
In this little code snippet, the user is supposed to input any random text in the text box input that appears on the UI with in 5 seconds or else the UI tells the time is up! I have not used any pop us or any logical scenario implementation in here. The whole idea of this is to help you understand how you can implement the timer into your project. Once you get a hold of the concept, I am sure you have your own 'logical scenario of implementation' that is far more important.
Here is the XAML code for the UI design.

<Page
    x:Class="timerDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:timerDemo"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBox x:Name="inputBox" HorizontalAlignment="Left" Height="40" Margin="110,239,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="248" FontSize="24"/>
        <TextBlock x:Name="timeRemaining" HorizontalAlignment="Left" Margin="751,87,0,0" TextWrapping="Wrap" Text="Time Left = " VerticalAlignment="Top" Height="46" Width="151" FontSize="26"/>
        <TextBox x:Name="showTime" HorizontalAlignment="Left" Margin="907,87,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
        <TextBlock x:Name="outputBox" HorizontalAlignment="Left" Margin="110,194,0,0" TextWrapping="Wrap" Text="Your Input Here" VerticalAlignment="Top" Height="40" Width="378" FontSize="24"/>
        <Button x:Name="clickButton" Content="Click Me!" HorizontalAlignment="Left" Margin="163,336,0,0" VerticalAlignment="Top" Click="clickButton_Click" />
    </Grid>
</Page>
This code simply creates two text boxes, two text blocks and a button, like the one shown in the figure:

Here is the code required for the respective .cs file

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace timerDemo
{
    public sealed partial class MainPage : Page
    {
        private int timeLeft;
        private DispatcherTimer timer;
        public MainPage()
        {
            timeLeft = 5;
            this.InitializeComponent();
            startMyTimer();
        }
        /// <summary>
        /// this method here starts the timer
        /// </summary>
        private void startMyTimer()
        {
            if (this.timer != null)
            {
                this.timer.Stop();
                this.timer = null;
            }
            //create a new DispatcherTimer type of object
            timer = new DispatcherTimer();
            //set the interval between two timer ticks. Here it 1 s.
            //the format is hr.min.sec
            //if you put (0,2,0) your timer will change in every two minutes
            timer.Interval = new TimeSpan(0, 0, 1);
            //this one here is event
            timer.Tick += timer_tick;
            //kick off the timer
            timer.Start();
           
        }
        public void timer_tick(object sender, object args)
        {
            if (timeLeft > 0)
            {
                timeLeft -= 1;
                this.showTime.Text = Convert.ToString(timeLeft);
            }
            else
            {
                timer.Stop();
                //check if the time is up!
                outputBox.Text = "Your Time is up!";
            }
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
        private void clickButton_Click(object sender, RoutedEventArgs e)
        {
            //check after the button is ticked
            if (timeLeft == 0 && inputBox.Text == "")
                outputBox.Text = "You are out of time";
            else
                outputBox.Text = "You have supplied input in time";
        }
      
    }
}

Wednesday, November 28, 2012

NetBeans IDE would not install in my Windows 8

It has been a while that I have installed Windows 8 on my machine and I have had a truck load of problems already.  A while ago, my volume controls were too slow to use ( Remedy Here) and the other day I had problems uploading images on my blog through IE 10 ( Read here) and now I am stuck because I cannot install NetBeans IDE on my system. I wanted to do some java stuff and I got NetBeans 7 for myself. I downloaded JDK 6 too and installed it prior to the installation of NetBeans 7. The error was as below:
I had never had to look into the 'Environment Variables' stuffs before while I was on Windows 7. But now, until I played with the Environment Variables, the problem would not go. Here is the step by step demonstration of how you can fix the problem:
Go to my computer:

Right Click the mouse button to go to the Properties:

Click the Advanced System Settings button on the left of the new page:

Now, under the Advanced tab, click Environment Variables
 

Find Path on the new window and click to edit it.

Then you can go ahead and add the path of your JDK file. The format would be like this:
C:\Program Files\Java\jdk1.6.0_27\bin
You need to enter the path till the bin folder. DO NOT OVERWRITE THE PATH CONTENTS, JUST ADD TO WHATEVER IS ALREADY THERE.


Close the windows and restart your system. Now you may go ahead and install your IDE and that should not be a problem. 

Happy Coding!:)