dimanche 2 juillet 2017

Is it possible to call override function with different type of pointers in C++?

Primary class contains virtual functions=0. Next class inherit from primary class. Third class contains e.g. container of primary class and call overloaded functions. How to properly call override function with different type of pointers?

Code (something like visitor design pattern):

ClassDeclarations.h

class Computer;
class ComputerPart;
class ComputerPartDisplayVisitor;
class ComputerPartVisitor;
class Keyboard;
class Monitor;
class Mouse;

Computer.h

#ifndef COMPUTER_H
#define COMPUTER_H
#include <vector>
#include "ClassDeclarations.h"
#include "ComputerPart.h"
class Computer : public ComputerPart
{
    std::vector<std::shared_ptr<ComputerPart>> parts;
public:
    Computer() { parts.push_back(std::make_shared<Mouse>()); }
    void accept(const std::shared_ptr<ComputerPartVisitor> &computerPartVisitor) const override{
        for(const auto &part : parts) { part->accept(computerPartVisitor); }
        computerPartVisitor->visit(this);
    }
};
#endif  //COMPUTER_H

ComputerPart.h

#ifndef COMPUTER_PART_H
#define COMPUTER_PART_H
#include <memory>
#include "ClassDeclarations.h"
#include "ComputerPartVisitor.h"
class ComputerPart
{
public:
    virtual ~ComputerPart() {}
    virtual void accept(const std::shared_ptr<ComputerPartVisitor> &computerPartVisitor) const = 0;
};
#endif  //COMPUTER_PART_H

ComputerPartDisplayVisitor.h

#ifndef COMPUTER_PART_DISPLAY_VISITOR_H
#define COMPUTER_PART_DISPLAY_VISITOR_H
#include <iostream>
#include "ClassDeclarations.h"
#include "ComputerPartVisitor.h"
class ComputerPartDisplayVisitor : public ComputerPartVisitor
{
public:
    void visit(const std::shared_ptr<Computer> &computer) const override{std::cout << "ComputerPartDisplayVisitor visit() Computer" << std::endl;}    
    void visit(const std::shared_ptr<Mouse> &mouser) const override{std::cout << "ComputerPartDisplayVisitor visit() Mouse" << std::endl;}
    void visit(const std::shared_ptr<Keyboard> &keyboard) const override{std::cout << "ComputerPartDisplayVisitor visit() Keyboard" << std::endl;}    
    void visit(const std::shared_ptr<Monitor> &monitor) const override{std::cout << "ComputerPartDisplayVisitor visit() Monitor" << std::endl;}
};
#endif  //COMPUTER_PART_DISPLAY_VISITOR_H

ComputerPartVisitor.h

#ifndef COMPUTER_PART_VISITOR_H
#define COMPUTER_PART_VISITOR_H
#include <memory>
#include "ClassDeclarations.h"
#include "Computer.h"
#include "Mouse.h"
#include "Keyboard.h"
#include "Monitor.h"
class ComputerPartVisitor
{
public:
    virtual ~ComputerPartVisitor() {}
    virtual void visit(const std::shared_ptr<Computer> &computer) const = 0;
    virtual void visit(const std::shared_ptr<Mouse> &mouse) const = 0;
    virtual void visit(const std::shared_ptr<Keyboard> &keyboard) const = 0;
    virtual void visit(const std::shared_ptr<Monitor> &monitor) const = 0;
};
#endif  //COMPUTER_PART_VISITOR_H

Keyboard.h

#ifndef KEYBOARD_H
#define KEYBOARD_H
#include "ClassDeclarations.h"
#include "ComputerPart.h"
class Keyboard : public ComputerPart
{
public:
    void accept(const std::shared_ptr<ComputerPartVisitor> &computerPartVisitor) const override{computerPartVisitor->visit(this);}
};
#endif  //KEYBOARD_H

Monitor.h

#ifndef MONITOR_H
#define MONITOR_H
#include "ClassDeclarations.h"
#include "ComputerPart.h"
class Monitor : public ComputerPart
{
public:
    void accept(const std::shared_ptr<ComputerPartVisitor> &computerPartVisitor) const override{computerPartVisitor->visit(this);}
};
#endif  //MONITOR_H

Mouse.h

#ifndef MOUSE_H
#define MOUSE_H
#include "ClassDeclarations.h"
#include "ComputerPart.h"
class Mouse : public ComputerPart
{
public:
    void accept(const std::shared_ptr<ComputerPartVisitor> &computerPartVisitor) const override{computerPartVisitor->visit(this);}
};
#endif  //MOUSE_H

Main.cpp

#include "ClassDeclarations.h"
#include "Computer.h"
#include "ComputerPartDisplayVisitor.h"
int main(){
    Computer computer;
    computer.accept(std::make_shared<computerPartDisplayVisitor>());
}

