mercredi 31 décembre 2014

Update UI(JSP page for Monitor) when certain Activities take place in a Web Application (in Tomcat)

The requirement is that I need to design a JSP page where a user logs in and monitors activities going on in the Application. For example: a user logged in, an account was created, a user logged out, left a comment and so on.


Initially my design was such that, I used polling to query the database regularly to check activities logged(in log table) recently and display that. I made Ajax calls every 1 minute to fetch latest data from table and added that to the activity list in the JSP page.


Polling is working but it has the disadvantage of putting pressure on the Database Server. I was wondering if there is a better approach, something similar to Observer Pattern or Publish-Subscribe pattern. Or should I maintain a Cache of these messages? In that case it will quickly grow and eat memory if its a heavily used application.


At the moment I could think of something similar to Echo server, where all important messages are sent to the Echo Server, and all the clients listening to the Echo Server will receive the message. However the feasibility of implementing this is under question.


Update UI(JSP page for Monitor) when certain Activities take place in a Web Application (in Tomcat)

The requirement is that I need to design a JSP page where a user logs in and monitors activities going on in the Application. For example: a user logged in, an account was created, a user logged out, left a comment and so on.


Initially my design was such that, I used polling to query the database regularly to check activities logged(in log table) recently and display that. I made Ajax calls every 1 minute to fetch latest data from table and added that to the activity list in the JSP page.


Polling is working but it has the disadvantage of putting pressure on the Database Server. I was wondering if there is a better approach, something similar to Observer Pattern or Publish-Subscribe pattern. Or should I maintain a Cache of these messages? In that case it will quickly grow and eat memory if its a heavily used application.


At the moment I could think of something similar to Echo server, where all important messages are sent to the Echo Server, and all the clients listening to the Echo Server will receive the message. However the feasibility of implementing this is under question.


Is there a good design pattern to "wrap" logic classes together to handle the flow of a game?

The topic may sound vague. That is because I couldn't find good words to summarize my question. I'm developing a tetris game as a school programming project (Java), and one of our tasks is to try to follow clean-code principles as closely as possible.


I've programmed Java for a while now, and I've only just begun to come across "design patterns". I found myself already following some (for example, the observer pattern), and got kind of hooked. For this particular problem I'm not looking necessarily for some out-of-the-book design patterns, but advice in general on how I could maybe improve my current design. I also want to know how my current design differs from the mediator pattern




In my current design, I have the class Game, which provides some fundamental logic for moving tetrominoes (tetris pieces) on the grid, removing filled rows, determining whether or not the game is over, etc. This class holds information of the currently falling tetromino, and the next tetromino that will start falling after the currently falling one has fallen.


I also have the class ScoreHandler, which defines how the scoring of each action should be determined. This class only holds information of the current score, and a way of updating the score.


I also have the class CommandHandler that keeps a registry of user commands. For example, the registry could hold an entry (keyCode, Command), where keyCode indicates some keyboard input, which points to a command that does stuff.


Finally, I have the class GameHandler that knows an instance of all the classes above. This class takes care of the game loop; it tells Game to play a round every X milliseconds and then notifies ScoreHandler of any cleared rows. Anywhere in-between the CommandHandler may notify the game handler that a user command was invoked, and the handler sends the command to the game instance which again updates its state according to the command.


In short the GameHandler class takes care of the flow of the game; it plays the game in a loop until some condition is met, updates the ScoreHandler's score and redirects any user commands to the game.




The Question(s)


Does my current design follow any known pattern? How does it differ from the mediator pattern? Is there an obviously better way of handling this kind of logic?


Is there a good design pattern to "wrap" logic classes together to handle the flow of a game?

The topic may sound vague. That is because I couldn't find good words to summarize my question. I'm developing a tetris game as a school programming project (Java), and one of our tasks is to try to follow clean-code principles as closely as possible.


I've programmed Java for a while now, and I've only just begun to come across "design patterns". I found myself already following some (for example, the observer pattern), and got kind of hooked. For this particular problem I'm not looking necessarily for some out-of-the-book design patterns, but advice in general on how I could maybe improve my current design. I also want to know how my current design differs from the mediator pattern




In my current design, I have the class Game, which provides some fundamental logic for moving tetrominoes (tetris pieces) on the grid, removing filled rows, determining whether or not the game is over, etc. This class holds information of the currently falling tetromino, and the next tetromino that will start falling after the currently falling one has fallen.


I also have the class ScoreHandler, which defines how the scoring of each action should be determined. This class only holds information of the current score, and a way of updating the score.


I also have the class CommandHandler that keeps a registry of user commands. For example, the registry could hold an entry (keyCode, Command), where keyCode indicates some keyboard input, which points to a command that does stuff.


Finally, I have the class GameHandler that knows an instance of all the classes above. This class takes care of the game loop; it tells Game to play a round every X milliseconds and then notifies ScoreHandler of any cleared rows. Anywhere in-between the CommandHandler may notify the game handler that a user command was invoked, and the handler sends the command to the game instance which again updates its state according to the command.


In short the GameHandler class takes care of the flow of the game; it plays the game in a loop until some condition is met, updates the ScoreHandler's score and redirects any user commands to the game.




The Question(s)


Does my current design follow any known pattern? How does it differ from the mediator pattern? Is there an obviously better way of handling this kind of logic?


Input pattern for password submits with empty input

I have this pattern for html input password (UpperCase, LowerCase, Number/SpecialChar and min 8 Chars)



