jeudi 1 octobre 2015

Best way to implement similar methods of two different classes?

I have two classes (A and B) which implements the same interface (I) in C#. The interface have 5 methods to implement. Implementations of two of those methods are almost the same in both A and B except each implemetation uses a different variable. Here is the abstract layout of my classes.

class A : I
{
     Folder folder;
     void method()
     {
        //implementation uses ``folder``
     }

class B : I
{
     List list;
     void method()
     {
        //implementation uses ``list``
     }
}

Because the implementation of Method is the same (except the one parameter) I want to have implement Method only once. What is the best solution according of design patterns? one simple option is to define a third class which implements Methodand takes one parameter (either list or folder) and then call it within the Mathod of A and B. Any other solution?

Any reason for newer programmers to avoid design patterns?

I was reading an article that was linked from the CodeProjects blog that lambasted the overuse of design patterns by newer programmers when writing code. I will try to find a link and add it later, but I read it a bit ago and the question has just been bothering me. The argument from the article was something along the lines of:

"Green programmers tend to use a lot of design patterns instead of following KISS principles and just coding for the problem at hand"

I have also read that some believe that using design patterns restricts the creativity of the programmer, which also is a little but of a strange argument.

My question to the wonderful programmers of stack overflow who are more experienced than I is: does this ring true? Do you find that newer programmers who utilize design patterns often overuse them and force them into places where they shouldn't be used? If so, what is your advice (besides "code more") to better understand where and when to use patterns in programming?

Cast Object at Runtime Depending on Instance Variable (C++)

I'm trying to represent a 2 dimensional map of objects. So I have a two-dimensional array of "MapItems":

MapItem world_map[10][10];

In my specific situation, these MapItems are going to be used to represent Drones, Static Objects (like trees or any obstruction that doesn't move), or empty positions (these objects will be subclasses of MapItem):

class Drone : public MapItem {
  int droneId;
  ...
}

class StaticObject : public MapItem {
  ...
}

class EmptyPosition : public MapItem {
  int amount_of_time_unoccupied;
  ...
}

Is it a good idea to have an instance variable on the MapItem class that tells what specific type of item it is, and then cast it the proper type based on that? For example:

enum ItemType = {DRONE, STATIC_OBSTRUCTION, EMPTY};
class MapItem {
  ItemType type;
  ...
}

And then when I want to know what is at a position in the map, I do:

MapItem item = world_map[3][3];
if (item.type == DRONE) {
  Drone *drone = dynamic_cast<Drone*>(&item);
  // Now do drone specific things with drone
  ...
} else if (item.type == STATIC_OBSTRUCTION) {
  StaticObject *object = dynamic_case<StaticObject*>(&item);
  // Static object specific stuff
  ...
} else {
  ...
}

I have not actually tried this, but I assume it's possible. What I'm really asking is this a good design pattern? Or is there a better way to do this?

client-server application desgin patters

I'm building both a client and server side application. it is a messaging/communication program. Currently the client side application is designed to accept either markup and/or text files that represent the requested information, as well as accept a streamed/downloaded file which represents message content (images, videos, etc), and also performs these processes in reverse in the case of sending messages, requesting lists, etc.

The server side of the application consists of python scripts and modules that read, write, and store files and information based on the requested action. The server itself would have to communicate with external dependencies outside of the python libraries (postgresql).

How could I deploy this program in a way that allows it to communicate via the requests and responses of HTTP and be serviceable by the client application programs?

Abstract Factory Design Pattern use

I am trying to learn creational design patterns, and i think i understand Factory pattern now. But on moving to Abstract Factory Pattern, I couldn't find its use. I know i miss something with this, but no idea where.

In Abstract Factory Pattern we will have a an Abstract Factory, and Concrete Factories wil return the instance. Suppose we are dealing with creation of Cars. We will have an Abstract Factory like

public interface CarFactory{
    public Car getCar();
}

And our concrete Factories will be something like

public class AudiFactory{
    public Car getCar(){
        return new Audi();
    }
}

public class VolvoFactory{
    public Car getCar(){
        return new Volvo();
    }
}

And in user class we will use it like

CarFactory factory = new AudiFactory();
Car carAudi = factory.getCar();
factory = new VolvoFactory();
Car carVolvo = factory.getCar();

I think we can build the same functionality using Factory Pattern too

public class CarFactory{

    public Car getCar(String make){
    if("Audi".equals(make))
        return new Audi();
    else if("Volvo".equals(make))
        return new Volvo();
    }
}

And in user class we can

CarFactory factory = new CarFactory();
Car carAudi = factory.getCar("Audi");
Car carVolvo = factory.getCar("Volvo");

If my understanding is correct(please correct me if its wrong), Why we need another design pattern for this?

Is this correct way to write factory and adapter pattern

I am trying to use adapter and factory pattern which i am trying to learn but not sure about correct way of using them in real scenario.

Below is one console application for writing log in three difference part.

Thanks in advance.

This is console application

class Program
{
    static void Main(string[] args)
    {
        LogWriterFactory _LogWriterFactory = new LogWriterFactory();

        var data = _LogWriterFactory.SaveData(SaveOption.Database, "Something");
        var email= _LogWriterFactory.SaveData(SaveOption.Email, "Something");
        var text = _LogWriterFactory.SaveData(SaveOption.Text, "Something");

        Console.WriteLine("{0}", data);
        Console.WriteLine("{0}", email);
        Console.WriteLine("{0}", text);
        Console.ReadKey();
    }
}

This is Class Library

public enum SaveOption
{
    Database = 1,
    Email = 2,
    Text = 3
}

public class LogWriterFactory
{
    public string SaveData(SaveOption option, string Log = "")
    {
        LogWriterAdp _LogWriterAdp = new LogWriterAdp();
        string output;
        switch (option)
        {
            case SaveOption.Database:
                IConnector _SendEmailConnector= new SendEmailConnector();
                output = _LogWriterAdp.Write(_SendEmailConnector, Log);
                break;
            case SaveOption.Email:
                IConnector _WriteInDBConnector = new WriteInDBConnector();
                output = _LogWriterAdp.Write(_WriteInDBConnector , Log);
                break;
            case SaveOption.Text:
                IConnector _WriteInTextConnector= new WriteInTextConnector();
                output = _LogWriterAdp.Write(_WriteInTextConnector, Log);
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
        return output;
    }
}

public class LogWriterAdp
{
    public string Write(IConnector Connector, string Log)
    {
        return Connector.Save(Log);
    }
}

public interface IConnector
{
    string Save(string Log);
}

public class SendEmailConnector : IConnector
{
    public string Save(string Log)
    {
        SendEmail _SendEmail = new SendEmail();
        return _SendEmail.Send(Log);
    }
}

public class WriteInDBConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInDB _WriteInDB = new WriteInDB();
        return _WriteInDB.Save(Log);
    }
}

public class WriteInTextConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInText _WriteInText = new WriteInText();
        return _WriteInText.Write(Log);
    }
}

public class SendEmail
{
    public string Send(string Log)
    {
        return "Data From DatabaseHelper " + Log;
    }
}

public class WriteInText
{
    public string Write(string Log)
    {
        return "Data From WebSiteScanner " + Log;
    }
}

public class WriteInDB
{
    public string Save(string Log)
    {
        return "Data From XmlFileLoader " + Log;
    }
}

Output

I am trying to use adapter and factory pattern which i am trying to learn but not sure about correct way of using them in real scenario.

Need help in finding a regex in Java to capture date with all formats in a string

I have a string with format given below, i want to capture the date from this string and then later parse it with a proper date format.

sometext username, 19/05/1985: some more text
sometext username2, 19-Sep-1985 23:59:59: some more text

Assumptions:

  1. username will always succeeded by a coma ","
  2. A date always ends with a colon
  3. There may more text before and after the username and date strings.