How to pack json with valid fields?

I have a class which contains various fields and they could be accessed with the help of getters and setters like the following

public class Student {
    
    private String name;
    private int age;
    private int sibblingsCount;
    private String elderSibblingName;
    private String youngerSibblingName;
    
    public String getName() {
    return this.name;
    }
    public void setName(String name) {
    this.name = name;
    }
    
    public int getAge() {
    return this.name;
    }
    public void setAge(int age) {
    this.age = age;
    }
    
    public void setSibblingsCount(int count) {
    this.sibblingsCount = count;
    }
    public int getSibblingsCount() {
    return this.sibblingsCount;
    }
    
    public void setElderSibblingName(String name) {
    this.elderSibblingName = name;
    }
    public String getElderSibblingName() {
    return this.elderSibblingName;
    }
    
    public void setYoungerSibblingName(String name) {
    this.youngerSibblingName = name;
    }
    public void getYoungerSibblingName() {
    return this.youngerSibblingName;
    }
    
    public String getStudentDetails() {
    
    JSONObject json = new JSONObject();
    if(name != null && !name.isEmpty()) {
    json.put("name", this.name);
    }
    
    if(this.age != 0) {
    json.put("age", this.age);
    }
    
    if(this.sibblingsCount != 0) {
    json.put("sibblingsCount", this.sibblingsCount);
    }
    
    if(this.elderSibblingName != null && !this.elderSibblingName.isEmpty()) {
    json.put("elderSibblingName", this.elderSibblingName);
    }
    
    if(this.youngerSibblingName != null && !this.youngerSibblingName.isEmpty() {
    json.put("youngerSibblingName", this.youngerSibblingName);
    }
    return json.toString();
    }
    }

All I need is to pack the valid fields in the class Student. The field is said to be valid when it contains some value in it. Say age should not be 0 and it must be a valid number. Say elderSibblingName it must not be null or empty. How to check for valid fields while packing the resultant json.

It is really painful to check for validity against each and every filed of the class which makes the code looks clumsy when there are too many fields in the class. Any suggestions to improve is most welcome !!

Thanks in advance :-)

Why are static methods not available in Singleton Instance?

I Create Generic Type Class Of name SingletonGenerator<> For Implement Singelton Design Pattern So The above code is it the class:

SingletonGenerator.cs

   public class SingletonGenerator<T> where T : class, new()
   {
      private static readonly Lazy<T> _instance =
        new Lazy<T>(() => new T(), LazyThreadSafetyMode.ExecutionAndPublication);

    private SingletonGenerator()
    {
    }

    public static T Instance => _instance.Value;

    }

And Create Other Class For Get Instance:

AppDb.cs

    public class AppDbContext
    {
      public string Database { get; set; }

      private static string ConnectionString { get; set; }

      public static void Send()
      {

      }

      public void Go()
      {
      }

     }

In Program.cs

    class Program
    {
     static void Main(string[] args)
     {
         var context = SingletonGenerator<AppDbContext>.Instance;

         var database = context.Database; // is available 
         var connection = context.ConnectionString; //is not available

         context.Go(); // is available 
         context.Send(); // is not available
     }
    }

My Question is Why are static methods not available in Singleton Instance?

And My Code is Correct?

samedi 1 juillet 2017

Which design pattern would be appropriate for the following api implementation?

I would like to add oEmbed tags to my site (I'm the oEmbed api provider). My api should respond the results based on the file type.

oEmbed Types has

  • Photo
  • Video
  • Link
  • Rich

My response to photo contains the following field

{
    "author_name": "rajasuba.s",
    "author_url": <author_image_url>,
    "thumbnail_width": 130,
    "provider_url": <provider_url>,
    "thumbnail_url": "<thumbnail_image_url>",
    "title": "Picture.png",
    "provider_name": "XYZ",
    "type": "photo",
    "version": "1.0",
    "url": "<given_url>",
    "thumbnail_height": 120
}

My response to video contains the following field

{
    "author_name": "rajasuba.s ",
    "author_url": "<image_url_of_author>",
    "thumbnail_width": 130,
    "html": "<iframe src="<source_url>" width=\"480\" height=\"270\" frameborder=\"0\">",
    "provider_url": "<service_url>",
    "thumbnail_url": "<thumbnail_image_url>",
    "title": "video_small_resource.mp4",
    "provider_name": "XYZ",
    "type": "video",
    "version": "1.0",
    "thumbnail_height": 120
}

And similarly for link and rich types.

I’m implementing this api in the following way. All I have is a servlet (where the api request lands). Here I have the following

public class OEmbedServlet extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
    //Parse request uri

      String format = request.getParameter(“format”);
      String url = request.getParameter(“url”);
      String file_id = request.getParameter(“file_id”);

      String max_width = request.getParameter(“max_height”);
      String max_height = request.getParameter(“max_width”);

          if(authorised_user) {
            oembed.setFileInfo(file_id);
            oembed.setProviderInfo();
            oembed.setURL(url);
            oembed.setThumbnailInfo();
            oembed.setOEmbedType();
          }

     writeResponse(response, oembed.getJSONObject(), format);
   }
}