(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$


The form submits with an empty input, how can I prevent this from happening?


Input pattern for password submits with empty input

I have this pattern for html input password (UpperCase, LowerCase, Number/SpecialChar and min 8 Chars)



(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$


The form submits with an empty input, how can I prevent this from happening?


Is there a code to perform factory reset on wrong pattern/unlock screen Android ?

I want to make some changes on Android pattern system file and make it perform factory reset on specific pattern. Anyone know how can I do this?


Is there a code to perform factory reset on wrong pattern/unlock screen Android ?

I want to make some changes on Android pattern system file and make it perform factory reset on specific pattern. Anyone know how can I do this?


Design Patterns for Data Access Layer

I have an application which uses a database (MongoDB) to store information. In the past I have used a class full of static methods to save and retrieve data but I have since realised this is not very object-oriented-ish or future proof.


Even though it is very unlikely I will change database I would rather something that does not tie me too strongly to Mongo. I would also like to be able to cache results with the option to refresh the cached object from the database but this is not essential and can be done in another place.


I have looked at data access objects but they do not seem very well-defined and I can't find any good examples of implementation (In Java or a similar language). I also have many one off cases such as finding usernames for tab completion which seem not well suited and would make the DAO large and bloated.


Are there any design patterns that would facilitate getting and saving objects without being too database specific? Good examples of implementation would be helpful (preferably in Java).


How to get a class object to store another class object in c#?

Suppose we have the C# code below that stores an instance of class A in class B. I want to create a version of class B that stores its own A. So when we change A outside of B, the internal A object in B doesn't change.



class A
{
public int data = 9;
}
class B
{
public B(A a_) { a = a_; }
public A a;
}

class Program
{
static void Main(string[] args)
{
A foo = new A();
foo.data = 20; // this changes the field a in B as well
B bar = new B(foo);

Console.WriteLine(bar.a.data); // prints 20 instead of 9
}
}


I can avoid this problem in C++ by using a templated bridge class that clones A when passing A into B. But apparently deep clones doesn't seem as widely used in C# for some reason(why?). Can anyone provide a good way around this storing problem.


C++ code:



template <typename T>
class Wrapper{
public:
Wrapper(const Wrapper<T> &orig){if(orig.data!=nullptr)data = orig.data->clone();}
Wrapper(const T &origdata){data = origdata.clone();}
Wrapper & operator=(const Wrapper<T> &orig){...}
...
~T(){delete data;}
private:
T *data;
}

class A{
public:
A():data(9){}
int data;
A *clone(){return new A(*this);}
}

class B{
public:
B(const Wrapper<A>& a_):ainner(a_){}
Wrapper<A> ainner;
}

int main(){
A a;
B b(a);
a.data =20;
std::cout << b.ainner.data; // prints 9 still
return 0;
}

Design Patterns for Data Access Layer

I have an application which uses a database (MongoDB) to store information. In the past I have used a class full of static methods to save and retrieve data but I have since realised this is not very object-oriented-ish or future proof.


Even though it is very unlikely I will change database I would rather something that does not tie me too strongly to Mongo. I would also like to be able to cache results with the option to refresh the cached object from the database but this is not essential and can be done in another place.


I have looked at data access objects but they do not seem very well-defined and I can't find any good examples of implementation (In Java or a similar language). I also have many one off cases such as finding usernames for tab completion which seem not well suited and would make the DAO large and bloated.


Are there any design patterns that would facilitate getting and saving objects without being too database specific? Good examples of implementation would be helpful (preferably in Java).


How to get a class object to store another class object in c#?

Suppose we have the C# code below that stores an instance of class A in class B. I want to create a version of class B that stores its own A. So when we change A outside of B, the internal A object in B doesn't change.



class A
{
public int data = 9;
}
class B
{
public B(A a_) { a = a_; }
public A a;
}

class Program
{
static void Main(string[] args)
{
A foo = new A();
foo.data = 20; // this changes the field a in B as well
B bar = new B(foo);

Console.WriteLine(bar.a.data); // prints 20 instead of 9
}
}


I can avoid this problem in C++ by using a templated bridge class that clones A when passing A into B. But apparently deep clones doesn't seem as widely used in C# for some reason(why?). Can anyone provide a good way around this storing problem.


C++ code:



template <typename T>
class Wrapper{
public:
Wrapper(const Wrapper<T> &orig){if(orig.data!=nullptr)data = orig.data->clone();}
Wrapper(const T &origdata){data = origdata.clone();}
Wrapper & operator=(const Wrapper<T> &orig){...}
...
~T(){delete data;}
private:
T *data;
}

class A{
public:
A():data(9){}
int data;
A *clone(){return new A(*this);}
}

class B{
public:
B(const Wrapper<A>& a_):ainner(a_){}
Wrapper<A> ainner;
}

int main(){
A a;
B b(a);
a.data =20;
std::cout << b.ainner.data; // prints 9 still
return 0;
}

Decorator and Flyweight

In what situation is best used design pattern Decorator and Flyweight together. I have a financial system to build and some friends showed me these standards.


Decorator and Flyweight

In what situation is best used design pattern Decorator and Flyweight together. I have a financial system to build and some friends showed me these standards.


the best place to refresh design patterns in .net knowledge [on hold]

after 3 years break Im comming back to .net. I would like to spend some time and refresh my knowledge, learn a little bit of new features and so on.


Im lookin for all in one place, resource where in systematical way I can learn all from: http://www.dofactory.com/


C#, WPF MVVM Pattern?, ASP.Net WebForms MVP Pattern, ASP.Net MVC, WinForms - MVP pattern? WCF,


design patterns in all


etc.


I found this site, it looks quite ok but I dont know if it is the best solution possible and what are the alternatives.


I find it really dificult to get all the knowledge from msdn as I cant figure out how to navigate there. Microsoft has dozens of websites with documentation and it is not user friendly.


Thank for any help


the best place to refresh design patterns in .net knowledge [on hold]

after 3 years break Im comming back to .net. I would like to spend some time and refresh my knowledge, learn a little bit of new features and so on.


Im lookin for all in one place, resource where in systematical way I can learn all from: http://www.dofactory.com/


C#, WPF MVVM Pattern?, ASP.Net WebForms MVP Pattern, ASP.Net MVC, WinForms - MVP pattern? WCF,


design patterns in all


etc.


I found this site, it looks quite ok but I dont know if it is the best solution possible and what are the alternatives.


I find it really dificult to get all the knowledge from msdn as I cant figure out how to navigate there. Microsoft has dozens of websites with documentation and it is not user friendly.


Thank for any help


How to use a single grep command to search a pattern from different unix servers

For Example,


I have two servers namely A and B. I want to use a grep command in either A or B, which will search in both A and B servers and display the match.


How to use a single grep command to search a pattern from different unix servers

For Example,


I have two servers namely A and B. I want to use a grep command in either A or B, which will search in both A and B servers and display the match.


mardi 30 décembre 2014

Organizing multiple panels and components in a wizard design

I'm writing on my own wizard and find myself duplicating code throughout my view class (using a MVC design pattern).


I have basic methods that create panels that are used by the wizard. Some of the panels share common components but may have different functionality.


My example below is not actual code, but just an example of my layout:



public class View
{
private Panel panel1;
private Panel panel2;
private Panel panel3;
private Panel panel4;

private JButton panel1Button1;
private JButton panel1Button2;
private JButton panel1Button3;
private JButton panel1Button4;

private JButton panel2Button1;
private JButton panel2Button2;
private JButton panel2Button3;
private JButton panel2Button4;

private JButton panel3Button1;
private JButton panel3Button2;
private JButton panel3Button3;
private JButton panel3Button4;

private JButton panel1Button1;
private JButton panel1Button2;
private JButton panel1Button3;
private JButton panel1Button4;

View()
{
panel1 = createPanel1();
panel2 = createPanel2();
panel3 = createPanel3();
panel4 = createPanel4();
}

private JPanel createPanel1()
{
// panel1 code which may have buttons, scroll panes, etc
return panel1;
}

private JPanel createPanel2()
{
// panel2 code which may have buttons, scroll panes, etc
return panel2;
}

private JPanel createPanel3()
{
// panel3 code which may have buttons, scroll panes, etc
return panel3;
}

private JPanel createPanel4()
{
// panel4 code which may have buttons, scroll panes, etc
return panel4;
}

// Getters for all the components, but only some buttons listed only for brevity
private JButton getPanel1Button1() { return panel1Button1; }
private JButton getPanel1Button2() { return panel1Button2; }
private JButton getPanel1Button3() { return panel1Button3; }
private JButton getPanel1Button4() { return panel1Button4; }
//etc

// Getterss for panels
private JPanel getPanel1() { return panel1; }
//etc
}


That is the basic layout of my code, but as you can see just adding one component that may be used in multiple panels creates a lot of duplicate work.


Buttons are easy because I can find them using a method that searches for buttons in a panel using the getText method, but this doesn't work for other components.


How can I reduce duplicating my code and reduce the amount of references for each panel (i.e. I have cancel, back and next buttons on each panel)? Or must I uniquely create a reference for each component of each panel and supply a getter to adequately set up an MVC?


Organizing multiple panels and components in a wizard design

I'm writing on my own wizard and find myself duplicating code throughout my view class (using a MVC design pattern).


I have basic methods that create panels that are used by the wizard. Some of the panels share common components but may have different functionality.


My example below is not actual code, but just an example of my layout:



public class View
{
private Panel panel1;
private Panel panel2;
private Panel panel3;
private Panel panel4;

private JButton panel1Button1;
private JButton panel1Button2;
private JButton panel1Button3;
private JButton panel1Button4;

private JButton panel2Button1;
private JButton panel2Button2;
private JButton panel2Button3;
private JButton panel2Button4;

private JButton panel3Button1;
private JButton panel3Button2;
private JButton panel3Button3;
private JButton panel3Button4;

private JButton panel1Button1;
private JButton panel1Button2;
private JButton panel1Button3;
private JButton panel1Button4;

View()
{
panel1 = createPanel1();
panel2 = createPanel2();
panel3 = createPanel3();
panel4 = createPanel4();
}

private JPanel createPanel1()
{
// panel1 code which may have buttons, scroll panes, etc
return panel1;
}

private JPanel createPanel2()
{
// panel2 code which may have buttons, scroll panes, etc
return panel2;
}

private JPanel createPanel3()
{
// panel3 code which may have buttons, scroll panes, etc
return panel3;
}

private JPanel createPanel4()
{
// panel4 code which may have buttons, scroll panes, etc
return panel4;
}

// Getters for all the components, but only some buttons listed only for brevity
private JButton getPanel1Button1() { return panel1Button1; }
private JButton getPanel1Button2() { return panel1Button2; }
private JButton getPanel1Button3() { return panel1Button3; }
private JButton getPanel1Button4() { return panel1Button4; }
//etc

// Getterss for panels
private JPanel getPanel1() { return panel1; }
//etc
}


That is the basic layout of my code, but as you can see just adding one component that may be used in multiple panels creates a lot of duplicate work.


Buttons are easy because I can find them using a method that searches for buttons in a panel using the getText method, but this doesn't work for other components.


How can I reduce duplicating my code and reduce the amount of references for each panel (i.e. I have cancel, back and next buttons on each panel)? Or must I uniquely create a reference for each component of each panel and supply a getter to adequately set up an MVC?


Object Oriented Programming with PHP [on hold]

I have task in OOP PHP,and here is one part which i don`t understand:



Characteristics of the health institution are:
1.Doktor (name, specialty) has more than one patient (name, ID number,
health records).
2.Pacient can have only one doctor.


I understand that i need to create two classes,Doctor and Patient,but i don`t understand how to make restrictions that doctor can have more than one patient,and patient can have only one doctor.Is there any design pattern for that?And task is to do this without creating MySQL database,focus is on OOP programming and way of thinking.


Object Oriented Programming with PHP [on hold]

I have task in OOP PHP,and here is one part which i don`t understand:



Characteristics of the health institution are:
1.Doktor (name, specialty) has more than one patient (name, ID number,
health records).
2.Pacient can have only one doctor.


I understand that i need to create two classes,Doctor and Patient,but i don`t understand how to make restrictions that doctor can have more than one patient,and patient can have only one doctor.Is there any design pattern for that?And task is to do this without creating MySQL database,focus is on OOP programming and way of thinking.


Creating a Basic Undo Manager for Integer Values

I want to design a basic command pattern that will save integer values and be able to execute a undo method. I'm not sure where to start at all so any help would be much appreciated. Very basic interpretations like below:



package com.k.s;

public class MainActivity extends Activity {

public int Counter = 0;

@Override
protected void onCreate(Bundle savedInsanceState) {
super.onCreate(savedInsanceState);
setContentView(R.layout.activity_main);

Button.setOnClickListener (new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Counter += 1;
}
}
}
}

Creating a Basic Undo Manager for Integer Values

I want to design a basic command pattern that will save integer values and be able to execute a undo method. I'm not sure where to start at all so any help would be much appreciated. Very basic interpretations like below:



package com.k.s;

public class MainActivity extends Activity {

public int Counter = 0;

@Override
protected void onCreate(Bundle savedInsanceState) {
super.onCreate(savedInsanceState);
setContentView(R.layout.activity_main);

Button.setOnClickListener (new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Counter += 1;
}
}
}
}

