samedi 31 janvier 2015

Eliminating re-implementation of methods from the built class in Builder, while keeping it with nested calling

I have a class that has to be checked for being set for all of the variables, while more variables that must be set could be added:



class A{
setVar1();
setVar2();
setVar3();
}


I have to check that all three sets were called before building it. How can I create a Builder that:


A. won't have to re-call the above methods again (like implementing inside builder another setVar1() setVar2() which will call those from A - this is a hell for future maintenance to me to implement each of those setters twice). So bad example for me here would be:



class ABuilder{
build(){...}
builderSetVar1(){...} //HELL NO!
builderSetVar2(){...} //NO NO NO!!!
...
}


B. Will check before building that all must have members are set (the user of the package, won't be able to have incomplete A)


C. Will allow nested one-line building of A (Builder...SetVar1(...)....SetVar2(...).build())


Is it even possible to achieve all of those three goals? I tried too many possibilities and in every solution


All in object oriented.


Eliminating re-implementation of methods from the built class in Builder, while keeping it with nested calling

I have a class that has to be checked for being set for all of the variables, while more variables that must be set could be added:



class A{
setVar1();
setVar2();
setVar3();
}


I have to check that all three sets were called before building it. How can I create a Builder that:


A. won't have to re-call the above methods again (like implementing inside builder another setVar1() setVar2() which will call those from A - this is a hell for future maintenance to me to implement each of those setters twice). So bad example for me here would be:



class ABuilder{
build(){...}
builderSetVar1(){...} //HELL NO!
builderSetVar2(){...} //NO NO NO!!!
...
}


B. Will check before building that all must have members are set (the user of the package, won't be able to have incomplete A)


C. Will allow nested one-line building of A (Builder...SetVar1(...)....SetVar2(...).build())


Is it even possible to achieve all of those three goals? I tried too many possibilities and in every solution


All in object oriented.


Code re-Design due to changing requirement

I have a method "AddUser" that validates User DTO and saves the record to the Database.


The requirement to send an email after the user is created and add the record to the messaging queue for some other application to consume got added later on. Due to changes/updates in requirements there were several updates to the userservice class each time. The code to send an email and adding to the queue is in a separate class exposed via an interface.


To avoid making change to userservice class each time the requirement changes, I am thinking of re-designing the class:

1. Create a command object AddUserCommand that saves the record to the database and decorate it with "EmailManager" and "MessagingQueue" classes that dynamically assigns more responsibility to "AddUserCommand" object.

2. Create a XML file that has the name of the class and method to invoke for AddUser method. Read the xml file(read once in a static constructor) and invoke methods at runtime. This would obviously be done by reflection so would be expensive.

e.g. <method name="userservice">

<add methodname="sendemail" type="EmailManager"/>

</method>


My question: Is there any existing open source framework or any design pattern that can be used to best solve this problem.



UserService.cs class
public void AddUser(UserDTO)
{
userRepository.Add(UserBO);
emailManager.SendEmail(userBO);
messagingQueue.Add(userBO);
}

Code re-Design due to changing requirement

I have a method "AddUser" that validates User DTO and saves the record to the Database.


The requirement to send an email after the user is created and add the record to the messaging queue for some other application to consume got added later on. Due to changes/updates in requirements there were several updates to the userservice class each time. The code to send an email and adding to the queue is in a separate class exposed via an interface.


To avoid making change to userservice class each time the requirement changes, I am thinking of re-designing the class:

1. Create a command object AddUserCommand that saves the record to the database and decorate it with "EmailManager" and "MessagingQueue" classes that dynamically assigns more responsibility to "AddUserCommand" object.

2. Create a XML file that has the name of the class and method to invoke for AddUser method. Read the xml file(read once in a static constructor) and invoke methods at runtime. This would obviously be done by reflection so would be expensive.

e.g. <method name="userservice">

<add methodname="sendemail" type="EmailManager"/>

</method>


My question: Is there any existing open source framework or any design pattern that can be used to best solve this problem.



UserService.cs class
public void AddUser(UserDTO)
{
userRepository.Add(UserBO);
emailManager.SendEmail(userBO);
messagingQueue.Add(userBO);
}

Where in the object-oriented design process is an architecture pattern chosen?

Most object oriented analysis and design books and resources describe the process where the analysis phase is followed by identifying classes. I understand that experience will often give you an idea of which architecture (if any) you should apply but is there a specific point in the object oriented design phase where this should occur? I'm about to start a large personal project and I want to make sure my choice of architecture doesn't disregard something from the analysis phase.


Where in the object-oriented design process is an architecture pattern chosen?

Most object oriented analysis and design books and resources describe the process where the analysis phase is followed by identifying classes. I understand that experience will often give you an idea of which architecture (if any) you should apply but is there a specific point in the object oriented design phase where this should occur? I'm about to start a large personal project and I want to make sure my choice of architecture doesn't disregard something from the analysis phase.


What's a good pattern or style in REST Resource classes to encapsulate error handling?

I've run into this pattern several times. In pseudo-code:


public class BlahResource { if (thisError) buildResponse(BAD_REQUEST); if (thatError) buildResponse(CONFLICT); ... doSomething(); return buildResponse(SUCCESS); }


Doesn't look too bad, but when you have a million error conditions to handle, too much business logic accretes into the Resource class and the noise quickly overwhelms the story of what the code is actually doing.


Since in a resource the error conditions are returning something, an exception thrown from a service doesn't seem right to me. And a status object encapsulating different combinations of return conditions and setups seems like overkill.


Is there something obvious I'm missing in how this can be coded in a logical, clear way? Possibly something functional/Guava/lambda-based that I'm missing, or just a regular OO solution.


What's a good pattern or style in REST Resource classes to encapsulate error handling?

I've run into this pattern several times. In pseudo-code:


public class BlahResource { if (thisError) buildResponse(BAD_REQUEST); if (thatError) buildResponse(CONFLICT); ... doSomething(); return buildResponse(SUCCESS); }


Doesn't look too bad, but when you have a million error conditions to handle, too much business logic accretes into the Resource class and the noise quickly overwhelms the story of what the code is actually doing.


Since in a resource the error conditions are returning something, an exception thrown from a service doesn't seem right to me. And a status object encapsulating different combinations of return conditions and setups seems like overkill.


Is there something obvious I'm missing in how this can be coded in a logical, clear way? Possibly something functional/Guava/lambda-based that I'm missing, or just a regular OO solution.


PHPUnit TDD questions

I'm learning TDD and I have some questions. - The idea is to create a Simple Factory guided by tests. The thing is that my test coverage isn't 100% and that is where my questions lies.


Before I show you the code, let me explain what I want.



  • The factory is responsable to instantiate the classes and to test this I have to simulate the instantiation of the class, doing this I'm using a concrete class, it works, but when I see the test coverage, the concrete class appear and it isn't 100% tested. (You will understand). - I want to avoid that, I want to test the factory as abstract as possible.

  • And the other problem is that I want to insert the factory as dependency on the constructor, how to test this?


The coverage:



  • PizzaStore.php - 33,33% - The constructor with the factory dependency isn't tested.

  • PizzaFactory.php - 100%

  • Pizza.php - 100%

  • Pizza/Greek.php - 0.00% - Appeared after testing the factory using the concrete class.


yoda


PizzaTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaTest extends PHPUnit_Framework_TestCase {

private $pizza;

public function setUp()
{
$this->pizza = $this->getMockForAbstractClass('Pattern\SimpleFactory\Pizza');
}

/**
* @covers Pattern\SimpleFactory\Pizza::setName
* @covers Pattern\SimpleFactory\Pizza::getName
*/
public function testPizzaSetsAndReturnsTheExpectedName()
{
$pizzaName = 'Greek Pizza';
$this->pizza->setName($pizzaName);
$this->assertEquals($pizzaName, $this->pizza->getName());
}

/**
* @covers Pattern\SimpleFactory\Pizza::setDescription
* @covers Pattern\SimpleFactory\Pizza::getDescription
*/
public function testPizzaSetsAndReturnsTheExpectedDescription()
{
$pizzaDescription = 'A Pepperoni-style pizza with dough, tomato, and cheese';
$this->pizza->setDescription($pizzaDescription);
$this->assertEquals($pizzaDescription, $this->pizza->getDescription());
}

}


PizzaStoreTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaStoreTest extends PHPUnit_Framework_TestCase {

/**
* @covers Pattern\SimpleFactory\PizzaStore::order
*/
public function testStoreShouldReturnsTheRequestedPizzaWhenOrdered()
{
$factory = new PizzaFactory();
$store = new PizzaStore($factory);
$pizza = $store->order('greek');
$this->assertInstanceOf('Pattern\SimpleFactory\Pizza', $pizza);
}

}


PizzaFactoryTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaFactoryTest extends PHPUnit_Framework_TestCase {

/**
* @var PizzaFactory
*/
private $pizzaFactory;

public function setUp()
{
$this->pizzaFactory = new PizzaFactory();
}

/**
* @covers Pattern\SimpleFactory\PizzaFactory::make
*/
public function testPizzaFactoryMakesAPizza()
{
$pizza = $this->pizzaFactory->make('greek');
$this->assertInstanceOf('Pattern\SimpleFactory\Pizza', $pizza);
}

/**
* @covers Pattern\SimpleFactory\PizzaFactory::make
*/
public function testPizzaFactoryReturnsNullWhenMakingANonexistentPizza()
{
$pizza = $this->pizzaFactory->make(null);
$this->isNull($pizza);
}

}


PizzaStore.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
class PizzaStore {

/**
* @var PizzaFactory
*/
private $factory;

/**
* @param PizzaFactory $factory
*/
function __construct(PizzaFactory $factory)
{
$this->factory = $factory;
}

/**
* @param string $name
* @return null|Pizza
*/
public function order($name)
{
return $this->factory->make($name);
}

}


PizzaFactory.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
class PizzaFactory {

/**
* @var array
*/
private $pizzas = [
'greek' => 'Pattern\SimpleFactory\Pizza\Greek',
'pepperoni' => 'Pattern\SimpleFactory\Pizza\Pepperoni',
];

/**
* @param string $name
* @return null|Pizza
*/
public function make($name)
{
if (isset($this->pizzas[$name]))
{
return new $this->pizzas[$name];
}

return null;
}

}


Pizza.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
abstract class Pizza {

/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;

/**
* @return string
*/
public function getName()
{
return $this->name;
}

/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}

/**
* @return string
*/
public function getDescription()
{
return $this->description;
}

/**
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}

}


Pizza\Pepperoni.php:



<?php namespace Pattern\SimpleFactory\Pizza;

use Pattern\SimpleFactory\Pizza;

/**
* @package Pattern\SimpleFactory\Pizza
*/
class Pepperoni extends Pizza {

function __construct()
{
parent::setName('Pizza Pepperoni');
parent::setDescription('A Pepperoni-style pizza with dough, tomato, and cheese');
}

}


Pizza\Greek.php:



<?php namespace Pattern\SimpleFactory\Pizza;

use Pattern\SimpleFactory\Pizza;

/**
* @package Pattern\SimpleFactory\Pizza
*/
class Greek extends Pizza {

function __construct()
{
parent::setName('Pizza Greek');
parent::setDescription('A Greek-style pizza with feta cheese, onion, olive and tomato');
}

}


And that is it, anything wrong, please, say it. Thank you in advance.


PHPUnit TDD questions

I'm learning TDD and I have some questions. - The idea is to create a Simple Factory guided by tests. The thing is that my test coverage isn't 100% and that is where my questions lies.


Before I show you the code, let me explain what I want.



  • The factory is responsable to instantiate the classes and to test this I have to simulate the instantiation of the class, doing this I'm using a concrete class, it works, but when I see the test coverage, the concrete class appear and it isn't 100% tested. (You will understand). - I want to avoid that, I want to test the factory as abstract as possible.

  • And the other problem is that I want to insert the factory as dependency on the constructor, how to test this?


The coverage:



  • PizzaStore.php - 33,33% - The constructor with the factory dependency isn't tested.

  • PizzaFactory.php - 100%

  • Pizza.php - 100%

  • Pizza/Greek.php - 0.00% - Appeared after testing the factory using the concrete class.


yoda


PizzaTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaTest extends PHPUnit_Framework_TestCase {

private $pizza;

public function setUp()
{
$this->pizza = $this->getMockForAbstractClass('Pattern\SimpleFactory\Pizza');
}

/**
* @covers Pattern\SimpleFactory\Pizza::setName
* @covers Pattern\SimpleFactory\Pizza::getName
*/
public function testPizzaSetsAndReturnsTheExpectedName()
{
$pizzaName = 'Greek Pizza';
$this->pizza->setName($pizzaName);
$this->assertEquals($pizzaName, $this->pizza->getName());
}

/**
* @covers Pattern\SimpleFactory\Pizza::setDescription
* @covers Pattern\SimpleFactory\Pizza::getDescription
*/
public function testPizzaSetsAndReturnsTheExpectedDescription()
{
$pizzaDescription = 'A Pepperoni-style pizza with dough, tomato, and cheese';
$this->pizza->setDescription($pizzaDescription);
$this->assertEquals($pizzaDescription, $this->pizza->getDescription());
}

}


PizzaStoreTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaStoreTest extends PHPUnit_Framework_TestCase {

/**
* @covers Pattern\SimpleFactory\PizzaStore::order
*/
public function testStoreShouldReturnsTheRequestedPizzaWhenOrdered()
{
$factory = new PizzaFactory();
$store = new PizzaStore($factory);
$pizza = $store->order('greek');
$this->assertInstanceOf('Pattern\SimpleFactory\Pizza', $pizza);
}

}


PizzaFactoryTest.php:



<?php namespace Pattern\SimpleFactory;

use PHPUnit_Framework_TestCase;

class PizzaFactoryTest extends PHPUnit_Framework_TestCase {

/**
* @var PizzaFactory
*/
private $pizzaFactory;

public function setUp()
{
$this->pizzaFactory = new PizzaFactory();
}

/**
* @covers Pattern\SimpleFactory\PizzaFactory::make
*/
public function testPizzaFactoryMakesAPizza()
{
$pizza = $this->pizzaFactory->make('greek');
$this->assertInstanceOf('Pattern\SimpleFactory\Pizza', $pizza);
}

/**
* @covers Pattern\SimpleFactory\PizzaFactory::make
*/
public function testPizzaFactoryReturnsNullWhenMakingANonexistentPizza()
{
$pizza = $this->pizzaFactory->make(null);
$this->isNull($pizza);
}

}


PizzaStore.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
class PizzaStore {

/**
* @var PizzaFactory
*/
private $factory;

/**
* @param PizzaFactory $factory
*/
function __construct(PizzaFactory $factory)
{
$this->factory = $factory;
}

/**
* @param string $name
* @return null|Pizza
*/
public function order($name)
{
return $this->factory->make($name);
}

}


PizzaFactory.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
class PizzaFactory {

/**
* @var array
*/
private $pizzas = [
'greek' => 'Pattern\SimpleFactory\Pizza\Greek',
'pepperoni' => 'Pattern\SimpleFactory\Pizza\Pepperoni',
];

/**
* @param string $name
* @return null|Pizza
*/
public function make($name)
{
if (isset($this->pizzas[$name]))
{
return new $this->pizzas[$name];
}

return null;
}

}


Pizza.php:



<?php namespace Pattern\SimpleFactory;

/**
* @package Pattern\SimpleFactory
*/
abstract class Pizza {

/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;

/**
* @return string
*/
public function getName()
{
return $this->name;
}

/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}

/**
* @return string
*/
public function getDescription()
{
return $this->description;
}

/**
* @param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}

}


Pizza\Pepperoni.php:



<?php namespace Pattern\SimpleFactory\Pizza;

use Pattern\SimpleFactory\Pizza;

/**
* @package Pattern\SimpleFactory\Pizza
*/
class Pepperoni extends Pizza {

function __construct()
{
parent::setName('Pizza Pepperoni');
parent::setDescription('A Pepperoni-style pizza with dough, tomato, and cheese');
}

}


Pizza\Greek.php:



<?php namespace Pattern\SimpleFactory\Pizza;

use Pattern\SimpleFactory\Pizza;

/**
* @package Pattern\SimpleFactory\Pizza
*/
class Greek extends Pizza {

function __construct()
{
parent::setName('Pizza Greek');
parent::setDescription('A Greek-style pizza with feta cheese, onion, olive and tomato');
}

}


And that is it, anything wrong, please, say it. Thank you in advance.


Wrapper Classes are not suited for callback frameworks


The disadvantages of wrapper classes are few. One caveat is that wrapper classes are not suited for use in callback frameworks, wherein objects pass self references to other objects for subsequent invocations (“callbacks”). Because a wrapped object doesn’t know of its wrapper, it passes a reference to itself (this) and callbacks elude the wrapper.



Can someone explain what this means with an example perhaps. It is written in Effective Java but I did not completely understand it.


Wrapper Classes are not suited for callback frameworks


The disadvantages of wrapper classes are few. One caveat is that wrapper classes are not suited for use in callback frameworks, wherein objects pass self references to other objects for subsequent invocations (“callbacks”). Because a wrapped object doesn’t know of its wrapper, it passes a reference to itself (this) and callbacks elude the wrapper.



Can someone explain what this means with an example perhaps. It is written in Effective Java but I did not completely understand it.


How to design a singleton class that needs a parameter only on the first instantiation?

I have a singleton class, ORMHelper, which needs a parameter(FileReader) only on the first time of its instantiation.



ORMHelper.getInstance(FileReader fr);


When this is done the singleton parses the file and does its stuff. Subsequent instantiations don't need the FileReader as the parsing is already done.



ORMHelper.getInstance();


There is a check in the getInstance() to figure out if the file has already been parsed and it throws up an exception otherwise.


Is there a better way to do this?


How to design a singleton class that needs a parameter only on the first instantiation?

I have a singleton class, ORMHelper, which needs a parameter(FileReader) only on the first time of its instantiation.



ORMHelper.getInstance(FileReader fr);


When this is done the singleton parses the file and does its stuff. Subsequent instantiations don't need the FileReader as the parsing is already done.



ORMHelper.getInstance();


There is a check in the getInstance() to figure out if the file has already been parsed and it throws up an exception otherwise.


Is there a better way to do this?


vendredi 30 janvier 2015

Optimizing data driven web application

I've built a simple web application using Java Server Faces (JSF) where I have a web page with a link and when I click that link, I just go to the database(MySQL) and fetch a list of items and would display in the web page. I've used Hibernate as an ORM tool.


I just have total of 10-15 entries in the database table that I query and the hibernate query is like "from myObject" which returns all the entries in the table.


Now, I'm trying to improve the performance of this application by limiting the number of queries to the database on every click on that link.


So I started learning about hibernate first level caching, second level caching, and Ehcache. Now I've some basic understanding on how they work.


Here is my question


Question : Let's say that the users of this application are divided into n groups-g1,g2,...,gn and each group has m users. When a user from group g1 clicks that link, I want to show a list of items specific to that particular group g1. Basically I want to show different list of items for different groups of users when they click on the link in the web page. As I want to show the same list of items to users in the same group, I want to limit the calls to database when the users from same group click that link. It would be great if some one could give their suggestions or give me some pointers that would help me go forward.


It is the same object that holds the data shown for all the user groups. There are adds, updates, and deletes to Entries(list of items shown in the web page) in the database. The list of items shown to the user is not static.


Optimizing data driven web application

I've built a simple web application using Java Server Faces (JSF) where I have a web page with a link and when I click that link, I just go to the database(MySQL) and fetch a list of items and would display in the web page. I've used Hibernate as an ORM tool.


I just have total of 10-15 entries in the database table that I query and the hibernate query is like "from myObject" which returns all the entries in the table.


Now, I'm trying to improve the performance of this application by limiting the number of queries to the database on every click on that link.


So I started learning about hibernate first level caching, second level caching, and Ehcache. Now I've some basic understanding on how they work.


Here is my question


Question : Let's say that the users of this application are divided into n groups-g1,g2,...,gn and each group has m users. When a user from group g1 clicks that link, I want to show a list of items specific to that particular group g1. Basically I want to show different list of items for different groups of users when they click on the link in the web page. As I want to show the same list of items to users in the same group, I want to limit the calls to database when the users from same group click that link. It would be great if some one could give their suggestions or give me some pointers that would help me go forward.


It is the same object that holds the data shown for all the user groups. There are adds, updates, and deletes to Entries(list of items shown in the web page) in the database. The list of items shown to the user is not static.


Using Java Reflection to determine which class to instantiate

There is a Message superclass and there are various Message subclasses like WeddingMessage, GreetingMessage, FarewellMessage, Birthday Message.


The Message superclass has a constructor:



public Message(String messageType){
this.messageType = messageType;
}


The message subclasses all have different constructors, but they all make a call to the superclass, where they pass the messageType as an argument So for example:



public BirthdayMessage( String name, int age){
super("birthday");
System.out.println("Happy birthday " + name + "You are " + age " years old");

public FareWellMessage(String name, String message){
super("farewell");
System.out.println(message + " " + name);
}


The messageType which is created is determined by arguments passed in by the user. So for example, if a user inserts 'birthday John 12', then a BirthdayMessage will be created with parameters John and 12. If a user enters 'farewell Grace take care' then an instance of FarewellMessage is created with those parameters.


Instead of having a bunch of if/else statements or a switch case, in the form of something like-



words[] = userinput.slice(' ');
word1 = words[0];
if (word1 == birthday)
create new BirthdayMessage(parameters here)
if (word1 == wedding)
create new weddingMessage(parameters here)


etc


How could i use reflection to determine which type of Message class to create. My current idea is to use the File class to get all the Files in the package which contain the message subclasses. Then use reflection to get each of their constructor parameter types and see if they match the parameters given by user input. Then make instances of those matching classes with random parameters. When made, the subclass will make a call to its superclass constructor with its messageType. Then i can check to see if the messageType variable matches the user input.


So if the user enters 'birthday john 23' I find all constructors in the package that take a String and an int as parameters and that have a field messageType(inherited from Message). Then i create an instance of that class and check if the messageType is == to the first word in the user input (birthday in this case). If it is, then i create an instance of that class with the user provided parameters.


Is there a better way to do this with reflection?


Using Java Reflection to determine which class to instantiate

There is a Message superclass and there are various Message subclasses like WeddingMessage, GreetingMessage, FarewellMessage, Birthday Message.


The Message superclass has a constructor:



public Message(String messageType){
this.messageType = messageType;
}


The message subclasses all have different constructors, but they all make a call to the superclass, where they pass the messageType as an argument So for example:



public BirthdayMessage( String name, int age){
super("birthday");
System.out.println("Happy birthday " + name + "You are " + age " years old");

public FareWellMessage(String name, String message){
super("farewell");
System.out.println(message + " " + name);
}


The messageType which is created is determined by arguments passed in by the user. So for example, if a user inserts 'birthday John 12', then a BirthdayMessage will be created with parameters John and 12. If a user enters 'farewell Grace take care' then an instance of FarewellMessage is created with those parameters.


Instead of having a bunch of if/else statements or a switch case, in the form of something like-



words[] = userinput.slice(' ');
word1 = words[0];
if (word1 == birthday)
create new BirthdayMessage(parameters here)
if (word1 == wedding)
create new weddingMessage(parameters here)


etc


How could i use reflection to determine which type of Message class to create. My current idea is to use the File class to get all the Files in the package which contain the message subclasses. Then use reflection to get each of their constructor parameter types and see if they match the parameters given by user input. Then make instances of those matching classes with random parameters. When made, the subclass will make a call to its superclass constructor with its messageType. Then i can check to see if the messageType variable matches the user input.


So if the user enters 'birthday john 23' I find all constructors in the package that take a String and an int as parameters and that have a field messageType(inherited from Message). Then i create an instance of that class and check if the messageType is == to the first word in the user input (birthday in this case). If it is, then i create an instance of that class with the user provided parameters.


Is there a better way to do this with reflection?


Builder pattern not working

So I am currently working on a game in Java with the help of LibGDX. Recently I bumped into a problem, when tryin to make a Builder class for another class which will have a lot of parameters, so I guessed it needs a Builder class. Being the confident java programmer I am, I started it and I found a problem which I can't correct. I have already looked it up on the internet and found some examples, but everything seems OK for me. Maybe you can help. The code needed:



public class SpecialTile implements MyAnimation {

/**
* Class builder for SpecialTile
* @author Zsemberi Daniel
*
*/
public static class SpecialTileBuilder {
/*
* Drawables
*/
private Sprite image;
private Animation anim;

//position
private Point position;

/**
* Sprite path constructor
*/
public SpecialTileBuilder(String imagePath) {
this.image = new Sprite((Texture) Load.manager.get(imagePath));
}

/**
* Image constructor
*/
public SpecialTileBuilder(Sprite image) {
this.image = image;
}

/**
* Animation constructor
*/
public SpecialTileBuilder(Animation anim) {
this.anim = anim;
}

//Set position
public SpecialTileBuilder setPosition(Point position) {
this.position = position;
return this;
}


public SpecialTile createSpecialTile() {
return new SpecialTile(this);
}
}

/*
* Drawables
*/
private Sprite image;
private Animation anim;

private float stateTime = 0f;

//position
private Point position;

protected SpecialTile(SpecialTileBuilder builder) {
image = builder.image;
anim = builder.anim;
position = builder.position;
}

/**
* Hits the player
*/
public boolean isHit(Sprite sprite) {
if(anim == null)
return image.getBoundingRectangle().contains(sprite.getBoundingRectangle());
else
return new Sprite(getCurrentFrame()).getBoundingRectangle().contains(sprite.getBoundingRectangle());
}

/**
* If it is triggered it does something
*/
public void doTheHarlemShake(Sprite sprite) {

}

public Sprite getSprite() { return image; }
public Animation getAnimation() { return anim; }

public float getX() { return position.x; }
public float getY() { return position.y; }

/*
* Animation stuff
*/

@Override
public TextureRegion getCurrentFrame() {
return anim.getKeyFrame(stateTime, true);
}

@Override
public void updateAnimation(float delta) {
stateTime += delta;
}

}


So up there you can see the whole class (I thought you may need it) where I wrote the Buidler. And here comes how I would use it if it worked.



SpecialTile.SpecialTileBuilder("test.png")
.setPosition(new Point(2, 2))
.createSpecialTile();


So it says in eclipse that I have got this problem:



The method SpecialTileBuilder(String) is undefined for the type SpecialTile



Builder pattern not working

So I am currently working on a game in Java with the help of LibGDX. Recently I bumped into a problem, when tryin to make a Builder class for another class which will have a lot of parameters, so I guessed it needs a Builder class. Being the confident java programmer I am, I started it and I found a problem which I can't correct. I have already looked it up on the internet and found some examples, but everything seems OK for me. Maybe you can help. The code needed:



public class SpecialTile implements MyAnimation {

/**
* Class builder for SpecialTile
* @author Zsemberi Daniel
*
*/
public static class SpecialTileBuilder {
/*
* Drawables
*/
private Sprite image;
private Animation anim;

//position
private Point position;

/**
* Sprite path constructor
*/
public SpecialTileBuilder(String imagePath) {
this.image = new Sprite((Texture) Load.manager.get(imagePath));
}

/**
* Image constructor
*/
public SpecialTileBuilder(Sprite image) {
this.image = image;
}

/**
* Animation constructor
*/
public SpecialTileBuilder(Animation anim) {
this.anim = anim;
}

//Set position
public SpecialTileBuilder setPosition(Point position) {
this.position = position;
return this;
}


public SpecialTile createSpecialTile() {
return new SpecialTile(this);
}
}

/*
* Drawables
*/
private Sprite image;
private Animation anim;

private float stateTime = 0f;

//position
private Point position;

protected SpecialTile(SpecialTileBuilder builder) {
image = builder.image;
anim = builder.anim;
position = builder.position;
}

/**
* Hits the player
*/
public boolean isHit(Sprite sprite) {
if(anim == null)
return image.getBoundingRectangle().contains(sprite.getBoundingRectangle());
else
return new Sprite(getCurrentFrame()).getBoundingRectangle().contains(sprite.getBoundingRectangle());
}

/**
* If it is triggered it does something
*/
public void doTheHarlemShake(Sprite sprite) {

}

public Sprite getSprite() { return image; }
public Animation getAnimation() { return anim; }

public float getX() { return position.x; }
public float getY() { return position.y; }

/*
* Animation stuff
*/

@Override
public TextureRegion getCurrentFrame() {
return anim.getKeyFrame(stateTime, true);
}

@Override
public void updateAnimation(float delta) {
stateTime += delta;
}

}


So up there you can see the whole class (I thought you may need it) where I wrote the Buidler. And here comes how I would use it if it worked.



SpecialTile.SpecialTileBuilder("test.png")
.setPosition(new Point(2, 2))
.createSpecialTile();


So it says in eclipse that I have got this problem:



The method SpecialTileBuilder(String) is undefined for the type SpecialTile



.Net Architecture Design Suggesion

I need to re-design whole architecture for below applications We have an applications CRM - for back office and call center (account. contact) Web application - online application (account, contact ) GP - (Customer Invoice processing)


Above all application talking to each other by scribe but all scribe run every 10 to 15 min interval respectively.


But many time scribe job failed and dependent application has to wait for 10s+ min to get updated or new data.


So management has decided to get some good solution to get latest data to every system at same time.


Solution: 1) I requested to prepare Service Layer which talk to all application to CRM and all data should only store in CRM. But in that case web team is totally depend on CRM only. If CRM goes down everything is stop.


End Goal : - Eliminate Scribe - All data should be available in all other system real time or nearly real time.


Suggestion: If you guys came across any solution or tool which really help us to resolve above issue.


In advance, Appreciate your support.


-Den


.Net Architecture Design Suggesion

I need to re-design whole architecture for below applications We have an applications CRM - for back office and call center (account. contact) Web application - online application (account, contact ) GP - (Customer Invoice processing)


Above all application talking to each other by scribe but all scribe run every 10 to 15 min interval respectively.


But many time scribe job failed and dependent application has to wait for 10s+ min to get updated or new data.


So management has decided to get some good solution to get latest data to every system at same time.


Solution: 1) I requested to prepare Service Layer which talk to all application to CRM and all data should only store in CRM. But in that case web team is totally depend on CRM only. If CRM goes down everything is stop.


End Goal : - Eliminate Scribe - All data should be available in all other system real time or nearly real time.


Suggestion: If you guys came across any solution or tool which really help us to resolve above issue.


In advance, Appreciate your support.


-Den


Can I make sure observe callback in order?

Any way to get called observer fuction in order?


I have ObserverFoo class.


and both ChildObserverA and ChildObserverB inherited ObserverFoo.


the problem is the observer callback should be called from ChildObserverA first.


Because there's dependency between ChildObserverA and ChildObserverB.


is it any good pattern to make sure ChildObserverA::Observe() called first?


Can I make sure observe callback in order?

Any way to get called observer fuction in order?


I have ObserverFoo class.


and both ChildObserverA and ChildObserverB inherited ObserverFoo.


the problem is the observer callback should be called from ChildObserverA first.


Because there's dependency between ChildObserverA and ChildObserverB.


is it any good pattern to make sure ChildObserverA::Observe() called first?


Pattern for processing custom Java annotations

I have read a lot of tutorials about Java annotations lately and I like the idea of creating a custom one. Most articles cover the very basic idea and fairly simple implementations. I'm missing a proper pattern to process my annotation, though.


Lets say I have a custom annotation @Foobar to initialize fields. I need to pass all classes that use this annotation to my processor, let's call it FoobarProcessor:



public class AnnotatedClass {
@Foobar
private String test = "";

static {
FoobarProcessor.process(AnnotatedClass.class);
}
}


Is there any approach to overcome this drawback? Is there any single point that all classes pass, where I can easily apply my annotation processor?


Pattern for processing custom Java annotations

I have read a lot of tutorials about Java annotations lately and I like the idea of creating a custom one. Most articles cover the very basic idea and fairly simple implementations. I'm missing a proper pattern to process my annotation, though.


Lets say I have a custom annotation @Foobar to initialize fields. I need to pass all classes that use this annotation to my processor, let's call it FoobarProcessor:



public class AnnotatedClass {
@Foobar
private String test = "";

static {
FoobarProcessor.process(AnnotatedClass.class);
}
}


Is there any approach to overcome this drawback? Is there any single point that all classes pass, where I can easily apply my annotation processor?


Best Pratices Domain Entities Composition?

I have the following project structure:



- Application.DataAccess : IUserRepository....
- Application.DataAccess : IUserRepository....
- Application.Busines : IUserService, ICustomerService...
- Application.Infrastructure : Logging, Exception handling... (Cross-cutting.)
- Application.Domain : User, Customer... (Entities)
- Application.WindowsForms : UI


Almost all of my service operations will have the following parameters:



  • User userOfOperation (That is in Doimain layer and represents a user)

  • PlaceOfOperation placeOfOperation (That is in Doimain layer and represents a branch office)


I think that i should create a new class and encapsulate this entities on it then call it"OperationSource".


like:



class OperationSource
{
Domain.User UserOfOperation { get; set; }
Domain.Enterprise PlaceOfOperation { get; set; }
}


Where should i put the compose classes (e.g OperationSource) in this case, on my Application.Busines or Application.Domain?


Best Pratices Domain Entities Composition?

I have the following project structure:



- Application.DataAccess : IUserRepository....
- Application.DataAccess : IUserRepository....
- Application.Busines : IUserService, ICustomerService...
- Application.Infrastructure : Logging, Exception handling... (Cross-cutting.)
- Application.Domain : User, Customer... (Entities)
- Application.WindowsForms : UI


Almost all of my service operations will have the following parameters:



  • User userOfOperation (That is in Doimain layer and represents a user)

  • PlaceOfOperation placeOfOperation (That is in Doimain layer and represents a branch office)


I think that i should create a new class and encapsulate this entities on it then call it"OperationSource".


like:



class OperationSource
{
Domain.User UserOfOperation { get; set; }
Domain.Enterprise PlaceOfOperation { get; set; }
}


Where should i put the compose classes (e.g OperationSource) in this case, on my Application.Busines or Application.Domain?


How to use "static data" properly with (Fluent) NHibernate

In our database we have "static data" where ids are assigned manually by hand and they are the same through out the whole life of project. In various places, we check if objects have the same ids with these static data such as:


enter image description here


Although, the data never changes using ids inside the code is really awful and I would like to change this to more readable and maintainable structure. I am thinking about using an enum but I am not sure how should I init the enum with fluent nhibernate. Any ideas/tips on how I can achieve this ?


How to use "static data" properly with (Fluent) NHibernate

In our database we have "static data" where ids are assigned manually by hand and they are the same through out the whole life of project. In various places, we check if objects have the same ids with these static data such as:


enter image description here


Although, the data never changes using ids inside the code is really awful and I would like to change this to more readable and maintainable structure. I am thinking about using an enum but I am not sure how should I init the enum with fluent nhibernate. Any ideas/tips on how I can achieve this ?


need to call provider to provider, but i wont

I've been refactoring a project so we get some proper architecture, though I've run into a problem which i can't seem to figure out without "hacking" the design pattern. Intro: presentation : contains my aspx files and ashx files, and only calls the next layer. Business logic : Contains Providers, which are used by presentation layer, and calls the data layer. data layer : Contains Collections of the entities and are called by the business logic layer. And has the connection to the database.


So pretty standard.


I have a OrderProvider method that should return a Order based on a orderId from the presentation layer, but that order also needs to have its ProductBundleLines And subscriptions on the productBundleLines. So a Order contains a list of productBundleLines which then contains a subscription object.


Normally when i want to get the productBundleLines i use the ProductBundleProvider, and the ProductbundleProvider has a method that fits my need to retrieve the productBundleLines with subscriptions PERFECTLY. But as i know of the pattern, this isn't allowed. Im not allowed to call a provider from another provider.


It would just be silly if i had the same code now in the orderProvider, though it would solve the problem. Or is there any other way that this could be made ?


ive sketched the setup in a uml, which would give a better overview of the structure. And just forget about the Managers, those arn't relevant in this case :) UML link


Hopefully this makes sense for you guys!


need to call provider to provider, but i wont

I've been refactoring a project so we get some proper architecture, though I've run into a problem which i can't seem to figure out without "hacking" the design pattern. Intro: presentation : contains my aspx files and ashx files, and only calls the next layer. Business logic : Contains Providers, which are used by presentation layer, and calls the data layer. data layer : Contains Collections of the entities and are called by the business logic layer. And has the connection to the database.


So pretty standard.


I have a OrderProvider method that should return a Order based on a orderId from the presentation layer, but that order also needs to have its ProductBundleLines And subscriptions on the productBundleLines. So a Order contains a list of productBundleLines which then contains a subscription object.


Normally when i want to get the productBundleLines i use the ProductBundleProvider, and the ProductbundleProvider has a method that fits my need to retrieve the productBundleLines with subscriptions PERFECTLY. But as i know of the pattern, this isn't allowed. Im not allowed to call a provider from another provider.


It would just be silly if i had the same code now in the orderProvider, though it would solve the problem. Or is there any other way that this could be made ?


ive sketched the setup in a uml, which would give a better overview of the structure. And just forget about the Managers, those arn't relevant in this case :) UML link


Hopefully this makes sense for you guys!


jeudi 29 janvier 2015

How do I manage the memory of a command processor in C++?

I'm trying to build a simple command processor in C++ and I'm stuck on a not so easy issue. I have a class (CommandProcessor) that takes a request of some form. This request is transformed into an object (Command) and put onto a queue or started immediately if there is no running command. The Command object is responsible for fullfilling the request. When it's completed, the CommandProcessor is notified so it can starts processing another command. This callback is where my problem lies : the CommandProcessor should delete the Command at this point, however, since the CommandProcessor is notified during the execution of a method in the Command object, the Command object ends up indirectly deleting itself.


I could possibly delay the callback at the end of the method to ensure that nothing gets executed after it, but I feel that this is a bit of a brittle design.


My other solution was to keep a reference to the completed command and dlete it when a new request enters the CommandProcessor, but there's 2 problems with that, the first being that I'm basically using memory that may never be deleted and the second is that the Command object contains some resources that needs to be released as soon as possible (e.g.file handler).


I'm probably not the first guy to stumble on this problem so I was wondering if anybody had a better idea.


Thanks!


How do I manage the memory of a command processor in C++?

I'm trying to build a simple command processor in C++ and I'm stuck on a not so easy issue. I have a class (CommandProcessor) that takes a request of some form. This request is transformed into an object (Command) and put onto a queue or started immediately if there is no running command. The Command object is responsible for fullfilling the request. When it's completed, the CommandProcessor is notified so it can starts processing another command. This callback is where my problem lies : the CommandProcessor should delete the Command at this point, however, since the CommandProcessor is notified during the execution of a method in the Command object, the Command object ends up indirectly deleting itself.


I could possibly delay the callback at the end of the method to ensure that nothing gets executed after it, but I feel that this is a bit of a brittle design.


My other solution was to keep a reference to the completed command and dlete it when a new request enters the CommandProcessor, but there's 2 problems with that, the first being that I'm basically using memory that may never be deleted and the second is that the Command object contains some resources that needs to be released as soon as possible (e.g.file handler).


I'm probably not the first guy to stumble on this problem so I was wondering if anybody had a better idea.


Thanks!


Alphabets only directive

I am trying to achieve a directive that would be used to accept only alphabets into the text box i.e from a-z or A-z I did try to do this by,



angular.module('myApp', []).directive('alphabetsOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {

if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/^[a-zA-Z]+$/, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}

return transformedInput;
});
}
};
});

