Best oop questions in June 2012

Benefit of Polymorphism

51 votes

When I started to look for the benefits of polymorphism, I found with this question here. But here I was unable to find my answer. Let me tell what I want to find. Here I have some classes:

class CoolingMachines{
    public void startMachine(){
        //No implementationion
    }
    public void stopMachine(){
        //No implementationion
    }
}

class Refrigerator extends CoolingMachines{
    public void startMachine(){
        System.out.println("Refrigerator Starts");
    }
    public void stopMachine(){
        System.out.println("Refrigerator Stop");
    }
    public void trip(){
        System.out.println("Refrigerator Trip");
    }
}

class AirConditioner extends CoolingMachines{
    public void startMachine(){
        System.out.println("AC Starts");
    }
    public void stopMachine(){
        System.out.println("AC Stop");
    }
}

public class PolymorphismDemo {
    CoolingMachines cm = new Refrigerator();
    Refrigerator rf = new Refrigerator();
}

Now here I created two objects in the Demo class and are references of Refrigerator. I have completely understood that from the rf object I am able to call the trip() method of Refrigerator, but that method will be hidden for the cm object. Now my question is why should I use polymorphism or why should I use

CoolingMachines cm = new Refrigerator();

when I am OK with

Refrigerator rf = new Refrigerator();

Is polymorphic object's efficiency is good or light in weight? What is the basic purpose and difference between both of these objects? Is there any difference between cm.start(); and rf.start()?

It is useful when you handle lists... A short example:

List<CoolingMachines> coolingMachines = ... // a list of CoolingMachines 
for (CoolingMachine current : coolingMachines) {
    current.start();
}

Or when you want to allow a method to work with any subclass of CoolingMachines

Why I should go for Interfaces in C# when I can implement the methods directly

15 votes

I am aware that this is a very basic question, but an interviewer asked me very trick way. I was helpless :(

I know only material or theoretical definition for an interface and also implemented in many projects I worked on. But I really don't understand why and how is this useful.

I also dont understand one thing in interface. i.e for example, we use

conn.Dispose(); in finally block. But I dont see that class is implementing or inheriting IDisposable interface (SqlConnection) class I mean. I am wondering how I can just call the method name. Also in the same thing, I am not understanding how Dispose method work as because, we need to implement the function body with our own implementation for all interface methods. So how Interfaces are accepted or named as contracts ? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.

MSDN asusual looks very scary and no single line is clear there (Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use).

The interviewer said:

He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand "Why Interface" in general. "Why abstract class" in general even if I can implement the same methods only one time and not gona change it.

I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning. I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly.

Interfaces are excellent when you want to create something like it:

 using System;

namespace MyInterfaceExample
{
    public interface IMyLogInterface
    {
        //I want to have a especific method that I'll use in MyLogClass
        void WriteLog();       
    }

    public class MyClass:IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyClass was Logged");
        }
    }

    public class MyOtherClass :IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyOtherClass was Logged");
            Console.Write("And I Logged it different, than MyClass");
        }
    }

    public class MyLogClass
    {
        //I created a WriteLog method where I can pass as parameter any object that implement IMyLogInterface.
        public static void WriteLog(IMyLogInterface myLogObject)
        {
            myLogObject.WriteLog(); //So I can use WriteLog here.
        }
    }

    public class MyMainClass
    {
        public void DoSomething()
        {
            MyClass aClass = new MyClass();
            MyOtherClass otherClass = new MyOtherClass();

            MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation
            MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log.
        }
    }
}

In my example, I could be a developer who write MyLogClass, and the other developers, could create they classes, and when they wanted to log, they implement the interface IMyLogInterface. It is as they were asking me what they need to implement to use WriteLog method in MyLogClass. The answer they will find in the interface.

Is it OK for a factory method to return null?

14 votes

I'm wondering about best practice here. Is it good practice for a factory method to return null if it can't create anything? Here's an example:

ICommand command = CommandFactory.CreateCommand(args);
if (command != null)
    command.Execute();
else
    // do something else if there is no command

An alternative would be to return a NullCommand or something, I guess, but what is best practice?

I think it's potentially reasonable for a factory method to return null in some situations, but not if it's a method called CreateCommand. If it were GetCommand or FetchCommand, that might be okay... but a Create method should throw an exception on failure, I would suggest.

Whether you really want it to return null in this situation depends on the bigger picture, of course. (Is there a reasonable null object implementation you could return instead, for example?)

MySQL PDO - What should be inside the try { block }?

10 votes

So I'm working on learning PDO, and making the transfer from the standard PHP MySQL functions. However, I have a question. Regarding the try {} blocks, what exactly should be in them, and what should go outside it?

Should everything that uses $sth-> ... be inside try {}? Should it just be from when the statement is first prepared all the way to when it is executed? Even less than that?

Any help would be greatly appreciated. :)

Here is an example method I have in a class. Is it organized properly? Notice how I put everything inside try {}. Is that wrong? It feels incorrect to me, but I'm not sure how I should change it.

protected function authorized()
{
    try
    {
        // Attempt to grab the user from the database.
        $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

        $sth->bindParam(':user_id', $this->user_id);
        $sth->execute();

        // Check if user exists in database.
        if ($sth->fetch()->num_rows > 0)
        {
            // User exists in database, and is therefore valid.
            return TRUE;
        }
        else
        {
            // User does not exist in database, and is therefore invalid.
            return FALSE;
        }
    }
    catch (PDOException $e)
    {
        pdo_error($e);
    }
}

The try catch should be outside the function.

<?php

protected function authorized() {
    // Attempt to grab the user from the database.
    $sth = $dbh->prepare("
            SELECT COUNT(*) AS num_rows
            FROM users
            WHERE user_id = :user_id
            ");

    $sth->bindParam(':user_id', $this->user_id);
    $sth->execute();

    // Check if user exists in database.
    if ($sth->fetch()->num_rows > 0) {
        // User exists in database, and is therefore valid.
        return TRUE;
    }
    else {
        // User does not exist in database, and is therefore invalid.
        return FALSE;
    }
}

...

try {
    authorized()
}
catch (PDOException $e) {
    pdo_error($e);
}

Don't handle exceptions inside of the methods. You try the method and catch the resulting exception if it happens.