Create objects inside a module javascript

I am learning design patterns in javascript but I have a problem creating a module. I am creating a Person object inside of module and I have combined it with a constructor pattern, just beacuse I am learning it too, but nothing happens.


Can anybody help me, I don't undertand my mistake here



var myModule = (function () {
function Person(id, name) {
this.id = id;
this.name = name;
}

Person.prototype.toString = function () {
return "\nID: " + this.Id + "\nName: " + this.name;
};

return {
newPerson: function (id, name) {
return new Person(id,name);
console.log(Person.toString());
}
};
})();

var x = myModule;

x.newPerson(1, "John");

Create objects inside a module javascript

I am learning design patterns in javascript but I have a problem creating a module. I am creating a Person object inside of module and I have combined it with a constructor pattern, just beacuse I am learning it too, but nothing happens.


Can anybody help me, I don't undertand my mistake here



var myModule = (function () {
function Person(id, name) {
this.id = id;
this.name = name;
}

Person.prototype.toString = function () {
return "\nID: " + this.Id + "\nName: " + this.name;
};

return {
newPerson: function (id, name) {
return new Person(id,name);
console.log(Person.toString());
}
};
})();

var x = myModule;

x.newPerson(1, "John");

Where to learn something about "application architecture / design"? [on hold]

sorry for my poor English and let's get down to business.


I am setting about writing a notepad application in C++, but this time I would like to do it decently. So far in every program I have written I've put an enormous while(true) loop in main function. In the loop there was the whole code for event handling etc. Yeah, it looks, feels and is terrible.


As a rookie coder I don't know any better, so this time I would like to write an application like a pro. Thus I need to learn something about this "code desing" (??). The problem is that I don't even know what this is called, so I can't really google it. I tried "code design", "code architecture" but all in vain.


I would really appreciate any help.


Where to learn something about "application architecture / design"? [on hold]

sorry for my poor English and let's get down to business.


I am setting about writing a notepad application in C++, but this time I would like to do it decently. So far in every program I have written I've put an enormous while(true) loop in main function. In the loop there was the whole code for event handling etc. Yeah, it looks, feels and is terrible.


As a rookie coder I don't know any better, so this time I would like to write an application like a pro. Thus I need to learn something about this "code desing" (??). The problem is that I don't even know what this is called, so I can't really google it. I tried "code design", "code architecture" but all in vain.


I would really appreciate any help.


Examples of Design Patterns used in .Net Framework [on hold]

I wondered whether it's possible to gather example for each of GoF patterns in .NET Framework?