function MyCtrl($scope) {
$scope.name = ''
}


but this does not works .


tried with pattern



'/^[a-zA-Z]$/'


but no success. Can anyone help me with this.


Alphabets only directive

I am trying to achieve a directive that would be used to accept only alphabets into the text box i.e from a-z or A-z I did try to do this by,



angular.module('myApp', []).directive('alphabetsOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {

if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/^[a-zA-Z]+$/, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}

return transformedInput;
});
}
};
});

function MyCtrl($scope) {
$scope.name = ''
}


but this does not works .


tried with pattern



'/^[a-zA-Z]$/'


but no success. Can anyone help me with this.


Publish/subscribe in Redis

I really have been struggling understanding the concept of publish/subscribe in Redis I'm looking for an example to make it tangible; I followed their wire protocol example, but they don't make sense to me at all and I don't get the concenpt; I have just copied and pasted their example here; could you please help me understand the logic at least in this example:


Wire protocol example



SUBSCRIBE first second

*3
$9
subscribe
$5
first
:1
*3
$9
subscribe
$6
second
:2


At this point, from another client we issue a PUBLISH operation against the channel named second:



> PUBLISH second Hello
This is what the first client receives:
*3
$7
message
$6
second
$5
Hello


Now the client unsubscribes itself from all the channels using the UNSUBSCRIBE command without additional arguments:



UNSUBSCRIBE
*3
$11
unsubscribe
$6
second
:1
*3
$11
unsubscribe
$5
first
:0


Thanks so much!


Publish/subscribe in Redis

I really have been struggling understanding the concept of publish/subscribe in Redis I'm looking for an example to make it tangible; I followed their wire protocol example, but they don't make sense to me at all and I don't get the concenpt; I have just copied and pasted their example here; could you please help me understand the logic at least in this example:


Wire protocol example



SUBSCRIBE first second

*3
$9
subscribe
$5
first
:1
*3
$9
subscribe
$6
second
:2


At this point, from another client we issue a PUBLISH operation against the channel named second:



> PUBLISH second Hello
This is what the first client receives:
*3
$7
message
$6
second
$5
Hello


Now the client unsubscribes itself from all the channels using the UNSUBSCRIBE command without additional arguments:



UNSUBSCRIBE
*3
$11
unsubscribe
$6
second
:1
*3
$11
unsubscribe
$5
first
:0


Thanks so much!


How can I consolidate code for checking true/false, retrieving an error message, and returning a JSON response?

Consider the class below (assume it has a simple constructor not shown here):



class Poll{

public $id = 0;
public $errorMessage = "";

public function vote($age = 0){
if($age <= 18){
// do something here
}
else{
$this->errorMessage = "You are not old enough to vote.";
return false;
}

try{
// do something here
}
catch (\Exception $e){
$this->errorMessage = "Voting failed!";
return false;
}

// do some more things here

return true;
}
}