And another class which does all utility job for this servlet

public class OEmbed {
private HttpServletRequest request;

public OEmbed(HttpServletRequest request) {
this.request = request;
this.oembedType = OEmbedType.LINK;
this.width = 0;
this.height = 0;
this.thumbnailWidth = 0;
this.thumbnailHeight = 0;
}

public enum OEmbedType {
RICH/*0*/,
LINK/*1*/,
PHOTO/*2*/,
VIDEO/*3*/
}

public void String author;
public void String file_id;
public void String extension;
public void String fileType;

//Getter and setter methods for all required info to be passed in the response like 

public String getAuthorName() {
return this.author;
}

public String setAuthorName(String name) {
this.author = name;
}

public void setURL(String url) {
this.url = url;
}

public String getURL(String url) {
return this.url;
}

//…. and other getter and setter methods
/*
- Few setter methods are invoked from the servlet
- Few setter methods are clubbed together and invoked from util classes
- The setter methods in util does some computation to assign value - or they are assigned based on inputted params
- All required getter methods are obtained while writing response json
*/

public JSONObject getJSONObject(boolean isAuthorised) throws Exception
{
JSONObject oembedObj = new JSONObject();
if(this.url != null && !this.url.isEmpty()) {
switch(this.oembedType) {
case PHOTO:
oembedObj.put("url", this.thumbnailUrl);
break;
case LINK:
oembedObj.put("url", this.url);
default:
oembedObj.put("url", this.url);
oembedObj.put("html", htmlContent);
break;
}

if(this.thumbnailUrl != null && !this.thumbnailUrl.isEmpty()) {
oembedObj.put(“thumbnail_url”, this.thumbnailUrl);
oembedObj.put(“thumbnail_width”, this.thumbnailWidth);
oembedObj.put(“thumbnail_height”, this.thumbnailHeight);
}

}
}

I still feel this design very cumbersome. I feel inconvenient in the following things,

  • few setter methods were invoked from servlet and few were invoked from util class
  • also while making use of class variables in util class - i have to be careful whether those attribute values were already initialised

say for an example

public void setThubnailUrl(String url) {
this.thumbnail_url = url;
}
public void setThubnailUrl() {
setThumbnailInfo();
getThumbnailStatus();
setThumbnailUrl(url);    //So before initialising this url - i have to make sure manually - whether the required params for thumbnail url is initialised already (I'm not sure weather it is a best practice to do like this)
}

How can I organise it in a much better way? Which design pattern would be appropriate for the following case? Any suggestions are welcome :-)

Software design patterns lexical analyzer

Which are the most common software design patterns that you can use to design/create a lexical analyzer?

Can you recommend any book or article that mention this?

PHP MVC Query builder class for building complex sql statements

This question is an extension of my post PHP MVC Data mapper pattern: class design. Actually, the answer to this question could be seen as a consequence of it.

I have a web MVC application with domain objects and data mappers. The class methods of the data mappers contain all database querying logic. I'm trying to avoid mirroring any database structure and, therefore, to achieve the maximum flexibility in constructing the sql statements. So, in principle, I'm trying to not make use of any ORM or Active Record structure/pattern AT ALL.

Now, let's suppose two things:

  • A data mapper abstract class - from which each specific data mapper class would inherit - does NOT exist. E.g: each data mapper class contains its own completely "proprietary" implementation of the data-access layer and, therefore, each data mapper class method can juggle with complex sql queries without any limitations.
  • The project is a complex one, with (very) complex queries on multiple databases and tables.

My question is: Under these circumstances, is the use of a query builder class - responsible for building the sql statements - a limitation or an advantage? I appreciate any arguments, or examples, or ideas.

Because the answer to this question is very important to me, I'll also put bounties on it in two days.

Thank you very much.

Where should I put the LocalDB file?

Say I have a Visual Studio solution with three projects:

Application Layer - MVC
Data Layer
Domain Layer
Service Layer

The data layer uses Entity Framework. Say I want to add a localdb (mainly for testing). Do I add the 'SQL Database file' solution item to the Application Layer (MVC) or data layer. It seems cleaner to add it to the data layer so that multiple clients can access it.

If it is added to the data layer then how do I ensure that the file is copied to the BIN folder of the application layer each time it is built so that the application layer can see it? Ideally the database would not be refreshed every time the application layer is built.