(not just examples of the patterns on C# like it's at http://www.dofactory.com/) but implementation in .NET Framework types


Can anyone remember examples of usages in .Net Framework of the following patterns:



  • Bridge

  • Flightweight

  • Mediator

  • State


I summarized material from similar questions on stack overflow:



  1. examples in .NET framework of Observer Iterator Decorator Adapter Factory Strategy Composite Template Method patterns

  2. examples in .NET framework of Observer Iterator Decorator Adapter Factory Strategy Composite Template Method, Patterns in the ASP.NET Pipeline, Intercepting Filter Pattern, Page Controller Pattern

  3. examples in .NET framework of Factory Method Singleton Prototype Adapter Composite Decorator Proxy Observer Iterator

  4. similar question - Are there any design patterns used in the .NET Framework? thanks Paul Lalonde and Peter Mortensen for their comment with examples for many usages of GoF patters


Creational patterns



  • Abstract Factory: System.Data.Common.DbProviderFactory. Every member function of this class is a factory method.

  • Builder: The WCF channel construction infrastructure or SqlCommandBuilder and StringBuilder

  • Factory Method System.Data.IDbConnection.BeginTransaction(). The type of transaction created depends on the underlying IDbConnection implementation or WebRequest (HttpWebRequest/FtpWebRequest)

  • Singleton - in .NET Remoting

  • Prototype - cloning and serialization


Behavioral patterns



  • Adapter: The ADO.NET providers, eg System.Data.SqlClient.SqlConnection, System.Data.OleDb.OleDbConnection etc. Each provider is an adapter for its specific database.

  • Bridge - ?

  • Composite:

    • System.Windows.Forms.Control and its derived classes.

    • System.Web.UI.Control and its derived classes.

    • System.Xml.XmlNode and its derived classes.



  • Decorator: Stream (FileStream/NetworkStream etc.)

  • Facade: System.Xml.Serialization.XmlSerializer. XmlSerializer hides a complex task (that includes generating assemblies on the fly!) behind a very easy-to-use class.

  • Flightweight -?

  • Proxy: The web service proxies generated by svcutil.exe and deriving from System.ServiceModel.ClientBase<TChannel>


Structural Patterns



  • Chain of responsibility: System.Web.UI.Control.OnBubbleEvent() and System.Web.UI.Control.RaiseBubbleEvent().

  • Command:System.Windows.Input.ICommand (in WPF).

  • Interpreter: System.Linq.Expressions.Expression and related classes.

  • Iterator - called "enumerator" and represented by the IEnumerator interface

  • Mediator -?

  • Memento: System.Linq.Expressions.Expression and related classes.

  • Observer - delegates and events ex. Button control and Click event

  • State- -?

  • Strategy - Sort method in ArrayList

  • Template Method - Render method for custom controls

  • Visitor : System.Linq.Expressions.ExpressionVisitor (used internally by [LINQ])


Examples of Design Patterns used in .Net Framework [on hold]

I wondered whether it's possible to gather example for each of GoF patterns in .NET Framework?


(not just examples of the patterns on C# like it's at http://www.dofactory.com/) but implementation in .NET Framework types


Can anyone remember examples of usages in .Net Framework of the following patterns:



  • Bridge

  • Flightweight

  • Mediator

  • State


I summarized material from similar questions on stack overflow:



  1. examples in .NET framework of Observer Iterator Decorator Adapter Factory Strategy Composite Template Method patterns

  2. examples in .NET framework of Observer Iterator Decorator Adapter Factory Strategy Composite Template Method, Patterns in the ASP.NET Pipeline, Intercepting Filter Pattern, Page Controller Pattern

  3. examples in .NET framework of Factory Method Singleton Prototype Adapter Composite Decorator Proxy Observer Iterator

  4. similar question - Are there any design patterns used in the .NET Framework? thanks Paul Lalonde and Peter Mortensen for their comment with examples for many usages of GoF patters


Creational patterns



  • Abstract Factory: System.Data.Common.DbProviderFactory. Every member function of this class is a factory method.

  • Builder: The WCF channel construction infrastructure or SqlCommandBuilder and StringBuilder

  • Factory Method System.Data.IDbConnection.BeginTransaction(). The type of transaction created depends on the underlying IDbConnection implementation or WebRequest (HttpWebRequest/FtpWebRequest)

  • Singleton - in .NET Remoting

  • Prototype - cloning and serialization


Behavioral patterns



  • Adapter: The ADO.NET providers, eg System.Data.SqlClient.SqlConnection, System.Data.OleDb.OleDbConnection etc. Each provider is an adapter for its specific database.

  • Bridge - ?

  • Composite:

    • System.Windows.Forms.Control and its derived classes.

    • System.Web.UI.Control and its derived classes.

    • System.Xml.XmlNode and its derived classes.



  • Decorator: Stream (FileStream/NetworkStream etc.)

  • Facade: System.Xml.Serialization.XmlSerializer. XmlSerializer hides a complex task (that includes generating assemblies on the fly!) behind a very easy-to-use class.

  • Flightweight -?

  • Proxy: The web service proxies generated by svcutil.exe and deriving from System.ServiceModel.ClientBase<TChannel>


Structural Patterns



  • Chain of responsibility: System.Web.UI.Control.OnBubbleEvent() and System.Web.UI.Control.RaiseBubbleEvent().

  • Command:System.Windows.Input.ICommand (in WPF).

  • Interpreter: System.Linq.Expressions.Expression and related classes.

  • Iterator - called "enumerator" and represented by the IEnumerator interface

  • Mediator -?

  • Memento: System.Linq.Expressions.Expression and related classes.

  • Observer - delegates and events ex. Button control and Click event

  • State- -?

  • Strategy - Sort method in ArrayList

  • Template Method - Render method for custom controls

  • Visitor : System.Linq.Expressions.ExpressionVisitor (used internally by [LINQ])


Better design pattern for file exporter that requires blocks of information?

I'm writing a VRML file exporter. Your typical VRML file looks something like I've copied below. Below that, you can find how I'm going about generating each vrml block. The thing is, I feel like I'm going about this all wrong but I can't think of any other way to do it.


Nodes having parent dependencies (transforms have shapes, shapes have appearance and geometry nodes, those have...), and I need to be able to set start and end text for each block. Doing this all via constructors and inheritance feels a bit janky, but creating functions and what not creates additional overhead and looks messy. I guess that's okay if I put it all behind a nice API but I figured I'd ask to see if there's a better OOP approach/design pattern I could be using here.



Transform {
translation 0 0 100
children [
Shape {
appearance Appearance {
texture ImageTexture {
repeatS TRUE
repeatT TRUE
url [
"texture.png"
]
} # end texture

} # end appearance

geometry IndexedFaceSet {
normalPerVertex TRUE
solid TRUE
coord Coordinate {
point [
-5.400000 0.030000 -0.000000,
...
] # end point
} # end coord

texCoord TextureCoordinate {
point [
0.062500 0.086207,
...
] # end point
} # end texCoord


normal Normal {
vector [
0 1 0,
]
} # end normals
coordIndex [
0, 1, 2, -1,
...
] # end coordIndex

texCoordIndex [
0, 1, 2, -1,
...
] # end texCoordIndex
normalIndex [
0, 0, 0, -1,
...
] # end normalIndex
} # end geometry
} # end shape
] # end children
} # end Transform


I've started to build the vrml file using classes like this:



////////////////////////////////////////////////
class Node {
protected:
string start;
string end;
int x;

Node() {}
Node(string _start, string _end)
: start(_start), end(_end) { }
};

////////////////////////////////////////////////
class TransformNode : protected Node {
vector<ShapeNode*> shape;

TransformNode() :
Node("TransformNode {\n\ttranslation 0 0 100\n\t\tchildren[\n",
"\t\t] # end children\n} # end TransformNode \n") { }
};

////////////////////////////////////////////////
struct ShapeNode : Node {
AppearanceNode appearance;
GeometryNode* geometryNode;

ShapeNode();
ShapeNode(string texture, string repeatS, string repeatT, string normalPerVertex, string solid, vector<float> coordinates, vector<int> ind) :
Node("ShapeNode { \n\n", "}\n")
{
appearance.imageTexture.url.textureURL = "\t\t\t\t\"" + texture + "\"\n";
appearance.imageTexture.repeatS = "\t\t\trepeatS " + repeatS + "\n";
appearance.imageTexture.repeatT = "\t\t\trepeatT " + repeatT + "\n";

geometryNode = new GeometryNode(normalPerVertex, solid, coordinates, ind);
}
};
////////////////////////////////////////////////

Better design pattern for file exporter that requires blocks of information?

I'm writing a VRML file exporter. Your typical VRML file looks something like I've copied below. Below that, you can find how I'm going about generating each vrml block. The thing is, I feel like I'm going about this all wrong but I can't think of any other way to do it.


Nodes having parent dependencies (transforms have shapes, shapes have appearance and geometry nodes, those have...), and I need to be able to set start and end text for each block. Doing this all via constructors and inheritance feels a bit janky, but creating functions and what not creates additional overhead and looks messy. I guess that's okay if I put it all behind a nice API but I figured I'd ask to see if there's a better OOP approach/design pattern I could be using here.



Transform {
translation 0 0 100
children [
Shape {
appearance Appearance {
texture ImageTexture {
repeatS TRUE
repeatT TRUE
url [
"texture.png"
]
} # end texture

} # end appearance

geometry IndexedFaceSet {
normalPerVertex TRUE
solid TRUE
coord Coordinate {
point [
-5.400000 0.030000 -0.000000,
...
] # end point
} # end coord

texCoord TextureCoordinate {
point [
0.062500 0.086207,
...
] # end point
} # end texCoord


normal Normal {
vector [
0 1 0,
]
} # end normals
coordIndex [
0, 1, 2, -1,
...
] # end coordIndex

texCoordIndex [
0, 1, 2, -1,
...
] # end texCoordIndex
normalIndex [
0, 0, 0, -1,
...
] # end normalIndex
} # end geometry
} # end shape
] # end children
} # end Transform


I've started to build the vrml file using classes like this:



////////////////////////////////////////////////
class Node {
protected:
string start;
string end;
int x;

Node() {}
Node(string _start, string _end)
: start(_start), end(_end) { }
};

////////////////////////////////////////////////
class TransformNode : protected Node {
vector<ShapeNode*> shape;

TransformNode() :
Node("TransformNode {\n\ttranslation 0 0 100\n\t\tchildren[\n",
"\t\t] # end children\n} # end TransformNode \n") { }
};

////////////////////////////////////////////////
struct ShapeNode : Node {
AppearanceNode appearance;
GeometryNode* geometryNode;

ShapeNode();
ShapeNode(string texture, string repeatS, string repeatT, string normalPerVertex, string solid, vector<float> coordinates, vector<int> ind) :
Node("ShapeNode { \n\n", "}\n")
{
appearance.imageTexture.url.textureURL = "\t\t\t\t\"" + texture + "\"\n";
appearance.imageTexture.repeatS = "\t\t\trepeatS " + repeatS + "\n";
appearance.imageTexture.repeatT = "\t\t\trepeatT " + repeatT + "\n";

geometryNode = new GeometryNode(normalPerVertex, solid, coordinates, ind);
}
};
////////////////////////////////////////////////

Is user class responsible for authentication?

I have class named User, it has fields like username, password, firstName... . is it good to place authenticate(username, password) method in it?


Is user class responsible for authentication?

I have class named User, it has fields like username, password, firstName... . is it good to place authenticate(username, password) method in it?


Template design pattern for operations with parameters

Template design pattern lets you design an algorithm which can be customized by overriding some template methods.



class Algorithm {
protected void init();
protected void prepareCup();
protected TeaBag prepareTeaBag();
protected void boilWater();
protected void putWaterIntoCup();
}


prepareTeaBag() can return arbitrary tea bags to make custom tea.


But what if I have an algorithm that would require some parameters for operations, for example name of the tea bag, and some other properties that are being changed into each of the operation. I can save those properties into class as a class members but that way I can't call it from different threads. I would need to pass some Context class that would change depending on operation in order to allow multi threading access, or something what are your thoughts on this?


Template design pattern for operations with parameters

Template design pattern lets you design an algorithm which can be customized by overriding some template methods.



class Algorithm {
protected void init();
protected void prepareCup();
protected TeaBag prepareTeaBag();
protected void boilWater();
protected void putWaterIntoCup();
}


prepareTeaBag() can return arbitrary tea bags to make custom tea.


But what if I have an algorithm that would require some parameters for operations, for example name of the tea bag, and some other properties that are being changed into each of the operation. I can save those properties into class as a class members but that way I can't call it from different threads. I would need to pass some Context class that would change depending on operation in order to allow multi threading access, or something what are your thoughts on this?


Remove all characters between two html tags in vi editor

How to remove all characters between two HTML tags? I want to remove everything between span tags,xml tags, the comment tags. I am using vi editor.


Remove all characters between two html tags in vi editor

How to remove all characters between two HTML tags? I want to remove everything between span tags,xml tags, the comment tags. I am using vi editor.


lundi 29 décembre 2014

ListenableFuture like alternative/extension for listeners in Java

Consider the case where I need to perform a task and return a simple future as a handle. Now Guava suggest listenableFuture which has only two functions success and failure. Is there a more generic class which can handle more intermediate stages.


Use case example: upload a file. Now instead of final result which just says success or failure, the consumer is also interested in the current progress of the file.


Is there something similar in Guava or some reliable libraries?


This can be done through custom callback or listener based model but I wanted to know the elegant ways people have been achieving this.


ListenableFuture like alternative/extension for listeners in Java

Consider the case where I need to perform a task and return a simple future as a handle. Now Guava suggest listenableFuture which has only two functions success and failure. Is there a more generic class which can handle more intermediate stages.


Use case example: upload a file. Now instead of final result which just says success or failure, the consumer is also interested in the current progress of the file.


Is there something similar in Guava or some reliable libraries?


This can be done through custom callback or listener based model but I wanted to know the elegant ways people have been achieving this.


Javascript prototype declaration over multiple files

I have this big "class".



function MyFunc(){
this.prop = true;
}

MyFunc.prototype.method1 = function(){
// code here
}


etc, lots of methods in one file. and then, the instance is created and run on document.ready


And then, I have one particularly large method, that I would like to move to a separate file. However, when I move it and include them one after another, main file first, the second one says MyFunc is not defined. I cannot add that prototype.method declaration on document.ready, also, since it has to be ready before instance is initialized. What pattern should I use here to properly organize my code? Thanks.


Javascript prototype declaration over multiple files

I have this big "class".



function MyFunc(){
this.prop = true;
}

MyFunc.prototype.method1 = function(){
// code here
}


etc, lots of methods in one file. and then, the instance is created and run on document.ready


And then, I have one particularly large method, that I would like to move to a separate file. However, when I move it and include them one after another, main file first, the second one says MyFunc is not defined. I cannot add that prototype.method declaration on document.ready, also, since it has to be ready before instance is initialized. What pattern should I use here to properly organize my code? Thanks.


Design for request bucket information on client

I'm trying to find the best way to design the client side storage of "buckets". To explain, the server sends down info like:



{
'buckets': {
'some_cool_bucket' : 'val1',
'another_bucket' : 'name'
}
}


Where the values can be



'some_cool_bucket' : 'val1' | 'val2' | 'val3'
'another_bucket' : 'name' | 'cool' | 'other'


basically all these buckets are enums with all the possible values known to both client and server, though there aren't common constraints, like buckets can have any number of possible values (no size limit), and any naming scheme.


I'm struggling against Java to find a design I am happy with. Forget about parsing JSON, blah blah blah, from a design point of view I want to know I can store this data that meets these requirements:



  1. Each bucket needs to be able to store a default value in case server doesn't send one down

  2. bucket.isBucket(...) should be type safe, ie, if we use an enum here, you shouldn't be able to pass in a bucket that doesn't belong without getting an error.

  3. Easy, simple access. Buckets.some_cool_bucket.is(val1) would be ideal.

  4. Minimal boiler plate in adding a new bucket

  5. Non confusing design


Ignoring these requirements, we could implement this as follows:



enum Bucket {
some_cool_bucket('val1'),
another_bucket('name');

Bucket(String default) {
[...]
}

// Assume this retrieves the stored value sent down from the server.
String getVal() {
[...]
}

boolean is(String val) {
return getVal().equals(val);
}
}


With usage Bucket.some_cool_bucket.is('val1'). Naturally, we would want to extend this by changing the type signature of is() to accept some val enum defined by some_cool_bucket. Since the values a bucket can take are not uniform, we'd have to define this inside the some_cool_bucket enum. But you can't have enums inside enums in Java.


Ok, reset. Let's try this again:



public abstract class BaseBucket<E extends Enum<E>> {

private final Class<E> mClazz;
private final E mDefaultBucket;

public BaseBucket(Class<E> clazz, E defaultBucket) {
mClazz = clazz;
mDefaultBucket = defaultBucket;
}

// Assume this retrieves the stored value sent down from the server, uses
// getName() to match with the data.
protected E getVal() {
[...]
}

protected abstract String getName();

public boolean is(E test) {
return getVal() == test;
}
}

public class SomeCoolBucket extends BaseBucket<Val> {
public SomeCoolBucket() {
super(Val.class, Val.val1);
}

@Override
public String getName() {
return "some_cool_bucket";
}

public enum Val {
val1, val2, val3;
}
}

public Buckets {
public static final SomeCoolBucket some_cool_bucket = new SomeCoolBucket();
}


Ok, this works! Great. It meets all the functional requirements, but it's cumbersome and I hate having to create a new class for each bucket. I find it hard to justify all of the code, though I believe the requirements are sound.


Does anyone have a better solution for this?


Design for request bucket information on client

I'm trying to find the best way to design the client side storage of "buckets". To explain, the server sends down info like:



{
'buckets': {
'some_cool_bucket' : 'val1',
'another_bucket' : 'name'
}
}


Where the values can be



'some_cool_bucket' : 'val1' | 'val2' | 'val3'
'another_bucket' : 'name' | 'cool' | 'other'


basically all these buckets are enums with all the possible values known to both client and server, though there aren't common constraints, like buckets can have any number of possible values (no size limit), and any naming scheme.


I'm struggling against Java to find a design I am happy with. Forget about parsing JSON, blah blah blah, from a design point of view I want to know I can store this data that meets these requirements:



  1. Each bucket needs to be able to store a default value in case server doesn't send one down

  2. bucket.isBucket(...) should be type safe, ie, if we use an enum here, you shouldn't be able to pass in a bucket that doesn't belong without getting an error.

  3. Easy, simple access. Buckets.some_cool_bucket.is(val1) would be ideal.

  4. Minimal boiler plate in adding a new bucket

  5. Non confusing design


Ignoring these requirements, we could implement this as follows:



enum Bucket {
some_cool_bucket('val1'),
another_bucket('name');

Bucket(String default) {
[...]
}

// Assume this retrieves the stored value sent down from the server.
String getVal() {
[...]
}

boolean is(String val) {
return getVal().equals(val);
}
}


With usage Bucket.some_cool_bucket.is('val1'). Naturally, we would want to extend this by changing the type signature of is() to accept some val enum defined by some_cool_bucket. Since the values a bucket can take are not uniform, we'd have to define this inside the some_cool_bucket enum. But you can't have enums inside enums in Java.


Ok, reset. Let's try this again:



public abstract class BaseBucket<E extends Enum<E>> {

private final Class<E> mClazz;
private final E mDefaultBucket;

public BaseBucket(Class<E> clazz, E defaultBucket) {
mClazz = clazz;
mDefaultBucket = defaultBucket;
}

// Assume this retrieves the stored value sent down from the server, uses
// getName() to match with the data.
protected E getVal() {
[...]
}

protected abstract String getName();

public boolean is(E test) {
return getVal() == test;
}
}

public class SomeCoolBucket extends BaseBucket<Val> {
public SomeCoolBucket() {
super(Val.class, Val.val1);
}

@Override
public String getName() {
return "some_cool_bucket";
}

public enum Val {
val1, val2, val3;
}
}

public Buckets {
public static final SomeCoolBucket some_cool_bucket = new SomeCoolBucket();
}


Ok, this works! Great. It meets all the functional requirements, but it's cumbersome and I hate having to create a new class for each bucket. I find it hard to justify all of the code, though I believe the requirements are sound.


Does anyone have a better solution for this?


Pros and cons of a global base object for all objects in Doctrine2

What are the pros and cons of using a global base entity for all entities in my Doctrine2 model?


I am considering having all of my domain entities extend a single generic base entity, so that I can specify the target entity of an association to be the base entity class, thereby allowing that association to hold any entity in my domain.


My associations will still be as specific as possible: an Order entity will contain Product objects, not Base objects. But more 'meta'-like functionality like status log items, authorization specs, etc., can be specified very generically by defining LogItems and AuthorizationRules having an association to BaseEntity, instead of with specific items.


I am not seeing this approach anywhere, but there seems to be some use or power to having all classes extend off a base Object entity ('Java-style'). But perhaps I am needlessly overcomplicating things.


Is a base entity in Doctrine2 a good idea?


Pros and cons of a global base object for all objects in Doctrine2

What are the pros and cons of using a global base entity for all entities in my Doctrine2 model?


I am considering having all of my domain entities extend a single generic base entity, so that I can specify the target entity of an association to be the base entity class, thereby allowing that association to hold any entity in my domain.


My associations will still be as specific as possible: an Order entity will contain Product objects, not Base objects. But more 'meta'-like functionality like status log items, authorization specs, etc., can be specified very generically by defining LogItems and AuthorizationRules having an association to BaseEntity, instead of with specific items.


I am not seeing this approach anywhere, but there seems to be some use or power to having all classes extend off a base Object entity ('Java-style'). But perhaps I am needlessly overcomplicating things.


Is a base entity in Doctrine2 a good idea?


iOS - masking with colorWithPatternImage without repeating on .png file

I'm triying to fill with pattern my mask images (.png)



UIImageView *imageView = (UIImageView*)_maskView.contentView;
imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.tintColor = [UIColor colorWithPatternImage:image];


Now I have done what I want to do. But with a problem. Here is the screenshot:


screenshot


In this screenshot I have these layers back to front;



  1. mainImageView -> contains the waterfall image.

  2. maskView -> lies on the top of the mainImageView. It is a custom UIView. It contains an imageView named contentView.

  3. contentView -> An UIImageView. Subview of maskView. Contains the mask image. I use colorWithPatternImage code on its tintColor.


As you can see, my pattern image is tiling(or repeating or whatever you call).


I tried to resize the pattern image to the size of the imageView also tried resizing to high resolutions like 4000X4000 with no luck.


Tried something like



self.layer.contents = (id)[UIImage imageNamed:@"freshBackground.png"].CGImage;


but this code is filling the entire imageView.


Now I'm out of options. Can anyone help me on this? Thank you.


iOS - masking with colorWithPatternImage without repeating on .png file

I'm triying to fill with pattern my mask images (.png)



UIImageView *imageView = (UIImageView*)_maskView.contentView;
imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.tintColor = [UIColor colorWithPatternImage:image];


Now I have done what I want to do. But with a problem. Here is the screenshot:


screenshot


In this screenshot I have these layers back to front;



  1. mainImageView -> contains the waterfall image.

  2. maskView -> lies on the top of the mainImageView. It is a custom UIView. It contains an imageView named contentView.

  3. contentView -> An UIImageView. Subview of maskView. Contains the mask image. I use colorWithPatternImage code on its tintColor.


As you can see, my pattern image is tiling(or repeating or whatever you call).


I tried to resize the pattern image to the size of the imageView also tried resizing to high resolutions like 4000X4000 with no luck.


Tried something like



self.layer.contents = (id)[UIImage imageNamed:@"freshBackground.png"].CGImage;


but this code is filling the entire imageView.


Now I'm out of options. Can anyone help me on this? Thank you.


Is it better to pass objects as parameters or as returns in Java? [on hold]

I'm surprised I haven't found more discussion on the subject, but is there a generally-accepted-practice, guideline, or even rule about which way of passing objects is superior in Java?


Example:



public ArrayList<Thing> getThings() {
ArrayList<Thing> temp = new ArrayList<Thing>();
temp.add(new Thing());
temp.add(new Thing());
return temp;
}


Versus



public void getThings(ArrayList<Thing> things) {
things.add(new Thing());
things.add(new Thing());
}


The first way, to me, is clearer but the second way takes advantage of language features. My boss and I have butted heads over this before, and I'd like to know what the programming community's opinion is. Preferably a Java-specific, sourced answer, but I'll take any advice.


Is it better to pass objects as parameters or as returns in Java? [on hold]

I'm surprised I haven't found more discussion on the subject, but is there a generally-accepted-practice, guideline, or even rule about which way of passing objects is superior in Java?


Example:



public ArrayList<Thing> getThings() {
ArrayList<Thing> temp = new ArrayList<Thing>();
temp.add(new Thing());
temp.add(new Thing());
return temp;
}


Versus



public void getThings(ArrayList<Thing> things) {
things.add(new Thing());
things.add(new Thing());
}


The first way, to me, is clearer but the second way takes advantage of language features. My boss and I have butted heads over this before, and I'd like to know what the programming community's opinion is. Preferably a Java-specific, sourced answer, but I'll take any advice.


haxe case pattern reuseing - maybe as a variable

Is there any way to save patterns in haxe? I have several switch functions, and some of them have the same pattern, and to make the code cleaner, I'd like to save them to a common array or something. So I have something like



switch (field) {
case 'x' | 'y' | 'color' : doThis();
}
//...other function...
switch (field) {
case 'x' | 'y' | 'color' : doThat();
}


and I want to have something like



myPattern = 'x' | 'y' | 'color';

switch (field) {
case myPattern : doThis();
}
//...other function...
switch (field) {
case myPattern : doThat();
}

haxe case pattern reuseing - maybe as a variable

Is there any way to save patterns in haxe? I have several switch functions, and some of them have the same pattern, and to make the code cleaner, I'd like to save them to a common array or something. So I have something like



switch (field) {
case 'x' | 'y' | 'color' : doThis();
}
//...other function...
switch (field) {
case 'x' | 'y' | 'color' : doThat();
}


and I want to have something like



myPattern = 'x' | 'y' | 'color';

switch (field) {
case myPattern : doThis();
}
//...other function...
switch (field) {
case myPattern : doThat();
}

What happens with references to window when we close it and how to prevent this memory leakage?

I'm interested in the issue of preventing memory leakages in long life java applications. So let's say we create a window for each user in some server side application. We have someone who is specifically develops this window. The developer of this window does something at onClose(), but the references to this window are still there. Which means that if the end user of that window has put some 1MB image into this window via some reference, then for 1000 users we'll have 1GB un-freed memory.


What is the common way (maybe some design pattern) to prevent such memory leakage in long life applications?


I'm reading this article in JavaWorld and I see that in the end it solves something that is related to references inside listeners. I don't understand the connection of it to this problem.


I do understand that we can simply create an external listeners which'll put null into all of the references to that window once it is closed, however I don't think it's the best solution (e.g. think of what happens when someone create a reference and forgets to add such a listener!).


What happens with references to window when we close it and how to prevent this memory leakage?

I'm interested in the issue of preventing memory leakages in long life java applications. So let's say we create a window for each user in some server side application. We have someone who is specifically develops this window. The developer of this window does something at onClose(), but the references to this window are still there. Which means that if the end user of that window has put some 1MB image into this window via some reference, then for 1000 users we'll have 1GB un-freed memory.


What is the common way (maybe some design pattern) to prevent such memory leakage in long life applications?


I'm reading this article in JavaWorld and I see that in the end it solves something that is related to references inside listeners. I don't understand the connection of it to this problem.


I do understand that we can simply create an external listeners which'll put null into all of the references to that window once it is closed, however I don't think it's the best solution (e.g. think of what happens when someone create a reference and forgets to add such a listener!).


History tables - Increasing rows with no limits

I'm no DBA and wanted to discuss or learn the best practices for tables whose rows can grow without a limit.


I saw that, at least where I work, the solution was to use a hot table (with 1 month of data, for example), and a process to move the "old" data to an identical table (history table).


The justification is that it would improve the performance of the newest data and historical data is subjected to a longer time to complete a survey.


For such approach, applications that query this data are required to identify whether the search time will only get the hot table or it should query also the history table.


I am little outraged by this solution. I am aware that Oracle has solutions for problems as this (Index / Tablespace / Cluster). As I have little knowledge, I cannot show them better and more accurate options.


Can anyone share some experience for cases like mine?


Could you provide me with some directions?


History tables - Increasing rows with no limits

I'm no DBA and wanted to discuss or learn the best practices for tables whose rows can grow without a limit.


I saw that, at least where I work, the solution was to use a hot table (with 1 month of data, for example), and a process to move the "old" data to an identical table (history table).


The justification is that it would improve the performance of the newest data and historical data is subjected to a longer time to complete a survey.


For such approach, applications that query this data are required to identify whether the search time will only get the hot table or it should query also the history table.


I am little outraged by this solution. I am aware that Oracle has solutions for problems as this (Index / Tablespace / Cluster). As I have little knowledge, I cannot show them better and more accurate options.


Can anyone share some experience for cases like mine?


Could you provide me with some directions?


dimanche 28 décembre 2014

Builder Design Pattern on a search engine

I am new to design patterns or if I am already using them I did not notice it. I looked on design patterns and I am trying to apply the Builder design pattern on a search feature on a website, so that instead of a whole method with a bunch of if statements, I would like to create a more neater code using the Builder design pattern.


My problem is that the builder design pattern main goal is to avoid having a bunch of methods, therefore creating several parts of the search feature because without it I'll end up with 16 methods if I have 4 options in my search engine.


My question, how would you do it ?


Builder Design Pattern on a search engine

I am new to design patterns or if I am already using them I did not notice it. I looked on design patterns and I am trying to apply the Builder design pattern on a search feature on a website, so that instead of a whole method with a bunch of if statements, I would like to create a more neater code using the Builder design pattern.


My problem is that the builder design pattern main goal is to avoid having a bunch of methods, therefore creating several parts of the search feature because without it I'll end up with 16 methods if I have 4 options in my search engine.


My question, how would you do it ?


Creating objects from xml and csv files - which OOP-Pattern? (Java) [on hold]

Let's say i have got a class called Car with attributes like seats or top speed and i want to create some cars based on xml and csv files.


The xml file could look like this:



<cars>
<car seats="4" top-speed="100" />
<car seats="2" top-speed="200" />
</cars>


csv:



2;150
5;110




Which classes you would create? Don't forget that there could be a third datasource later!


My problem is'nt the parsing of the files, but finding good names/structe for my classes. Are there two factories (XmlFactory/CsvFactory)? Or are they builders? Or readers? Is CarXmlFactory better than XmlCarFactory?


I can't find descriptive names.


Thank you!


Creating objects from xml and csv files - which OOP-Pattern? (Java) [on hold]

Let's say i have got a class called Car with attributes like seats or top speed and i want to create some cars based on xml and csv files.


The xml file could look like this:



<cars>
<car seats="4" top-speed="100" />
<car seats="2" top-speed="200" />
</cars>


csv:



2;150
5;110




Which classes you would create? Don't forget that there could be a third datasource later!


My problem is'nt the parsing of the files, but finding good names/structe for my classes. Are there two factories (XmlFactory/CsvFactory)? Or are they builders? Or readers? Is CarXmlFactory better than XmlCarFactory?


I can't find descriptive names.


Thank you!


samedi 27 décembre 2014

Notify all objects of a class of property change

I have following class and there can be many objects instantiated from this class. I want to have this Visibility property shared among all objects. When visibility is changed for one object, all other objects should have the same value. I have view(XAML) per viewmodel which has this Visibility property bound to one element's visibility.



public class ViewModel
{
private Visibility visibility = Visibility.Visible;
public Visibility Visibility
{
get { return this.visibility; }
set { this.CheckAccessInvoke(() => this.SetAndRaisePropertyChanged(ref this.visibility, alue)); }
}
}


What could be a good solution for this?


Notify all objects of a class of property change

I have following class and there can be many objects instantiated from this class. I want to have this Visibility property shared among all objects. When visibility is changed for one object, all other objects should have the same value. I have view(XAML) per viewmodel which has this Visibility property bound to one element's visibility.



public class ViewModel
{
private Visibility visibility = Visibility.Visible;
public Visibility Visibility
{
get { return this.visibility; }
set { this.CheckAccessInvoke(() => this.SetAndRaisePropertyChanged(ref this.visibility, alue)); }
}
}


What could be a good solution for this?


Design patterns/guidelines on creating application/product configurations

I was wondering if there are any design patterns, best practices, guidelines or documented widsom/best practices for creating 'application configuration' structure, data, and files. I realize this questions has been partially touched in some posts but I hope this questions questions the topic from another angle.



  • Basically what kind of analysis goes into creating the configuration structure?

  • What analysis needs to take place?

  • What kind of forces are at play that one needs to consider?

  • When does application configuration analysis/creation come into play; is it an after-thought or followup to the main design activity or interdependent with the main development flow?

  • What pros and cons for structuring configuration data in one way rather than another.

  • What kind of requirements needs to be captured or aware of (flexibility, override capability, lack of duplication, selection, ...)


Specifically my interest in in developing the hierarchy of configuration settings.


Are there any actual projects out there with sufficient level of sophistication whose configuration could be studied?


My question is not aimed at format or type of files (whether to use flat ini, or json, xml, ...) but at how to arrive at configurations in the first place.


Thanks


Design patterns/guidelines on creating application/product configurations

I was wondering if there are any design patterns, best practices, guidelines or documented widsom/best practices for creating 'application configuration' structure, data, and files. I realize this questions has been partially touched in some posts but I hope this questions questions the topic from another angle.



  • Basically what kind of analysis goes into creating the configuration structure?

  • What analysis needs to take place?

  • What kind of forces are at play that one needs to consider?

  • When does application configuration analysis/creation come into play; is it an after-thought or followup to the main design activity or interdependent with the main development flow?

  • What pros and cons for structuring configuration data in one way rather than another.

  • What kind of requirements needs to be captured or aware of (flexibility, override capability, lack of duplication, selection, ...)


Specifically my interest in in developing the hierarchy of configuration settings.


Are there any actual projects out there with sufficient level of sophistication whose configuration could be studied?


My question is not aimed at format or type of files (whether to use flat ini, or json, xml, ...) but at how to arrive at configurations in the first place.


Thanks


how can i improve a shallow copy of a singleton pattern?

I have a class whitch has a singleton implementation and a Clone() method for shallow copy never affecting initial singleton : class A Static Singleton A // ... Collection of data, array... () ... // private constructor of A() { if singleton == null initialize data () }



public function Get() as A
if Singleton == null)
{
singleton = new(A)
}

function Clone()
obj as A = new A()
A.Collections = copy of collection (*) // shallow copy : reference only of data array in List of Collection
return A


Remark :

I think that it is anti-pattern because singleton can be "clone"

Question : How can i benefit to the shallow copy with a good design pattern ?


how can i improve a shallow copy of a singleton pattern?

I have a class whitch has a singleton implementation and a Clone() method for shallow copy never affecting initial singleton : class A Static Singleton A // ... Collection of data, array... () ... // private constructor of A() { if singleton == null initialize data () }



public function Get() as A
if Singleton == null)
{
singleton = new(A)
}