Now consider using it like this:



// Setup an initial object we'll use in a JSON response
$response = new \stdClass;
$response->error = "";
$response->message = "";

// Let's vote
$myPoll = new Poll($input['id']);
if(!$myPoll->vote($input['age'])){
// Opps something went wrong
$response->error = "Error: ".$myPoll->errorMessage;
return json_encode($response);
}

// Voting finished, return success message
$response->message = "Voted Successfully!";
return json_encode($response);


I'm going to be doing this a lot throughout the application. I'm checking a method for true/false and then asking the object for an error message to give out in some fashion. The classes that produce errors may not necessarily be used for JSON responses, but it will be quite often. Also notice the two techniques used in the class for producing an error. How should I alter/add classes like the one shown here (or what design pattern would help here) to consolidate this approach and take more advantage of the power of OOP?


How can I consolidate code for checking true/false, retrieving an error message, and returning a JSON response?

Consider the class below (assume it has a simple constructor not shown here):



class Poll{

public $id = 0;
public $errorMessage = "";

public function vote($age = 0){
if($age <= 18){
// do something here
}
else{
$this->errorMessage = "You are not old enough to vote.";
return false;
}

try{
// do something here
}
catch (\Exception $e){
$this->errorMessage = "Voting failed!";
return false;
}

// do some more things here

return true;
}
}