function Clone()
obj as A = new A()
A.Collections = copy of collection (*) // shallow copy : reference only of data array in List of Collection
return A


Remark :

I think that it is anti-pattern because singleton can be "clone"

Question : How can i benefit to the shallow copy with a good design pattern ?


Auto generate unique IDs using the singleton pattern

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.


In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries. They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).


The given example:



class IDGenerator
{
private static IDGenerator instance;

private int nextID;

private IDGenerator() { nextID = 1; }

[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}

public int nextId()
{
return nextID++;
}
}


Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.


I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).


But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.


So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?


Auto generate unique IDs using the singleton pattern

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.


In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries. They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).


The given example:



class IDGenerator
{
private static IDGenerator instance;

private int nextID;

private IDGenerator() { nextID = 1; }

[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}

public int nextId()
{
return nextID++;
}
}


Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.


I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).


But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.


So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?


Which design pattern for my proxy Rule

I have a proxy HttpHandler that gets a url from user as a querystring parameter like following.



public class MagicProxy : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string requestUrl = HttpUtility.UrlDecode(context.Request.QueryString["url"]);
}

public bool IsReusable
{
get
{
return false;
}
}
}


url parameter is like this:



http://server1.com/service?method=get&request=GetInfo
http://server1.com/service?method=get&request=GetFeatures
http://server1.com/service?method=get&request=GetImage&Format=PNG


I am parsing url querystring. Because some users can use method=get and can not use method=post. Some users can use request=GetInfo and some users can not use reguest=GetImage.


These are my rules by users. I want to use desgin pattern to implement these rules. But I could not decide to use. Specification, Strategy, or else. I am new at desing patterns.



public interface IRule{}
public class UserCanUseGetMethod:IRule{}


How can I combine rules and user?


Which design pattern for my proxy Rule

I have a proxy HttpHandler that gets a url from user as a querystring parameter like following.



public class MagicProxy : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string requestUrl = HttpUtility.UrlDecode(context.Request.QueryString["url"]);
}

public bool IsReusable
{
get
{
return false;
}
}
}


url parameter is like this:



http://server1.com/service?method=get&request=GetInfo
http://server1.com/service?method=get&request=GetFeatures
http://server1.com/service?method=get&request=GetImage&Format=PNG


I am parsing url querystring. Because some users can use method=get and can not use method=post. Some users can use request=GetInfo and some users can not use reguest=GetImage.


These are my rules by users. I want to use desgin pattern to implement these rules. But I could not decide to use. Specification, Strategy, or else. I am new at desing patterns.



public interface IRule{}
public class UserCanUseGetMethod:IRule{}


How can I combine rules and user?


Whitelisting of Patterns in a Set of Patterns with controlled Multi Occurance in Regex