Now consider using it like this:



// Setup an initial object we'll use in a JSON response
$response = new \stdClass;
$response->error = "";
$response->message = "";

// Let's vote
$myPoll = new Poll($input['id']);
if(!$myPoll->vote($input['age'])){
// Opps something went wrong
$response->error = "Error: ".$myPoll->errorMessage;
return json_encode($response);
}

// Voting finished, return success message
$response->message = "Voted Successfully!";
return json_encode($response);


I'm going to be doing this a lot throughout the application. I'm checking a method for true/false and then asking the object for an error message to give out in some fashion. The classes that produce errors may not necessarily be used for JSON responses, but it will be quite often. Also notice the two techniques used in the class for producing an error. How should I alter/add classes like the one shown here (or what design pattern would help here) to consolidate this approach and take more advantage of the power of OOP?


Java Triangle Pattern Printing

Trying to write a program that will print a number of triangle patterns, both hollow and solid. I have implemented this by using constructors, along with other utility methods. As of right now I am trying to display a triangle of size 7 with the following character (*).


for some reason I am only getting the following output: 0000. I have created a test triangle down below



Triangle s1 = new Triangle(7, '*');
s1.displaySolidUL();

public class Triangle {

// Declare & intialize data fields
final private static char defaultChar = '*';
final private static int defaultSize = 10;

private static char triangleChar;
private static int triangleSize;

private static int triangleCount = 0;


// Constructors
public Triangle() {
this(defaultSize, defaultChar);
}

public Triangle(int s) {
this(s, defaultChar);
}

public Triangle(char n) {
this(n, defaultChar);
}

public Triangle(int size, char character) {
if ((triangleSize <= 0) || (triangleSize > 50)) {
size = defaultSize;
// System.out.println(errorSizeMsg);
} else if (triangleChar == ' ') {
character = defaultChar;
// System.out.println(errorBlankChar);
} else {
size = triangleSize;
character = triangleChar;

// increment triangle count
triangleCount++;
}
}

// Accessors and Mutators
public int getSize() {
return triangleSize;
}

public char getChar() {
return triangleChar;
}

public void setSize(int size) {
triangleSize = size;
}

public void setChar(char character) {
triangleChar = character;
}


// Main methods for displaying triangles
public void displaySolidLL() {

}

public void displaySolidLR() {

}

public void displaySolidUL() {
for (int x = 0; x <= triangleSize; x++) {
for (int y = 0; y <= triangleSize; y++) {
if (y <= x) {
System.out.print(triangleChar);
}
}
}
System.out.println();
}

public void displaySolidUR() {

}


// Other utility classes
// Printing out new lines
public static void newLine(int numLines) {
for (int i = 0; i < numLines; i++) {
System.out.println();
}
}

// Display triangle count
public static void getTriangleCount() {
System.out.print("The total number of triangles printed equals: " + triangleCount);
}
}