I want the following examples to return match



  • I like foobar.com

  • I like google.com and foobar.com

  • I like foobar.com and google.com

  • I like foobargoogle.com and googlefoobar.com

  • I like yahoo.com and foobar.com

  • I like foobar.com and yahoo.com

  • I like foobaryahoo.com and yahoofoobar.com


I don't want the following examples to return match



  • I like yahoo.com

  • I like foobaryahoo.com

  • I like google.com

  • I like foobargoogle.com

  • I like google.com and yahoo.com

  • I like foobargoogle.com and foobaryahoo.com


Note - It's not an equal match but a contain match


I tried the following Regex Pattern:



(?!(^.*((google)|(yahoo))\.com.*$))(^.*\w+\.com.*$)


but as soon as either "google.com" or "yahoo.com" occured, it terminated with no match even if "foobar.com" occured before it.


eg. I like foobar.com but not google.com


Basically, I want it to ignore "google.com" and "yahoo.com" anywhere in the string and detect any other type: "\w+.com".


Note:



  • google.com and yahoo.com are just examples. So, it should ignore match set of any string length of alphanumeric characters

  • ignore case and whitespace


Whitelisting of Patterns in a Set of Patterns with controlled Multi Occurance in Regex

I want the following examples to return match



  • I like foobar.com

  • I like google.com and foobar.com

  • I like foobar.com and google.com

  • I like foobargoogle.com and googlefoobar.com

  • I like yahoo.com and foobar.com

  • I like foobar.com and yahoo.com

  • I like foobaryahoo.com and yahoofoobar.com