Java Triangle Pattern Printing

Trying to write a program that will print a number of triangle patterns, both hollow and solid. I have implemented this by using constructors, along with other utility methods. As of right now I am trying to display a triangle of size 7 with the following character (*).


for some reason I am only getting the following output: 0000. I have created a test triangle down below



Triangle s1 = new Triangle(7, '*');
s1.displaySolidUL();

public class Triangle {

// Declare & intialize data fields
final private static char defaultChar = '*';
final private static int defaultSize = 10;

private static char triangleChar;
private static int triangleSize;

private static int triangleCount = 0;


// Constructors
public Triangle() {
this(defaultSize, defaultChar);
}

public Triangle(int s) {
this(s, defaultChar);
}

public Triangle(char n) {
this(n, defaultChar);
}

public Triangle(int size, char character) {
if ((triangleSize <= 0) || (triangleSize > 50)) {
size = defaultSize;
// System.out.println(errorSizeMsg);
} else if (triangleChar == ' ') {
character = defaultChar;
// System.out.println(errorBlankChar);
} else {
size = triangleSize;
character = triangleChar;

// increment triangle count
triangleCount++;
}
}

// Accessors and Mutators
public int getSize() {
return triangleSize;
}

public char getChar() {
return triangleChar;
}

public void setSize(int size) {
triangleSize = size;
}

public void setChar(char character) {
triangleChar = character;
}


// Main methods for displaying triangles
public void displaySolidLL() {

}

public void displaySolidLR() {

}

public void displaySolidUL() {
for (int x = 0; x <= triangleSize; x++) {
for (int y = 0; y <= triangleSize; y++) {
if (y <= x) {
System.out.print(triangleChar);
}
}
}
System.out.println();
}

public void displaySolidUR() {

}


// Other utility classes
// Printing out new lines
public static void newLine(int numLines) {
for (int i = 0; i < numLines; i++) {
System.out.println();
}
}

// Display triangle count
public static void getTriangleCount() {
System.out.print("The total number of triangles printed equals: " + triangleCount);
}
}

Where to place autorisation code

I have a PHP MVC application. The business logic is implemented in a service layer and a domain model. My question is, where should I implement authorisation checks? In the service layer? Or the domain model?


In a discussion on the service layer pattern, http://ift.tt/tSAesn, Martin Fowler prefers to separate 'application logic' from 'business logic'. The former goes in the service layer, the latter in the domain objects.


Some of my authorisation rules are complex. Authorisation can depend on the current user, their roles, the state of many otherwise unrelated objects, etc. These seem to belong in the domain objects, or in some cases the factories for these objects.


But in other cases, the rules are quite simple. For example, "only a supervisor can approve a new noticeboard post". In these cases I am tempted to check authorisation in the service layer. It obviates the security requirements, and by putting them in a (mock-able) service layer listener, my code becomes easier to test.


So, the question is should I put simple authorisation checks in the service layer, and more complex ones in the domain objects? Or am I asking for trouble by splitting it across two layers?


Java static class wildcard assignment

So i'm having an issue with the following design pattern I was hoping to get some help on. I keep getting a ClassNotFoundException on my interfaceFactory when I know that it is linked. The InterfaceFactory has been used by a python program in the sense shown below. I tried to implement it in java without much luck. its the java lines near the end that are giving me so much trouble. Any thoughts as to what might be going on?



Public class InterfaceFactory
{
public static Class<? extends Y> classR; //must be initialized in setup
public static Y newY(){ … }
}


In python, the statements



InterfaceFactory.classR = classT #classT not a constructor just the classname
classT.CONSTANT1 =….
classT.CONSTANT2=….


Where classT extends Y as it should. It isn’t a constructor or anything. Just the name of the class. I’m trying to use the 1 line of python code above in java. The implementation I tried was:



InterfaceFactory interfaceFactory = new InterfaceFactory(); //line1
interfaceFactory.classR = classT.class; //line2

classT.CONSTANT1=something;


it throws a ClassNotFoundException on line1.


Where to place autorisation code

I have a PHP MVC application. The business logic is implemented in a service layer and a domain model. My question is, where should I implement authorisation checks? In the service layer? Or the domain model?


In a discussion on the service layer pattern, http://ift.tt/tSAesn, Martin Fowler prefers to separate 'application logic' from 'business logic'. The former goes in the service layer, the latter in the domain objects.


Some of my authorisation rules are complex. Authorisation can depend on the current user, their roles, the state of many otherwise unrelated objects, etc. These seem to belong in the domain objects, or in some cases the factories for these objects.


But in other cases, the rules are quite simple. For example, "only a supervisor can approve a new noticeboard post". In these cases I am tempted to check authorisation in the service layer. It obviates the security requirements, and by putting them in a (mock-able) service layer listener, my code becomes easier to test.


So, the question is should I put simple authorisation checks in the service layer, and more complex ones in the domain objects? Or am I asking for trouble by splitting it across two layers?


Java static class wildcard assignment

So i'm having an issue with the following design pattern I was hoping to get some help on. I keep getting a ClassNotFoundException on my interfaceFactory when I know that it is linked. The InterfaceFactory has been used by a python program in the sense shown below. I tried to implement it in java without much luck. its the java lines near the end that are giving me so much trouble. Any thoughts as to what might be going on?



Public class InterfaceFactory
{
public static Class<? extends Y> classR; //must be initialized in setup
public static Y newY(){ … }
}


In python, the statements



InterfaceFactory.classR = classT #classT not a constructor just the classname
classT.CONSTANT1 =….
classT.CONSTANT2=….


Where classT extends Y as it should. It isn’t a constructor or anything. Just the name of the class. I’m trying to use the 1 line of python code above in java. The implementation I tried was:



InterfaceFactory interfaceFactory = new InterfaceFactory(); //line1
interfaceFactory.classR = classT.class; //line2

classT.CONSTANT1=something;


it throws a ClassNotFoundException on line1.


Object oriented logic with different types for a report

I want to create report mechanism with object oriented design patterns. I want to create a report generator. Reports can be PDF , Wrod, HTML. So I created an interface like this:



interface IReportGenerator{
Report Generate();
}

class PDFReportGenerator : IReportGenerator{
public Report Generate(){
retrun ******;
}
}


But I have many type of reports. FeaturedProductsReport, MostActiveCustomersReport, BestSellerReporst, etc.


Each type of report is different parameters. So I could aggregate them. How can I do object oriented design these logic?


Object oriented logic with different types for a report

I want to create report mechanism with object oriented design patterns. I want to create a report generator. Reports can be PDF , Wrod, HTML. So I created an interface like this:



interface IReportGenerator{
Report Generate();
}

class PDFReportGenerator : IReportGenerator{
public Report Generate(){
retrun ******;
}
}


But I have many type of reports. FeaturedProductsReport, MostActiveCustomersReport, BestSellerReporst, etc.


Each type of report is different parameters. So I could aggregate them. How can I do object oriented design these logic?


Can connection passing through constructor in DAO pattern be unsafe in any case?

I am using DAO pattern. In my case the DAO does not open or close connection; instead connection is passed to it through constructor; it uses that connection to perform its job. Can connection passing through constructor to DAO layer be unsafe in any case? If yes please tell me how.


This is how I am using it:


This is the parent of all DAO implementations:



public abstract class SuperDAO {
private Connection connection;
public SuperDAO(Connection connection) { this.connection = connection; }
public Connection getConnection() { return this.connection; }
}


This is the User business object:



public class User {
private String userId;
private String password;
public String getUserId() { return this.userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getPassword() { return this.password; }
public void setPassword(String password) { this.password = password; }
}


This is the DAO of User business object:



public interface UserDAO {
User getUser(String userId, String password);
}


This is the SQL Server implementation of DAO of User business object:



public class SQLServerUserDAO extends SuperDAO implements UserDAO {
public SQLServerUserDAO(Connection connection) { super(connection); }
public User getUser(String userId, String password) {
// perform task; use getConnection() for connection; dont close connection
}
}


This is the DAO Factory:



public abstract class DAOFactory {
public static final int SQL_SERVER = 1;
protected Connection connection;

public static DAOFactory getDAOFactory(int factoryType, Connection connection) {
DAOFactory daoFactory = null;

switch (factoryType) {
case SQL_SERVER:
daoFactory = new SQLServerDAOFactory();
daoFactory.connection = connection;
break;
}

return daoFactory;
}

public abstract UserDAO getUserDAO();
}


This is the SQL Server implementation of DAO Factory:



public class SQLServerDAOFactory extends DAOFactory {
public UserDAO getUserDAO() {
UserDAO userDAO = new SQLServerUserDAO(connection);
return userDAO;
}
}


And this is how I use it:



Connection connection = null;

try {
connection = ... // obtain a connection;
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER, connection);
UserDAO userDAO = daoFactory.getUserDAO();
...
} finally {
connection.close();
}


In which cases this code will be broken? Please advise.


Thanks


Can connection passing through constructor in DAO pattern be unsafe in any case?

I am using DAO pattern. In my case the DAO does not open or close connection; instead connection is passed to it through constructor; it uses that connection to perform its job. Can connection passing through constructor to DAO layer be unsafe in any case? If yes please tell me how.


This is how I am using it:


This is the parent of all DAO implementations:



public abstract class SuperDAO {
private Connection connection;
public SuperDAO(Connection connection) { this.connection = connection; }
public Connection getConnection() { return this.connection; }
}


This is the User business object:



public class User {
private String userId;
private String password;
public String getUserId() { return this.userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getPassword() { return this.password; }
public void setPassword(String password) { this.password = password; }
}


This is the DAO of User business object:



public interface UserDAO {
User getUser(String userId, String password);
}


This is the SQL Server implementation of DAO of User business object:



public class SQLServerUserDAO extends SuperDAO implements UserDAO {
public SQLServerUserDAO(Connection connection) { super(connection); }
public User getUser(String userId, String password) {
// perform task; use getConnection() for connection; dont close connection
}
}


This is the DAO Factory:



public abstract class DAOFactory {
public static final int SQL_SERVER = 1;
protected Connection connection;

public static DAOFactory getDAOFactory(int factoryType, Connection connection) {
DAOFactory daoFactory = null;

switch (factoryType) {
case SQL_SERVER:
daoFactory = new SQLServerDAOFactory();
daoFactory.connection = connection;
break;
}

return daoFactory;
}

public abstract UserDAO getUserDAO();
}


This is the SQL Server implementation of DAO Factory:



public class SQLServerDAOFactory extends DAOFactory {
public UserDAO getUserDAO() {
UserDAO userDAO = new SQLServerUserDAO(connection);
return userDAO;
}
}


And this is how I use it:



Connection connection = null;

try {
connection = ... // obtain a connection;
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER, connection);
UserDAO userDAO = daoFactory.getUserDAO();
...
} finally {
connection.close();
}