I don't want the following examples to return match



  • I like yahoo.com

  • I like foobaryahoo.com

  • I like google.com

  • I like foobargoogle.com

  • I like google.com and yahoo.com

  • I like foobargoogle.com and foobaryahoo.com


Note - It's not an equal match but a contain match


I tried the following Regex Pattern:



(?!(^.*((google)|(yahoo))\.com.*$))(^.*\w+\.com.*$)


but as soon as either "google.com" or "yahoo.com" occured, it terminated with no match even if "foobar.com" occured before it.


eg. I like foobar.com but not google.com


Basically, I want it to ignore "google.com" and "yahoo.com" anywhere in the string and detect any other type: "\w+.com".


Note:



  • google.com and yahoo.com are just examples. So, it should ignore match set of any string length of alphanumeric characters

  • ignore case and whitespace


vendredi 26 décembre 2014

Good Constructor Design

In general, is it a bad idea to construct other objects within a constructor (I generally don't like it)? Suppose an object of type A needs an instance of type B. The instance of type B should be static, because I truly only want one copy of it...really...no, seriously. Type b also raises events that type A will need to handle. Type B is in an external library that I have no control over. Making my type B object static seems like it would be an annoyance on testing. I originally wanted to make A completely static, because it is essentially a proxy of B. Maybe that's the real question. What's a good proxy design when the object being proxies requires initialization? I can think of at least three options:



  1. Pass in the arguments need to construct type A along with type B. The constructor of type A then constructs type B. (Calling a create method to return type B from within the constructor would be the same basic concept.

  2. Pass in a constructed object.

  3. Create an initialize method.


I don't like option 1 because it's just complicated. I would have to do all sort of type B initialization code, set up event handlers, etc. I don't like option 2 because I don't want the outside world knowing about this dependency. Class A is the only type that will EVER interact with Class B. In general, I don't like initialize methods, or methods that "guard" the state of an encapsulated dependency. I seem to end up with a lot of code like this:



if (typeB != null && typeB.State != Unitialized)


Yuck.


Here is some sample code that I am working with. Just looking for how to make this really clean, simple and easy to maintain.



public class A
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private B b;

public new A(string productName, string serviceName)
{
b = new B
{
ProductName = productName,
ServiceName = serviceName
};

b.SomethingHappened += b_HandleIt;


Thanks in advance.


Good Constructor Design

In general, is it a bad idea to construct other objects within a constructor (I generally don't like it)? Suppose an object of type A needs an instance of type B. The instance of type B should be static, because I truly only want one copy of it...really...no, seriously. Type b also raises events that type A will need to handle. Type B is in an external library that I have no control over. Making my type B object static seems like it would be an annoyance on testing. I originally wanted to make A completely static, because it is essentially a proxy of B. Maybe that's the real question. What's a good proxy design when the object being proxies requires initialization? I can think of at least three options:



  1. Pass in the arguments need to construct type A along with type B. The constructor of type A then constructs type B. (Calling a create method to return type B from within the constructor would be the same basic concept.

  2. Pass in a constructed object.

  3. Create an initialize method.


I don't like option 1 because it's just complicated. I would have to do all sort of type B initialization code, set up event handlers, etc. I don't like option 2 because I don't want the outside world knowing about this dependency. Class A is the only type that will EVER interact with Class B. In general, I don't like initialize methods, or methods that "guard" the state of an encapsulated dependency. I seem to end up with a lot of code like this:



if (typeB != null && typeB.State != Unitialized)


Yuck.


Here is some sample code that I am working with. Just looking for how to make this really clean, simple and easy to maintain.



public class A
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private B b;

public new A(string productName, string serviceName)
{
b = new B
{
ProductName = productName,
ServiceName = serviceName
};

b.SomethingHappened += b_HandleIt;


Thanks in advance.