In which cases this code will be broken? Please advise.


Thanks


Absence of DTO vs usage of business objects in repository pattern

I am working on a project. The goal is to develop an MVC app along with an API that will be serving live data to lot of interested parties around the World. MVC app will be simple and will allow users to register for usage of Web API. Web API is the real thing, it would be an interface for the rest of the World for massive amounts of valuable data that we have. Some examples of the methods I am going to expose are:



  1. List GetAssetsByNation (string NationCode, Datetime StartRange, Datetime EndRange )

  2. Bool VerifyAssetDetails (string username, string pwd )

  3. Asset GetAssetDetails ( int AssetId )


There are several designs I am thinking of for web api:


Design 1


DAL: Normal data access methods, caching


Domain Layer: Repository methods implementation, Repository interface, Business (domain) objects/entities


BLL: Business methods (logic & validation)


Presentation: MVC app


Design 2


DAL: Normal data access methods, caching, Repository methods implementation


BLL: Repository interface, Business methods (logic & validation), Business objects/entities


Presentation: MVC app


Which approach do you guys think is better? Would you make any changes to above?



  • I am using the repository pattern because we intend to change our database system from sql to no-sql one in few years. In order to make the switch as painless as possible, repository pattern is being used.

  • I am not using DTO’s here. I cant see any use of them since I think I can pass around Business objects from one layer to another. Is there any con to it given the nature of methods mentioned above.


I am not very good with design patterns, so your opinion of the two above designs would be really appreciated. Thank you very much!


Absence of DTO vs usage of business objects in repository pattern

I am working on a project. The goal is to develop an MVC app along with an API that will be serving live data to lot of interested parties around the World. MVC app will be simple and will allow users to register for usage of Web API. Web API is the real thing, it would be an interface for the rest of the World for massive amounts of valuable data that we have. Some examples of the methods I am going to expose are:



  1. List GetAssetsByNation (string NationCode, Datetime StartRange, Datetime EndRange )

  2. Bool VerifyAssetDetails (string username, string pwd )

  3. Asset GetAssetDetails ( int AssetId )


There are several designs I am thinking of for web api:


Design 1


DAL: Normal data access methods, caching


Domain Layer: Repository methods implementation, Repository interface, Business (domain) objects/entities


BLL: Business methods (logic & validation)


Presentation: MVC app


Design 2


DAL: Normal data access methods, caching, Repository methods implementation


BLL: Repository interface, Business methods (logic & validation), Business objects/entities


Presentation: MVC app


Which approach do you guys think is better? Would you make any changes to above?



  • I am using the repository pattern because we intend to change our database system from sql to no-sql one in few years. In order to make the switch as painless as possible, repository pattern is being used.

  • I am not using DTO’s here. I cant see any use of them since I think I can pass around Business objects from one layer to another. Is there any con to it given the nature of methods mentioned above.


I am not very good with design patterns, so your opinion of the two above designs would be really appreciated. Thank you very much!


PHP - SQL Fluent Interface

i'm looking for a SQL Framework for PHP, with the following aspect that it has a Fluent Interface like described here.


Have you any piece of advice for me? Or some equivalent solution?


Thanks in forward


PHP - SQL Fluent Interface

i'm looking for a SQL Framework for PHP, with the following aspect that it has a Fluent Interface like described here.


Have you any piece of advice for me? Or some equivalent solution?


Thanks in forward


Drawing a Vertical Pyramid in C

I have to get the desired output as follows:



1
2 6
3 7 10
4 8 11 13
5 9 12 14 15


But I can't seem to figure out how to do it. All I get is:



1
2 6
3 7 6
4 8 7 6
5 9 8 7 6


Here is my code:



#include<stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=0;j<i;j++)
{
if((j+1)==1)
printf("%d ",i);
else
printf("%d ",i+n-j);
}
printf("\n");
}
return 0;
}

Repository pattern in DDD, MVC [on hold]

Now this is the first time I am really thinking about design patterns and doing things properly and the most modern way. I have come across a pattern named domain driven design. From my understanding it is simply designing the business logic layer in a more ‘domain-oriented’ way. Although I have worked on massive projects but unfortunately most of them were designed poorly and the separation of logic was not done properly. We have 3 layered applications here but they are very leaky. I am trying to change things here but with no one to guide, I am really confused!


The project is developing an MVC app along with an API that will be serving live data to lot of interested parties around the World. MVC app will be simple and will allow users to register for usage of Web API. Web API is the real thing, it would be an interface for the rest of the World for massive amounts of valuable data that we have. Some examples of the methods I am going to expose are:



  1. Bool VerifyLoginDetails (string username, string pwd )

  2. List GetPlayerByNation (string NationCode, Datetime StartRange, Datetime EndRange )

  3. Player GetPlayerDetails ( int PlayerId )


There are several designs I am thinking of for web api:


Design 1


DAL: Normal data access methods, caching, Repository methods implementation


BLL: Repository interface, Business methods (logic & validation), Business objects/entities


Presentation: MVC app


Design 2


DAL: Normal data access methods, caching


Domain Layer: Repository methods implementation, Repository interface, Business (domain) objects/entities


BLL: Business methods (logic & validation)


Presentation: MVC app


Which approach do you guys think is better? Would you make any changes to above?



  • I am using the repository pattern because we intend to change our database system from sql to no-sql one in few years! In order to make the switch as painless as possible, repository pattern is being used.

  • I am not using DTO’s here. I cant see any use of them since I think I can pass around Business objects from one layer to another. Is there any con to it given the nature of methods mentioned above.


Thank you very much!


Drawing a Vertical Pyramid in C

I have to get the desired output as follows:



1
2 6
3 7 10
4 8 11 13
5 9 12 14 15


But I can't seem to figure out how to do it. All I get is:



1
2 6
3 7 6
4 8 7 6
5 9 8 7 6


Here is my code:



#include<stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=0;j<i;j++)
{
if((j+1)==1)
printf("%d ",i);
else
printf("%d ",i+n-j);
}
printf("\n");
}
return 0;
}

Repository pattern in DDD, MVC [on hold]

Now this is the first time I am really thinking about design patterns and doing things properly and the most modern way. I have come across a pattern named domain driven design. From my understanding it is simply designing the business logic layer in a more ‘domain-oriented’ way. Although I have worked on massive projects but unfortunately most of them were designed poorly and the separation of logic was not done properly. We have 3 layered applications here but they are very leaky. I am trying to change things here but with no one to guide, I am really confused!


The project is developing an MVC app along with an API that will be serving live data to lot of interested parties around the World. MVC app will be simple and will allow users to register for usage of Web API. Web API is the real thing, it would be an interface for the rest of the World for massive amounts of valuable data that we have. Some examples of the methods I am going to expose are:



  1. Bool VerifyLoginDetails (string username, string pwd )

  2. List GetPlayerByNation (string NationCode, Datetime StartRange, Datetime EndRange )

  3. Player GetPlayerDetails ( int PlayerId )


There are several designs I am thinking of for web api:


Design 1


DAL: Normal data access methods, caching, Repository methods implementation


BLL: Repository interface, Business methods (logic & validation), Business objects/entities


Presentation: MVC app


Design 2


DAL: Normal data access methods, caching


Domain Layer: Repository methods implementation, Repository interface, Business (domain) objects/entities


BLL: Business methods (logic & validation)


Presentation: MVC app


Which approach do you guys think is better? Would you make any changes to above?



  • I am using the repository pattern because we intend to change our database system from sql to no-sql one in few years! In order to make the switch as painless as possible, repository pattern is being used.

  • I am not using DTO’s here. I cant see any use of them since I think I can pass around Business objects from one layer to another. Is there any con to it given the nature of methods mentioned above.


Thank you very much!


A beginner book for design patterns?

I'm studying the Object Oriented Design & Analysis course, our teacher told us to have a brief look on design patterns. So here I am asking a quick reference for good books on design pattern. Suggestion will be appreciated.