I'm reviewing the concept of Smart vs. Dumb Components, and overall I think it's a good design principal. But the aspect of styling begs some obvious questions for me - The principal recommends smart components don't provide any styling, but if this is strictly adhered to, where only dumb components provide styling, wouldn't the app look disjoint/ununiform? Does the guideline have any say on global stylesheets?
dimanche 30 avril 2017
Constructing object
I have a query in constructing an object and storing it in database in json format.
Its in air domain industry. Need to construct an ojbect and store it in database in json format so the other applications can use the same object for various test automation scripts.
What i have done is i have created a class called PassengerDetails and inserted to station, from station etc., as below.
class PassengerDetails{
private String toStation;// Origin
private String fromStation;// destination
private String noOfAdults;
and getters and setters.
}
The passenger type also changes, like infants, companions etc., and i am not understanding how to handle it in class PassengerDetails. I have a guess like i have to add another class for PassengerType. Please correct me if i am wrong and suggest me how to add that passengertype details.
And I have created one ticket class (one ticket for each passenger, if 3 adults are there then 3 tickets and and three tickets are associated with one unique PNR). Here we have to store how the ticket is purchased, i mean by cash or credit card
class PaymentDetails{
private String creditCardType;
private String creditCardNo;
private String creditCardHolderName;
private String cash;
getters and setters.
}
We are having different payment types like Creditcard, cash, vouchers, refund amount etc., I am in confusion again how to handle this in the above PaymentDetails Class and how to link this class with TicketInformation and PassengerDetails
class TicketInformation{
private List<PassengerDetails> passengerDetails;
Getters and setters...
}
For multiple tickets, we have one PNR.
class PNRDetails{
List<TicketInformation> ticketInformationList = new ArrayList();
getters and setters.
}
Now i have a query like, if there is modification in flights or dates etc., new ticket will be issued. Now the question is how to store this new tickets and old tickets so that the user who retrieves the list of tickets can understand that there is a modification and hence there are new tickets and old tickets.
The other scenario is that if there is an addition of additonal passenger then not only the ticket changes but also the PNR changes, Now the question is i want to store both new and old PNRs and associated tickets.
For multiple PNR's how to write the class, do i have to write a class where it has List as instance variable. I messed up the code and i am in confusion. Could any one suggest better approach in modifications of code.
Moving behavior of following gameobjects in Unity
I’m trying to clone this arrow game from ketchapp which I don’t intend to publish, I’m only doing it for learning purposes so don’t hate me for that. Anyway I’m using Unity and I’ve programmed the controller which is attached to the head, and the tail parts have the script which tries to follow the head. But the tail parts are not following in a desired behavior like they do in the actual game. I’ve tried spherical interpolation (slerp) and smooth damp (vector2.smoothdamp) for the follow like positioning of tail parts, but it’s making a curvy pattern (which it should because it’s slerp and smooth damp) when the head moves left or right which is not what I want. In the actual game the tail parts move exactly in a way or in a pattern the head moves. I’ve thought of storing the transform of head, and then making the rest of the tail parts follow through them but that doesn’t seem like an efficient approach at all. So how should it be approached? I’m attaching images from the actual game and my work so far.
How to create a singleton using enum while also passing state of the singleton
I have created a singleton using double locking check and now I want to create a singleton using enum. I know I can create singleton something like below:
public enum MyEnumSingleton{
MY_ENUM_SINGLETON(2, "Hello");
private int id;
private String name;
MyEnumSingleton(int _id, String _name){
this.id = _id;
this.name = _name;
}
}
But I want the "id" and "name" information to be passed passed dynamically and not hardcoded in enum, much like the way I can do new MySingleton(2, "s")
with any class.
I have how to hardcode the value and create enum singleton but not able to get how to pass information dynamically.
Java Singleton pattern creating NullPointException [duplicate]
This question already has an answer here:
I am writing a program to hold information from several Excel spreadsheets. I have a basic UI, a facade class that's a singleton, a personnel class to store objects from the spreadsheets, and a class for each spreadsheet to read the data that also follow the singleton pattern. I thought I had written the singleton pattern properly, but when I try to add a personnel object to a list stored in the facade class I get a NullPointException. I've tried using the enum method for singletons, but I have the same problem.
This is the GUI class:
public class TestGUI
{
// Instance variables
private static Base base;
// Main method
public static void main(String[] args)
{
// Initialise Base facade class
base = Base.getInstance();
}
}
This is the facade class, Base:
public class Base
{
// Instance variables
private static Base baseInstance;
private ArrayList<Personnel> personnelList;
DateTest dateTest;
private PersonnelDatabase personnelDatabase;
// Constructor
private Base()
{
personnelList = new ArrayList<>();
dateTest = new DateTest();
personnelDatabase = PersonnelDatabase.getInstance();
}
// Methods
public static Base getInstance()
{
if (baseInstance == null)
{
baseInstance = new Base();
}
return baseInstance;
}
public ArrayList<Personnel> getPersonnel()
{
return personnelList;
}
void addPersonnelToList(Personnel aPersonnel)
{
personnelList.add(aPersonnel);
}
public boolean addPersonnel(String aServiceNumber, String aFirstName,
String aSurname, Rank aRank, String aDateOfBirth)
{
if (!dateTest.dateTester(aDateOfBirth))
return false;
return (personnelList.add(new Personnel(aServiceNumber, aFirstName,
aSurname, aRank, aDateOfBirth)));
}
}
This is one of the classes for reading a spreadsheet:
public class PersonnelDatabase
{
// Instance variables
private static PersonnelDatabase pBInstance;
private Base base;
private FileInputStream file;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private Cell cell;
private String serviceNumber;
private String firstName;
private String surName;
private Rank rank;
private String dateOfBirth;
// Constructor
private PersonnelDatabase()
{
try
{
file = new FileInputStream(new File
("./Personnel Database.xlsx"));
workbook = new XSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
cell = null;
}
catch (Exception e)
{
e.printStackTrace();
}
// Create personnel objects from personnel database
retrieveAllPersonnel();
closeFile();
}
// Private methods
void closeFile()
{
try
{
file.close();
FileOutputStream outFile = new FileOutputStream(new File
("./Personnel Database.xlsx"));
workbook.write(outFile);
outFile.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private Rank convertRank(String aRank)
{
String rank;
rank = aRank.substring(5);
rank = rank.trim();
rank = rank.toUpperCase();
return Rank.valueOf(rank);
}
private void retrieveAllPersonnel()
{
boolean result;
int row = 1;
// Iterate through rows containing NATO personnel number
//while(sheet.getRow(row).getCell(1).
getStringCellValue().substring(0, 3).equals("NII"))
for (int i = 1; i < 17; i++)
{
serviceNumber = sheet.getRow(row).
getCell(4).getStringCellValue();
firstName = sheet.getRow(row).
getCell(6).getStringCellValue();
surName = sheet.getRow(row).
getCell(7).getStringCellValue();
rank = convertRank(sheet.getRow(row).
getCell(5).getStringCellValue());
dateOfBirth = sheet.getRow(row).
getCell(10).getStringCellValue();
// Create personnel and add to base personnel list
Personnel person = new Personnel(serviceNumber, firstName,
surName, rank, dateOfBirth, row);
System.out.println(person.getNameAndRank() + "\n");
base.addPersonnelToList(person);
//result = base.addPersonnel(serviceNumber, firstName, surName,
rank, dateOfBirth);
row++;
}
}
public static PersonnelDatabase getInstance()
{
if (pBInstance == null)
{
pBInstance = new PersonnelDatabase();
}
return pBInstance;
}
}
I am fairly new to programming, so it's probably something obvious, but I have spent hours looking for the cause.
What kind of object I should pass from DAL to BLL if I need to create custom type?
I have read many topics on stackoverflow but I still don't know what kind of object I should pass from DAL to BLL if I need to create custom type.
In DAL I have an entity:
public class Note
{
[Key]
public int NoteId { get; set; }
[Required]
[Column(TypeName = "varchar(MAX)")]
public string Content { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
But I need to return to BLL only: NoteId, Content and number of comments which aren't spam so in DAL I have a query:
public IEnumerable<WhatIsIt> GetNotesWithNoSpamCommentsCount()
{
var whatIsIt = context.Notes.Select(x =>
new WhatIsIt
{
NoteId = x.NoteId,
NoteSummary = x.Content,
NoteCommentsCount = x.Comments.Where(y => y.IsSpam == false).Count()
}).ToList();
return whatIsIt;
}
What kind of object is it which I return - is it Data Access Object or Model or Data Transfer Object or Business Object or something else?
best practices for dealing with a large number of images in a web app
So the user clicks an image and it opens in a new page with description etc. Im only dealing with 12 images so its not a big deal, but what if I had 500 or 1000+ images? Thats a alot of extra pages to deal with. This is part of my final exam and Im curious about best practice solutions for a large number of images under these specific circumstances. And this is being done with asp.net if that makes any difference.
The application should still function like the midterm that if one clicks on the small image clip a new page should be opened with a larger image displayed along with a full description. Please remember to include coffee information such as calories, and nutritional facts. Let’s have a limit of at least 4 pastries, 4 teas, and 4 coffees.
samedi 29 avril 2017
Factory CreateInstance arguments not neessary for a specific subtype
I have a factory class and one create instance method
CreateInstance(EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita, IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider)
the factory can instantiate two differents sub-types depending on the value of tipoParametroEntita.TipoCampo.IdTipoCampo
The point is the second argument of CreateInstance
(parametroEntitaMultiValoreDataSourceProvider
) is used only for creating instance of TipoEntitaTipoParametroEntitaMultiValore
whereas is not used in creating instance of TipoEntitaTipoParametroEntitaSingoloValore
public class TipoEntitaTipoParametroEntitaFactory : ITipoEntitaTipoParametroEntitaFactory
{
/// <summary>
/// Creates an instance of TipoEntitaTipoParametroEntitaSingoloValore or TipoEntitaTipoParametroEntitaMultiValore
/// </summary>
public TipoEntitaTipoParametroEntita CreateInstance(EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita, IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider)
{
if (tipoParametroEntita.TipoCampo.IdTipoCampo == (int)EntityModel.Enum.TipoCampo.CampoLibero ||
tipoParametroEntita.TipoCampo.IdTipoCampo == (int)EntityModel.Enum.TipoCampo.CampoLiberoMultiLinea)
{
return new TipoEntitaTipoParametroEntitaSingoloValore(tipoParametroEntita);
}
if (tipoParametroEntita.TipoCampo.IdTipoCampo ==
(int)EntityModel.Enum.TipoCampo.DropdownListQueryDataSource ||
tipoParametroEntita.TipoCampo.IdTipoCampo ==
(int)EntityModel.Enum.TipoCampo.DropdownListTableDataSource)
{
return new TipoEntitaTipoParametroEntitaMultiValore(tipoParametroEntita,
parametroEntitaMultiValoreDataSourceProvider);
}
return null;
}
}
Im doubtful about this adopted pattern as I always need to pass an instance of IParametroEntitaMultiValoreDataSourceProvider
even if it could not be necessary and moreover someone reading the signature of the method might be led to think that for creating any type of TipoEntitaTipoParametroEntita
an instance of IParametroEntitaMultiValoreDataSourceProvider
is required.
What could be a better approach? Two distinct factories? Only one factory and two CreateInstance (one returning TipoEntitaTipoParametroEntitaSingoloValore
and the other TipoEntitaTipoParametroEntitaMultiValore
)?
I both of the cases I should already know which factory or which CreateInstance to call so I should check tipoParametroEntita.TipoCampo.IdTipoCampo
every time in advance. But I'd like to keep this logic only in one place.
Reduce db accesses in mongodb
I'm playing around with my first full stack experience and I would like to start with the right foot.
Let's say I'm using MongoDb with a collection called Item, and I know that its properties are updated rarely.
Item {
"_id":ObjectId
// ...
}
Say I have a client application (a mobile device) that is able to persist data fetched from the server.
I want the user to always have the latest updated items every time he/she refreshes the UI (e.g. opens the app), but I don't want to overload the server database with requests given the fact the Items fetched would probably be already present in the local storage.
My question is whether it is wise to use a "version" property that checks if the Item on the mobile device is the same as the one of the server. Something like
V {
"_id_of_the_Item": "version_of_the_Item"
}
that allows me to check if client_version < server_version
.
This also implies the client should be sending the server a list of (ids+versions
) or let the server keep track of each user's latest fetch.
- Thinking about this solution I realized that given N Items I would have also N
V-documents
. Am I then introducing an overhead instead of reducing the number of request to the database, making them (N+M) where M is the number of Items that were updated and actually need to be fetched? - Is there any consolidated pattern for this?
Node Singleton Use
The author of this article uses singletons for the service layer in this example Node api:
He states, "We only want there to ever be one instance of our player service, so instead of exporting the class itself, we’ll export a new instance of it. Module files in node are only ever executed once, so this effectively gives us a singleton."
'use strict';
var uuid = require('node-uuid');
class PlayersService {
constructor() {
this.players = [];
}
getPlayers() {
return this.players;
}
getSinglePlayer(playerId) {
var player = this.players.filter(p => p.id === playerId)[0];
return player || null;
}
addPlayer(info) {
// prevent a bit of bad/duplicate data
if (!info || this.players.filter(p => (p.firstName === info.firstName && p.lastName === info.lastName)).length > 0) {
return false;
}
info.id = uuid.v4();
this.players.push(info);
return true;
}
updatePlayer(playerId, info) {
var player = this.getSinglePlayer(playerId);
if (player) {
player.firstName = info.firstName ? info.firstName : player.firstName;
player.lastName = info.lastName ? info.lastName : player.lastName;
player.displayName = info.displayName ? info.displayName : player.displayName;
return true;
}
return false;
}
}
module.exports = new PlayersService();
Which seems reasonable since the function of these services is to provide the same implementation for the controllers that use them.
However, in this post:
On Design Patterns: When to use the Singleton?
the poster asks for a legitimate use case for singletons other than a Logger class. Several people responded to his question by saying that singletons should never be used.
But isn't the use of singletons for services like the one I've copied here a legitimate use case and a best practice so that you are not creating multiple instances that provide the same implementation? Thanks.
Using ParentDecorator class for Child classes
Lets say I have four classes:
abstract class Parent {/*do stuff*/ }
class ChildA extends Parent {/*do more stuff*/}
class ChildB extends Parent {/*do more stuff differently*/}
class ParentDecorator extends Parent {
// do stuff
doSomething() {
//doing something
}
}
How can i use ParentDecorator method doSomething() with ChildA and ChildB objects? The obvious answer would be something like:
Parent child = new ParentDecorator(child);
((ParentDecorator) child).doSomething();
but my case, all my objects are in a lists like:
ArrayList<Parent> objects;
and i have methods like findObject(info)
which returns an object from the list.
Now, lets say i want to call doStuff from the decorator for a specific object from that list. I can do something like:
Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
((ParentDecorator) child1).doSomething();
but with this, only child1 will be able to use ParentDecorator functionality, and findObject(info) will return an unchanged object. I tried this:
( (ParentDecorator) findObject(info)).doSomething();
but it throws an error "ChildA cannot be cast to ParentDecorator"
Do i need to creat ChildADecorator and ChildBDecorator, which seems a bit redundant? Or is there some workaround i cant seem to figure out?
UML and Code Relationship
I understand that the main goal of UML is to communicate. UML intends to provide a design of a system and Code really is the actual building block of the system.
My question is if code an uml are suppose to directly mirror each other. Let me explain: ~I am working on a java program that uses a web service to display movie show times. ~So far I have managed to make simple gui with AWT and Swing that displays show times. ~The program has 16 classes and a friend of mine extended my code on a git however he added the following to all the classes.
package ShowTimesFrUSA;
I wanted to present my program with designs of UML with a package Diagram. However I already divided my classes into different packages differently from the way it is coded.Packages:UI (AWT and Swing) , Controllers, Moviemonitor, MovieService, USAmovies <>
I just want to show the dependancies between the class groups in my code as part of the requirements for this presentation and the package diagram is really good for that. But I am unsure if the packages in the model should directly mirror the way packages are coded in java?
what is the proper way to create an application
I want a simple advice to create an application .I have my idea but I do not know which part of the app I am supposed to start first (Design or code ) I would like your advice in that direction .. it will be easy to finish the app (make it working properly ) with simple design and after work properly on the UI design
or it will be better to make the design and then code accordingly
I would like to get advice and suggestion fact in some situation of code , design and all
thank you
Design to store query in object form
We are building an application where we need to store Query in object form like:
class Query{
public Select s{get;set;}
public From f{get;set;}
}
class select {
public List< Column > columns {get;set;}
}
class Column{
public string ColumnName {get;set;}
public string AliasName {get;set;}
}
class From {
public Table mainTable{get;set;}
public List<JoinTable>{get;set;}
}
class Table {
public string tableName{get;set;}
public string Alias{get;set;}
}
class JoinTable:Table{
public string OnExpression{get;set;}
}
we are storing details in these objects so later on we can create queries for any database using these objects.It can be even more complex with subquery also. Please let me know if there is any better design to do so.
Note: We are using C# to develop this application.
vendredi 28 avril 2017
Controllers in vendor folders - my controllers - what is the right approach?
So I use a package from github ticketit(http://ift.tt/2peZ7aQ) and this package has controllers included.
And I integrated it into fresh laravel application.
now, I want to add an API endpoints into my application, my question is
should I copy the controllers from the ticketit package in the vendor directory and create my app/http/controllers folder or should I access the controllers in the vendor ? or are there any good design out there I should do?
so what i'm planning to do is
Route::get('api/v1/getdata','TicketsController@data');
Route::get('/getdata','TicketsController@data');
Please help on the design,
If I try to edit the controllers inside the vendor folders and upload it in server for sure it will not be upload.
btw, I'm using Laravel 5.4 and Laravel passport.
"That" tag not working AIML
i'm trying to make a bot with AIML, and on the code bellow, only de last item is recognized with an YES answer. Why did this happens?
<category>
<pattern> * </pattern>
<template><random>
<li>Hi i am aviator wanna talk about boeing airplanes</li>
<li>Hello how are you what about discuss boeing airplanes</li>
<li>Well hello wanna talk about boeing airplanes</li>
<li>Hi there what abou talk of some boeing airplanes</li>
<li>Hey there could we talk about boeing airplanes</li>
<li>What about talk of airplanes</li>
</random></template>
<category>
<pattern>YES</pattern>
<that>Hi i am aviator wanna talk about boeing airplanes</that>
<that>Hello how are you what about discuss boeing airplanes</that>
<that>Well hello wanna talk about boeing airplanes</that>
<that>Well hello wanna talk about boeing airplanes</that>
<that>Hey there could we talk about boeing airplanes</that>
<that>What about talk of airplanes</that>
<template>OK then, <set name = "topic">747</set> it will be!</template>
Thanks in advance.
MergeSort loop where comparison is done in real-time with user input. Don't know design pattern to make this work
So I want to implement a merge sort on an array of items that will be compared in pairs in real-time by the end user. There is a MergeSortMgr object with a delegate to the viewControl who will present the comparisons. All works fine if I simply return from the view control's delegate method. However, I am having crazy trouble figuring out the pattern to only return from the delegate method after I have presented the user with the two items and a selection has been made. I have tried while loops (causes my UI to blank out), callbacks (couldn't figure out a pattern than would let me delay the sync delegateMethod return. Anyway...I got a really cool feature that needs this. Help please.
Here is the MergeSortMgr object:
protocol MergeSortMgrDelegate {
func presentMatch(item1: Int, item2: Int) -> Bool
}
class MergeSortMgr: NSObject {
var delegate: MergeSortMgrDelegate?
override init() {
}
func merge(leftArray leftArray: [Int], rightArray: [Int]) -> [Int] {
// Index of items to compare
var leftIndex = 0
var rightIndex = 0
print("Merging \(leftArray) and \(rightArray)")
// Array containing the sorted items
var sortedArray = [Int]()
// Compare the elements and add them to the sorted array *in order*
while leftIndex < leftArray.count && rightIndex < rightArray.count {
var comparison = delegate?.presentMatch(item1: leftArray[leftIndex], item2: rightArray[rightIndex])
print(comparison)
if comparison! { //leftArray[leftIndex] < rightArray[rightIndex]
sortedArray.append(leftArray[leftIndex])
print("Moving left item into array: \(leftArray[leftIndex])")
leftIndex += 1
} else if !comparison! { //leftArray[leftIndex] > rightArray[rightIndex]
sortedArray.append(rightArray[rightIndex])
print("Moving right item into array: \(rightArray[rightIndex])")
rightIndex += 1
} else {
print("Numbers were identical: \(leftArray[leftIndex]) == \(rightArray[rightIndex])")
sortedArray.append(leftArray[leftIndex])
leftIndex += 1
sortedArray.append(rightArray[rightIndex])
rightIndex += 1
}
}
// At this point, the elements were compared and sorted properly,
// so we just need to append the rest of the items to the array
while leftIndex < leftArray.count {
sortedArray.append(leftArray[leftIndex])
print("Moving left item into array: \(leftArray[leftIndex])")
leftIndex += 1
}
while rightIndex < rightArray.count {
sortedArray.append(rightArray[rightIndex])
print("Moving right item into array: \(rightArray[rightIndex])")
rightIndex += 1
}
return sortedArray
}
func mergeSort(array: [Int]) -> [Int] {
// If our array only has one item, we're done
guard array.count > 1 else { return array }
// Find the middle of the array
let middleIndex = array.count / 2
// Recursively sort the left and right parts of the array
let leftArray = mergeSort(array: Array(array[0..<middleIndex]))
let rightArray = mergeSort(array: Array(array[middleIndex..<array.count]))
return merge(leftArray: leftArray, rightArray: rightArray)
}
}
Here is the ViewController which implements the MergeSortMgr delegate method, should display to the user the comparison, then return the selection back via the delegate. (This last part is my problem.)
class ViewController: UIViewController, MergeSortMgrDelegate {
var mergeSortMgr = MergeSortMgr()
var array: [Int] = []
var selection: Int?
@IBOutlet weak var button_item1: UIButton!
@IBOutlet weak var button_item2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
mergeSortMgr.delegate = self
//test array actual array will be not comparable objects
array = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]
array = mergeSortMgr.mergeSort(array: array)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func presentMatch(item1: Int, item2: Int) -> Bool {
selection = nil
button_item1.setTitle(String(item1), for: .normal)
button_item1.tag = item1
button_item2.setTitle(String(item2), for: .normal)
button_item2.tag = item2
//async callback pattern doesn't seem to work
getResult() {
if selection == item1 {
return false
} else {
return true
}
return false
}
//While loop blanks out my screen
var result = false
while selection == nil {
if selection == item1 {
result = false
} else {
result = true
}
}
return result
}
func getResult(completion: (Void) -> Bool) {
completion()
}
@IBAction func onItem1(_ sender: UIButton) {
self.selection = sender.tag
}
@IBAction func onItem2(_ sender: UIButton) {
self.selection = sender.tag
}
}
Is there a better way of not repeating code than Template Method Design Pattern?
There are Employees to model, and the problem to solve is to calculate the salary. There are diferent types of employees, all of them share discount for Social Work:
The Generic Employee:
public class Employee{
float salary;
public Empleado(float salary) {
this.salary = salary;
}
public float salary() {
return this.minusSocialWork(this.salary);
}
private float descuentoObraSocial(float sueldo) {
return (float) (salary * 0.87);
}
}
And there are subtypes:
- Employee with family and basic salary (has a Bono Plus if has childrens + basic salary)
- Plant Employee (for each children (son, daughter) $150 + basic salary)
- Trainee Employee (salary is hours * price by hour)
- Temporary employee (salary is hours * price by hour + Bono Plus + basic salary)
Question:
Using Template Method Design Pattern, I find a lot of duplicate code, so my question is: is there a better close up when there are so many subtypes or kinds of Employees and combinations?
Preferable Pattern for getting around the "moving out of borrowed self" checker
Just to demo my problem, consider this pattern where there are several states registered with a dispatcher, and each state knows what state to transtion next to when it receives an appropriate event. Just a simple state transition pattern.
struct Dispatcher {
states: HashMap<Uid, Rc<RefCell<State>>>,
}
impl Dispatcher {
pub fn insert_state(&mut self, state_id: Uid, state: Rc<RefCell<State>>) -> Option<Rc<RefCell<State>>> {
self.states.insert(state_id, state)
}
fn dispatch(&mut self, state_id: Uid, event: Event) {
if let Some(mut state) = states.get_mut(&state_id).cloned() {
state.handle_event(self, event);
}
}
}
trait State {
fn handle_event(&mut self, &mut Dispatcher, Event);
}
struct S0 {
state_id: Uid,
move_only_field: Option<MOF>,
// This is pattern that concerns me.
}
impl State for S0 {
fn handle_event(&mut self, dispatcher: &mut Dispatcher, event: Event) {
if event == Event::SomeEvent {
// Do some work
if let Some(mof) = self.mof.take() {
let next_state = Rc::new(RefCell::new(S0 {
state_id: self.state_id,
move_only_field: mof,
}));
let _ = dispatcher.insert(self.state_id, next_state);
} else {
// log an error: BUGGY Logic somewhere
let _ = dispatcher.remove_state(&self.state_id);
}
} else {
// Do some other work, maybe transition to State S2 etc.
}
}
}
struct S1 {
state_id: Uid,
move_only_field: MOF,
}
impl State for S1 {
fn handle_event(&mut self, dispatcher: &mut Dispatcher, event: Event) {
// Do some work, maybe transition to State S2/S3/S4 etc.
}
}
As marked in the code via inline comment, S0::move_only_field
needs to be an Option
in this pattern. However I am not sure this is best way to approach it. Here are the ways I can think of with demerits of each one:
With reference to the inline comment above saying:
// This is pattern that concerns me.
I cannot move it out without putting it into an Option
, in handle_event
as self is borrowed. So my choices are:
- Put it into and Option like here: Feels hacky and everytime i need to check the invariant that the option is always
Some
otherwisepanic!
or make it a NOP withif let Some() =
pattern and ignore the else clause, but this causes code-bloat. Both, doing and unwrap or bloating the code withif let Some()
feels a bit off. - Get it into a shared ownership
Rc<RefCell<>>
: Need to heap allocate all such variables or construct another struct calledInner
or something that has all these non-clonable types and put that into anRc<RefCell<>>
. - Pass stuff back to
Dispatcher
indicating it to basically remove us from the map and then move things out of us to the next State which will also be indicated via our return value: Too much coupling, breaks OOP, does not scale as Dispatcher needs to know about all the States and needs frequent updating. I don't think this is a good paradigm, but could be wrong. - Implemnt
Default
for MOF above: Now we can mem::replace it with default while moving out the old value. The burden of panic'ing OR returning an error OR doing a NOP is now hidden in implementation ofMOF
. The problem here is we don't always have the access to MOF type and for those that we do, it again takes the point of bloat from user code to the code of MOF. - Let the function
handle_event
takeself
by move asfn handle_event(mut self, ...) -> Option<Self>
: Now instead ofRc<RefCell<>>
you will need to haveBox<State>
and move it out each time in the dispatcher and if the return isSome
you put it back. This almost feels like a sledgehammer and makes many other idioms impossible, for instance if I wanted to share self further in some registered closure/callback I would normally put aWeak<RefCell<>>
previously but now sharing self in callbacks etc is impossible.
Are there any other options ? Is there any that is considered the "most idiomatic" way of doing this in Rust ?
How to wrap a Collection object of a subclass?
I'm building an array where each element in the array is a LinkedList of Strings. I MUST use the following implementation:
Build a class that wraps a LinkedList object (and also extends a given class), and have every element in the array be an instance of this class. I'm given the following class which I need to extend (which I can't change, and I MUST use):
public Class1{
java.util.Collection<java.lang.String> collection;
Class1(java.util.Collection<java.lang.String> collection){
this.collection = collection; }
public void add(String str) {
collection.add(str); }
and Class1 has a couple more methods related to Collection (delete, etc.). I want to create a class that extends Class1, and wraps a LinkedList object. I want this class to meet two requirements:
- use Class1 implementation for the collection methods (add, delete, etc.)
- to have other methods of its own, for example the following getFirst() method.
So here's what I did:
public class Bucket extends Class1 {
LinkedList<String> linkedList;
Bucket(){
super(new LinkedList<String>()); }
public String getFirst(){
linkedList.getFirst(); } }
I have a main class that tries to run the following code
Bucket bucket = new Bucket();
bucket.add("5");
bucket.getFirst();
This falls in the bucket.getFirst() line, because obviously the linkedList in the Bucket class is null, it isn't the LinkedList object I've sent to Class1, so the getFirst() method in Bucket is trying to operate on null.
How can I solve this? How can I connect the LinkedList I send to Class1 to the LinkedList I have in the Bucket class? Thank you for reading so far.
Public interface, internal functionality
I have an interface which is currently public. This is passed to the client as a representation of a type (same application but I cannot modify calling code beyond changes types).
A -> B.GetIntrerface();
A -> B.SendInterface(A.InterfaceIGot);
Is essentially what I'm saying here.
With that in mind, if I want to have internal functionality (so that the caller cannot see it), and I do not want to pass a concrete class to the caller, is there a design pattern that supports this?
Can I do:
A.otherInterface = A.instanceOfB.GetInterface();
instanceOfB.SendInterface(A.otherInterface);
Where otherInterface is public.
And internally in SendInterface
?
A.DoSomethingInternal();
I know I could downcast, but it seems messy. Is there an established design pattern for this?
Thanks!
Applying the Decorator Pattern to Java String Class
I want to add functionality to the java.lang.String
class. I thought of using the decorator pattern as follows:
public class StringDecorator {
String str;
public StringDecorator(String str)
{
this.str = str;
}
// Wrap all methods in String class such as:
public int length()
{
return str.length();
}
// Add other methods from String class here.. And then add new functions..
public void newFunction1()
{
}
}
However, I read on SO here: http://ift.tt/2oEKoqR that this is not appropriate because String is final and cannot be extended. The user also suggests that "a different design pattern is in order".
Can someone please confirm if indeed it is not appropriate to use the decorator pattern in this scenario and if so what other design pattern can be used instead?
What's a good way to pass the params to service method? An entire object or just some of its params?
guys, I am new to Java EE, and I'm now designing the service layer. I am very confused about what param should I pass to the method from my controller layer, the entire object? or just its essential params?
For example, if I want to create an article, here is the code.
The first way
public void createArticle(Article article) {
articleDAO.create(article);
}
The second way
public void createArticle(String title, String subtitle) {
Article article = new Article();
article.setTitle(title);
article.setSubtitle1(subtitle);
articleDAO.create(article);
}
so please help me, which way should I follow? I am so confused, thanks!
How to use application's own API within the application itself?
I have to develop a functionality to store and retrieve some data in Laravel. We have to create a API and a desktop widget for the operation.
What our client wants is we need to use the API itself for the dashboard widget. So I need to use the API calls for the operation. I can not override the API functionality to maintain standards.
But, There are some other operations I want to perform at the time of saving and retrieving. I basically need a wrapper around the API functions.
I can use either AJAX to call API but then I have to make another call for wrapper operations. Or I can call API controller within my controller. But it is not a good structural approach so I do not want to use it.
So please suggest me a design structure to do the same. How should I use my own API within my own application?
jeudi 27 avril 2017
best way to define calculations in a database
I am designing a database where I can keep device readings from multiple devices in multiple locations. Each location can have more than one device, in which case the results may have to be combined. These calculations vary, so it is not always the same formula. I implemented a table for locations, one for devices, linked to location ID, and one for periodic measurement results, linked to device ID. For the calculated result, I was thinking to implement a table calculations, to define the calculated results for two devices, and to save the result in the same table as for the devices. Is this a good approach, or are there better ways to do this?
How to update the property value in Revealing Prototype Pattern
This is my code example. I have a dog that with printAge()
function that log the age
property. age
has also gave as public property.
let Dog = function(){
};
Dog.prototype = function(){
let age = 3;
let printAge = function(){
console.log(age);
};
return{
age : age,
printAge : printAge
}
}();
Then I assign age
from dog's instance and call printAge()
to log but the value of age
3 is not updated with new value.
let DogInstance = new Dog();
DogInstance.age = 7;
DogInstace.printAge();
The result log is 3
But if I declare another function to assign the age
instead of assinging age
directly, it works.
Dog.prototype = function(){
let age = 3;
let setAge = function(val){
age = val;
}
let getAge = function() {
return age;
}
let printAge = function(){
console.log(age);
};
return{
setAge : setAge,
printAge : printAge
}
}();
let DogInstance = new Dog();
DogInstance.setAge(7);
DogInstace.printAge();
The result is: 7
Is that mean, we can't assign a property even if it was public in Revealing Prototype Pattern?
Can we write @Component or any other annotations on DTO classes
I am working with Spring Restful and Hibernate. To remove the redundancy in code I want to avoid the object creation of DTO in each and every methods and want to declare it with @Component annotation, I want to know is there any specific rules for DTOs as we have some guidelines for POJO and JavaBeans.
Prevent Cracking Singleton using reflection
I came across the below example where a singleton class can be instantiated using reflections. The code is like below
public class SingletonExploitationExample {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
MySingleTon.getInstance();
Constructor<MySingleTon> constructor = MySingleTon.class.getDeclaredConstructor();
constructor.setAccessible(true);
MySingleTon obj1 = constructor.newInstance();
MySingleTon obj2 = constructor.newInstance();
MySingleTon obj3 = constructor.newInstance();
obj1.printN();
}
}
final class MySingleTon {
private static MySingleTon instance = null;
private static int count = 0;
private MySingleTon(){
count++;
}
public void printN(){
System.out.println(count);
}
public static MySingleTon getInstance(){
if(instance == null){
synchronized (MySingleTon.class){
if(instance == null){
instance = new MySingleTon();
}
}
}
return instance;
}
}
Is there any way this can be avoided or a singleton be made to have only one instance(with reflection also user should not be able to instantiate a new object) ?
Java default interface methods concrete use cases
Java 9 is near to come and more features will be added to Java interfaces, like private methods. default
methods in interfaces were added in Java 8, essentially to support the use of lambdas inside collections without breaking retro-compatibility with previous versions of the language.
In Scala, methods inside trait
s are quite useful. However, Scala has a different approach treating trait
s than Java with default
methods. Think to multiple inheritance resolution or the use of trait
s as mixins.
Apart the above use, which are the real scenarios in which using a default
methods is worth? During this years is it arisen some pattern that uses them? Which problems can I solve using this kind of methods?
Creating element inside IEnumerable instead of adding existing element to it
It is good to use such approach to add new item to custom collection? Not to add existing element, but create new element inside the collection? The method name "Add" is suitable for this case? (The purpose is hiding repositories.) Thanks.
public class MyObject
{
public int ID { get; }
public Value1 { get; }
public Value2 { get; }
}
public interface ICustomCollection : IEnumerable<MyObject>
{
MyObject Add(value1, value2);
}
public class CustomCollection : ICustomCollection
{
MyObjectFactory factory;
MyObjectRepository repository;
public IEnumerator<MyObject> GetEnumerator()
{
return repository.GetAllObjects();
}
public MyObject Add(value1, value2)
{
var newItem = factory.Create(value1, value2);
repository.AddObject(newItem);
return newItem;
}
//...
}
Modelling class hierarchy
I'm currently modeling a class hierarchy so wanted to check if anyone has any better way of doing this. The problem is as follows:
I have a menu item that has id and icons inside it. Then I can have also menu item that has other sub-menu items (but not icons at the same time). It is basically container for the sub-menu items, but has also id as the real menu item. Current model is something like this:
class SubMenuItemTypeId{}
class MenuItemTypeId{}
class MenuIconId{}
class MenuIcon{}
interface MenuItemWithoutSubItems{
MenuItemTypeId getTypeId();
List<MenuIcon> getIcons();
}
interface MenuItemWithSubItems{
MenuItemTypeId getTypeId();
Map<SubMenuItemTypeId, SubMenuItem> getTypeKeyToSubMenuItem();
}
interface SubMenuItem{
SubMenuItemTypeId getTypeId();
List<MenuIcon> getIcons();
}
interface Publishable{
void suspend();
void publish();
}
interface ControllableMenuItemWithoutSubItems extends MenuItemWithoutSubItems, Publishable{
void control(MenuIconId iconId, String iconData);
}
interface ControllableMenuItemWithSubItems extends MenuItemWithSubItems, Publishable{
void control(SubMenuItemTypeId typeid, MenuIconId iconId, String iconData);
}
The problem - it seems like I can make it more generic. Only thing that came to my mind was this variation:
enum EnumSubMenuItemTypeId implements SubMenuItemTypeId{
ONLY_IF_MENU_ITEM_WITHOUT_SUB_ITEMS(0);
private int id;
EnumSubMenuItemTypeId(int id){
this.id = id;
}
@Override
public Integer getId() {
return id;
}
}
class RealSubMenuItemTypeId implements SubMenuItemTypeId{
private int id;
@Override
public Integer getId() {
return id;
}
}
interface SubMenuItemTypeId{
Integer getId();
}
class MenuItemTypeId{}
class MenuIconId{}
class MenuIcon{}
interface MenuItem{
MenuItemTypeId getTypeId();
Map<SubMenuItemTypeId, SubMenuItem> getTypeKeyToSubMenuItem();
}
interface SubMenuItem{
SubMenuItemTypeId getTypeId();
List<MenuIcon> getIcons();
}
interface Publishable{
void suspend();
void publish();
}
interface ControllableMenuItem extends MenuItem, Publishable{
void control(SubMenuItemTypeId typeid, MenuIconId iconId, String iconData);
}
But problem with this is that if I want MenuItemWithoutSubItems
I have to make MenuItem
and as SubMenuItemTypeId
in Map
I have to use EnumSubMenuItemTypeId.ONLY_IF_MENU_ITEM_WITHOUT_SUB_ITEMS
-> which is a workaround in my case. Classes are simpler, but it still seems more complex than needs to.
Any other options that I could have?
Folder Structure on each layer in visual studio solution
I have visual studio solution including an ASP.NET MVC and WCF hosting projects. Also, have Service.cs, Engine.cs, Repository.cs classe(s) behind ServiceName.svc boundary.
My question is about organization of folders thus file names on each layer. For instance, i have a Settings page where user updates his full name, address and phone number. I have two options to follow:
1- AccountController.cs (/settings action) -> AccountService.svc -> AccountService.cs (UpdateFullName() operation) -> AccountEngine.cs (updateFullName() method) -> AccountRepository.cs -> SQL Server
or
2- SettingsController.cs (/home action) -> SettingsService.svc(UpdateFullName() operation) -> SettingsService.cs -> SettingsEngine.cs (updateFullName() method) -> AccountRepository.cs -> SQL Server
Would be glad to receive your insights and recommendations, i know about organization by functional cohesion and about DDD but still did not get to the point where i have a pattern clear in my mind to follow and consider it as best practice and apply it to all projects.
PHP - Design pattern for dynamic "validators"
I struggling with following problem:
- User send message via form
- Request is passed to controller
(In controller) - App checks if user is logged
- App checks if user has permission to send messages
- App prepares (filter/validate) data send from app
- Controller pass data to
Service
layer
(In service) - Service inserts data to database
- Service returns result to controller
(In controller) - App creates
View Model
and send result to user's browser
Problem
Users have status (it's kind of role but more detailed) and I have to check if user's status allows to specific actions.
For example:
I have "status-checkers":
- MessageChecker - class to check if user with provided status may send message
- LimitChecker - class to check if user with provided status didn't exceeded message limit
- SomethingElseChecker
I'm looking for a way (design pattern) to easily add/remove checker without modifying controller or service.
Let's say I have configuration array with these active checkers:
checker.config.php
return [
'Namespace\Checker\MessageChecker',
'Namespace\Checker\LimitChecker',
'Namespace\Checker\FooChecker'
];
What next? Should I pass it to controller and check it on this level? Or to service and check it on this layer? What design pattern will be suitable for my problem?
mercredi 26 avril 2017
java design pattern for for decoupling task completion and execution of next
I implemented a wrapper for a queue that holds incoming tasks. Every time a task is executed, a callback is called to the wrapper's owning class for the the actual execution (doSomething()).
This implementation doesn't look good, because as long as there are still items in the queue, the callbacks will start chaining together and grow the stack. Is there a common design pattern to decouple the completion of the previous task and execution of the next task?
public void executeCallback(Task task) {
switch(task.type()) {
case TASK_TYPE1:
doSomething();
break;
case TASK_TYPE2:
doSomethingElse();
}
queueWrapper.executeNextTaskInQueue(); //doesn't look too good
}
}
State Pattern for login and payment logic design
First of all thank you all in advance, this community makes the code around the globe so much better!
So, I´m designing a system to manage login routing and payments for customers to use a service.
I´ve decided that for my logic it would be better to use the State Pattern, so that each state knows how to handle the payment transactions gotten from another system, which already exists, to change state (there are some kinds of payment).
Also it would know which main page the customer should land in, as there are some different payment screens options for different kinds of customers.
Here is a snippet of my design, sorry for not putting any code but haven´t touched code yet.
Transaction (base class)
- MonthlyFeeTransaction
- CancelSignatureTransaction
- ...OtherKindsOfTransactions (subclasses)
(properties)
- Client client
- double Amount
- Date transactionDate
- ...otherProperties
(method)
-> registrate():void
(calls appropriate service methods to registrate itself in the DB)
ClientState (base class)
- NewClient
- UpToDateClient
- InadimplentClient
- CancelledClient
- ...OtherKindsOfClients(subclasses)
(methods)
getLoginScreen (): String
receiveTransaction (Transaction transaction)
...someOtherMethods()
The Transactions are what triggers change in the state, and some modifications in the DB will have to be made accordingly, which changes depending on the state flow. Ex: for a CancelledClient to become UpToDate the cancellationDate parameter must be set to null, which is not the case for a NewClient to become UpToDate, and so on.
I´ve thought of some ways to make this work. For example I could overload the receiveTransaction method so that there is one for every Transaction subclass, and put the state transition logic there. This way I would need to write new methods in ClientState subclasses for every new Transaction type, which doesn´t fell very OO.
Or I could have the Transaction object send a message to the receiving State object triggering the change, but then the Transaction object would have to know about ClientState methods, which is not desired from a business point of view.
So what I ask is: how could I loosen the coupling between these two classes, so that whenever I add a new Transaction subclass or a new State subclass I don´t have to make any modifications in the other?
Is there another design better suited for this?
If I can make the question anyhow clearer please tell me.
Thanks again!
Design pattern for requiring children of a base class to call a method from the base class
Let's say I have a base class
public class BaseAuthenticator
{
protected void AuthenticateSuccessfully()
{
// Do stuff
}
}
And I have many types of authenticators all deriving from the base class. I only want one thing from the derived classes : It's that they don't forget to call AuthenticateSuccessfully()
somewhere in their code. All authenticators have their own logic, but in the end they should always call AuthenticateSuccessfully()
somewhere when ready to do so (after validations, etc.).
How can I ensure at compile time that every derived authenticator calls the AuthenticateSuccessfully()
method at least once?
Disable button good practice in IOS?
I currently have a UIButton in my app when clicked, starts running a block of code that takes awhile to finish so I run it on another queue.
I would like to keep the button enable so that if the user clicks the button in 2 quick succession for example, I would ignore the data returned from the first click and just use the data from the second click. My problem is that I'm worried that the user might click the button 20 or 30 times and my app would create 20-30 queues which would slow the execution?
How would I be able to deal with this? I feel like disabling the UIButton after 1 click is not a good solution.
Interpreter design pattern using java
I am doing a DBMS using this interface
package eg.edu.alexu.csd.oop.db;
public interface Database {
/**
* Creates/drops table or database.
* @param query structure definition query (e.g., create or drop table)
* @returns true if success, or false otherwise
* @throws SQLException syntax error
*/
public boolean executeStructureQuery(String query) throws java.sql.SQLException;
/**
* Select from table
* @param query data retrieval query (e.g., select)
* @return the selected records or an empty array if no records match. Columns
types must be preserved, i.e, Columns of “int” data type return
Integer objects, and columns of “varchar” data type return String
objects)
* @throws SQLException syntax error
*/
public Object[][] executeRetrievalQuery(String query) throws java.sql.SQLException;
/**
* Insert or update or delete the data
* @param query data manipulation query (e.g., insert, update or delete)
* @return the updated rows count
* @throws SQLException syntax error
*/
public int executeUpdateQuery(String query) throws java.sql.SQLException;
}
So I created a validator and a tokenizer which returns an area. And I want to use the tokens to use Interpreter design pattern, however, all resources have a very simple code and I am unable to understand how to use it here. Any guidance would or suggestions would be appreciated
PHP callbacks usage
I know what the callbacks are and how works, I'm just thinking about WHEN to use them.
What are you typical situations where you use a callback?
Are there any design patterns or something like this for these situations?
Thank you.
C# Bridge design pattern
I found this question in glassdoor and careercup, this is an OOP design question.
many people claim to have solved it using different design patterns.
I think It can be solved either with bridge pattern or decorator pattern.
I tried to implement it using bridge pattern but found myself stuck.
in the original question the base class is derived by 4 classes: 1. woodChair 2. woodTable 3.metalChair 4.metalTable
I think I understand how to create the bridge here but I'm not sure if it doesn't break the conditions of the question.
Can you please say:
A. which design pattern will you use? or how (don't have to use a design pattern)
B. Is my implementation correct? does it break the conditions set by the interviewer?
Original Question:
You are on a team that is creating a program to model stress on furniture. Your task is to model the behavior of furniture under abuse such as excessive weight or application of fire.
Someone has already created a prototype with a base class Furniture, and four derived classes WoodChair,SteelChair, WoodTable, and SteelTable.
We will need to start adding other furniture like couches, beds, bookcases, and desks, and also new materials such as plastic, cloth, rubber, etc. Try to improve the class design - you are free to modify it however you wish since it is only a prototype.
applyWeight(double x, double y, double weight, double seconds)
;
the furniture becomes unusable if enough weight is applied; the algorithm depends on shape of furniture, and the location where the weight is applied applyFire(double x, double y, double fireStrength, double seconds)
;
the furniture becomes unusable if it is made of wood, and fire is applied long enough; wood will change from brown to black if it is burnt (whether or not the furniture becomes unusable)
Color getColor(); // possible values: Gray, Brown, Black, etc
FurnitureState getState();
// possible values: OK, UNUSABLE
[TestClass]
public class UnitTest1
{
[TestMethod]
public void SuperFurnitureTest()
{
SuperFurniture furniture = new SuperFurniture();
//test for wood Chair
furniture.CurrentFurniture = new WoodFurniture(20, 10);
furniture.CurrentFurniture.applyFire(0, 1, 2, 21);
Assert.AreEqual(Color.Black, furniture.CurrentFurniture.getColor());
furniture.CurrentFurniture.applyWeight(0, 1, 2, 21);
Assert.AreEqual(FurnitureState.OK, furniture.CurrentFurniture.getState());
}
}
public class Furniture
{
protected FurnitureState _state;
protected Color _color;
public double _size;
public double _weightThreshold;
public Furniture(double size)
{
_state = FurnitureState.OK;
}
public virtual void applyFire(double x, double y, double fireStrength, double seconds)
{
}
public virtual void applyWeight(double x, double y, double weight, double seconds)
{
if (x * y > _size)
{
if (weight > _weightThreshold)
{
_state = FurnitureState.UNUSABLE;
}
}
}
public Color getColor()
{
return _color;
}
public FurnitureState getState()
{
return _state;
}
}
public class WoodFurniture :Furniture
{
public double _fireThresh;
public WoodFurniture(double fireThresh, double size) :base(size)
{
_fireThresh = fireThresh;
}
public override void applyFire(double x, double y, double fireStrength, double seconds)
{
if (seconds > _fireThresh)
{
_color = Color.Black;
}
}
}
public class SuperFurniture
{
Furniture currentFurniture = null;
public Furniture CurrentFurniture
{
get { return currentFurniture;}
set { currentFurniture = value; }
}
public void applyWeight(double x, double y, double weight, double seconds)
{
currentFurniture.applyWeight(x, y, weight, seconds);
}
void applyFire(double x, double y, double fireStrength, double seconds)
{
currentFurniture.applyFire(x, y, fireStrength, seconds);
}
}
Getters naming convention
I understand the traditional naming convention for getter methods:
getName();
getAddress();
getAge();
But i dont understand why. I would rather just use the property name as the method as in the following example:
class Person
{
private $name;
private $address;
private $age;
public function __construct($name, $address, $age)
{
$this->name = name;
$this->address = address;
$this->age = age;
}
public function name()
{
return $this->name;
}
public function address()
{
return $this->address;
}
public function age()
{
return $this->age;
}
}
This makes code more fluent to me
i.e. $person->address()
But i get pulled up on code reviews when doing this for not using proper naming conventions.
Is there anything fundamentally wrong with not using get/set prefixes ?
pattern matching in postgresql
I need to substring "test" from my variable "5.myname (test)" in postgresql I am able to extract number[i.e 5] and text [i.e myname] from above string but unable to extract test. can anyone please suggest pattern to extract test from above string.
What to use for microservices inter-communications .NET
Doing some research on splitting our monolith into micro-services and trying to understand/determine the best way for communications between services, or if I should even be communicating between services?
Should each micro-service be a web service that only serves Http or should I be using a service bus to pass work requests around?
How to avoid using singleton in a proper way?
I want to refactor my code to apply clean approach.
I have a class user
class User {
let name: String?
let id: String
var isOnline: Bool
var mesaageHistory = [Message]()
init(name: String, id: String, isOnlineStatus: Bool) {
self.name = name
self.id = id
self.isOnline = isOnlineStatus
}
}
Then I'm using fabric pattern to create list of my users.
protocol CreateUserProtocol: class {
func sortArray(inputArr: [User])
}
class CreateUserEntity: CreateUserProtocol {
static let shared = CreateUserEntity()
var users = [User]()
func sortArray(inputArr: [User]){
var applySortingByDate: Bool = false
for user in inputArr {
if !user.mesaageHistory.isEmpty {
applySortingByDate = true
}
}
if applySortingByDate {
inputArr.sorted(by: { (first, second) -> Bool in
(first.mesaageHistory.last?.messageTime)! < (second.mesaageHistory.last?.messageTime)!
})
} else {
inputArr.sorted(by: { (first, second) -> Bool in
first.name! < second.name!
})
}
}
}
One controller is responsible for appending new users, while another is used to retrieve them and bind them to tableView. Everything is working fine, but I think my solution is not good enough for scaling.
Moreover in one of my VC I use to sort my Users to online and offline. I think, that I shouldn't do that in my VC and to put this logic into my CreateUserEntity
var onlineUsersData = [User]()
var offlineUsersData = [User]()
private func classifyUsers() {
for user in CreateUserEntity.shared.users {
print("is user online: \(user.isOnline)")
print(CreateUserEntity.shared.users.count)
if user.isOnline == true && !onlineUsersData.contains(user) {
onlineUsersData.append(user)
}
if user.isOnline == false && !offlineUsersData.contains(user) {
offlineUsersData.append(user)
}
}
}
I'd like to rewrite it in proper way, what can you recommend me?
Command Pattern example confusion
I am going through the Head-First Design Pattern book when I came across the "Command Pattern" chapter. I have recreated the example in Playground:
protocol RemoteActions {
func turnOn()
}
protocol Product {
var description: String { get set }
}
struct Light: Product {
var description: String
// some other properties
}
struct Heater: Product {
var description: String
// some other properties
}
class LightOn: RemoteActions {
var light: Light
init(light: Light) {
self.light = light
}
func turnOn() {
print("\(light.description) on")
}
}
class HeaterOn: RemoteActions {
var heater: Heater
init(heater: Heater) {
self.heater = heater
}
func turnOn() {
print("\(heater.description) on")
}
}
class Remote {
func doAction(action: RemoteActions) {
action.turnOn()
}
}
let r = Remote()
let l = Light(description: "light1")
let h = Heater(description: "heater1")
let lo = LightOn(light: l)
let ho = HeaterOn(heater: h)
r.doAction(action: lo)
r.doAction(action: ho)
I mean what are the benefits of this pattern?? Yes, I can see that the remote will only know about its actions, but what if I wanted to create a new Product to be turned on and off? I will undoubtfully have to create a new "Command Class" right? Which makes this part in the book really silly:
Wouldn't it be better if we conformed the action into said Product? Like this:
protocol RemoteActions {
func turnOn()
}
protocol Product: RemoteActions {
var description: String { get set }
func turnOn()
}
struct Light: Product {
var description: String
// some other properties
func turnOn() {
print("\(description) on")
}
}
struct Heater: Product {
var description: String
// some other properties
func turnOn() {
print("\(description) on")
}
}
class Remote {
func doAction(product: Product) {
product.turnOn()
}
}
let r = Remote()
let l = Light(description: "light1")
let h = Heater(description: "heater1")
r.doAction(product: l)
r.doAction(product: h)
Can someone summarize all of these terms? Hook, Callback, Event, etc
Can anyone explain what these terms mean, their differences, and how they're related to each other? (ex. is it true that the term 'hook' supersets 'callback'?)
- Hook
- Callback
- Observer
- Listener
- Event
- Event handler
- Event queue
- Dispatcher
- Event driven architecture
- Publish and subscribe
- Template method
- Framework
- Implicit invocation
mardi 25 avril 2017
How to add attributes and methods to an instance of a class
I am writing a class that needs to behave as if it were an instance of another class, but have additional methods and attributes. I've tried doing different things within __new__
but to no avail. As an example, here is a half-written class and the desired behavior:
class A(object):
def __new__(self, a, b):
value = 100 + a # instances of A need to behave like integers
... # bind A methods and attributes to value?
return value
def __init__(self, a, b)
self.b = b
def something(self):
return 20 + self.b
Here is the desired behavior:
a = A(10, 5)
print(a + 10) # 110
print(a * 2) # 200
print(a.b) # 5
print(a.something()) # 25
I know that when __new__
returns an instance of a class different than A
, then __init__
and other methods are not bound to value
. None of the other methods are either. Is this sort of thing possible? Am I thinking about this problem the wrong way?
What is the opposite of domain driven design?
I'm looking for a term that describes a design pattern (or anti-pattern) that describes when a system is organized by generalizations rather than the terms of the business.
For example consider the domain driven example of:
Customer.Load
Account.Load
Orders.Load
vs:
Load.LoadCustomers
Load.LoadAccounts
Load.LoadOrders
Another example could be seen here in mvc: ASP.NET MVC - putting controller & associated views in the same folder?
While more about organization vs design, the comment from pettys IMO is correct:
Realize that there are two dimensions of the system at odds here, the architectural and the business. The original poster wants to keep all parts that deal with a certain business concern in one place. The default ASP.NET MVC layout spreads a single business concern out quite a bit so that architecturally-similar classes can stay together. Between these two choices I'd rather have things grouped by business concern than by architectural concern
There is only one way to physically organize the project. The OP is asking to organize by domain and pettys describes the default organization as "architecturally" organized. But it is this "architectural" organization that I'm better trying to classify.
It seems to me that this is aspect-oriented design, ie design favoring a classification with respect to a general process instead of specific terms of the business. I do not intend to confuse this with aspect-oriented programming which can be complementary to DDD, but it IS confusing which is why I'm wondering if there is a better name.
Is it better to add variables to capture state or create a new file for that specific state?
I have a piece of code that runs pretty much the same except in certain situations/contexts it has some minor modifications when it's called in that situation/context.
Is it better to capture the states of the context in state variables? Pros: less code/more reusability Cons: will make the code less readable and more complex as more state modifications are added.
OR
Is it better to create a new file for that specific context?
pros: easy readability because no state variables, one file per state .
cons: less dry.
How to materialize extended properties in EF6 using raw sql?
I have used EFExtension.dll with EF5 like this:
ents.CreateStoreCommand(sql).Materialize<MYTYPE>()
now I am migrating to EF6. As I understood the EFExtension is expecting the ents
to be System.Data.Objects.ObjectContext
, while in EF6 its System.Data.Entity.Core.Objects.ObjectContext
hence I cant use it.
I tried to replace it with the "stock" EF method like this:
ents.ExecuteStoreQuery<MYTYPE>(sql)
but it skips several fields which declared not in the model but in the partial class extension. they are not part of the DB table - they normally are results of joins to another tables and belong architecturally to the "object" part of the entity but not the "storage" part.
Anyone can help to solve this ?
3-Layer without repositories, with entity framework?
I've decided to ditch repositories, instead I will use them directly in my services. However, I am now not sure where my EF DbContext should sit and where SaveChanges() should be called from. Here is my current design:
- MVC Client
- View Models
- Core BLL
- Domain Models
- Managers
- Services - Used to talk to third-parties and DAL
- Data DAL
- Entity Models
- DbContext
Should services sit in BLL, or should that be in the DAL?
Also any improvements you could suggest on the above are welcome, thank you!
Composite pattern and workflow
Is the composite pattern to implement appropriate workflow?
In general,the patterns are suitable for implementation workflow?
Analyzing date and time patterns
I want to understand when (time and day) people are making certain inquiries. Are their patterns in the day of the week, time of the day and/or both? I've got a list of date and times in the following format:
2016-12-05T14:18:51-0800
Can anyone make a suggestion on a good method (or library, package, etc) for this kind of simple analysis? Currently the data lives in a Python dictionary but i'm flexible and this can be sent anywhere.
Design wise, how should I append new elements using JQuery?
I have been using JQuery for some time now, and I wonder what is the best way to display new elements?
Attempt #1
Load external html snippet, and insert it using append
Attempt #2
Change display from none and have all available html preloaded on the page
Attempt #3
Store it in a string and append the element to the designated id.
I feel as though all of these are not great design practice, but which is the best? If there is some other way that I have missed please inform me
How to create an object with callable methods, but which I can also call like a function
I use d3.js a lot and have been thinking recently about their linearScale function.
It allows you to do this:
var x = d3.scaleLinear()
.domain([10, 130])
.range([0, 960]);
x(20); // 80
x(50); // 320
As far as I can tell:
- x holds the return value of d3.scaleLinear()
- x is object-like, because we can then call the methods 'range' and 'domain'
- x is also function-like, because we can call it like 'x(20)' and get a return value
I do not need to know anything specific about how d3 implements this, d3 is simply the first example that came to mind of an API that allows me to do this.
I am interested in implementing something similar myself in javascript and would like to know the necessary design pattern in its simplest form.
I have tried looking at the source code for d3, but there is a lot of extra functionality, and it's split over multiple files - which makes it hard for me to find what I'm looking for, especially when I don't know what that is. Any help would be much appreciated.
Which is better for creating json request body: method with lots of arguments or builder pattern?
In my tests I send requests with such a body:
{
"param": "value",
"param": "value",
"param": "value",
"param": "value",
"param": {
"param": value,
"param": "value"
},
"param": "value"
}
For each test I use different combination of values (params are always the same). So my question is which is better to use: a method with a bunch of arguments like
public JSONObject createRequestBody(param1, param2, param3, param4, param5, param6, param7) {...}
or a builder pattern? Or maybe there is another solution. Thanks!
NLayer Boilerplate Critique?
I've put together a boilerplate solution to try and nail down the best way to approach the 'n layer' design pattern. I've given it a shot, but I don't believe my approach to the repository layer has gone to plan, with this implementation the results are filtered in memory and I don't believe that's ideal.
Could I please get some critique on the approach I have taken and the implementation?
lundi 24 avril 2017
Are there generic master slave alogrithms / apis avaialble for microcontrollers
In programming robots several micro-controllers and processors work in coordination. To my mind master slave communication comes to mind. Are there generic algorithms and api's available for such communication? I am a novice in programming micro-controllers and working primarily with arduino and I concepts around Serial/SPI/I2C interfaces, however I am looking for algorithms / patterns for programming.
Are Comments and Posts the same
I'm currently in the process of building another generic Blog style website, and I got to thinking. Where I usually use a separate table for Posts
and another for Comments
and then join them using FK's. I began to wonder, are they really worthy of separate tables?
For example properties they both share include:
- ID (int)
- Title (string)
- Body (text)
- Poster (FK)
- Created At (Datetime)
- Updated At (DateTime)
- Likes/Dislikes(ints)
- Etc..
One Post
Has(optional) Many Comments
,Many Comments
have one Post
, but also One Comment
, may also have many Comments
.
Now would it make more sense. For a table to contain both, Comments and Posts, and self reference them from within? Having a separate lookup table for containing what each type of entity is.
Then however, if a Post is a Comment, and a comment is no different to a post. Except for in a view context, should posted Images also be contained within the same table? As these to, can have likes/comments/name etc.
Question in short: Do blog Posts and Comments belong in the same table?
Java repaint() not updating images, poor design
I am having some problems with the repaint() method in my code, while everything runs normally (no exceptions) there is no change to the panel I am drawing to.
I know that the design of the classes/methods is not great and is probably contributing to the problem but I don't know how to clean it up without breaking my program.
You can see my code + some screenshot of the output here:
The Draw class is responsible for paint and repainting the game board
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel{
Observer observer = new Observer();
ArrayList<BufferedImage> Pieces = new ArrayList<BufferedImage>();
int movedToX;
int movedToY;
BufferedImage pieceIcon;
String square;
String piece;
public JPanel makeABoard(){
JPanel board = null;
try {
final BufferedImage gboard = ImageIO.read(new File("cutsomGameBoard.jpg"));
//load white game pieces
Pieces.add(ImageIO.read(new File("rect-lightOrange.png")));
Pieces.add(ImageIO.read(new File("rect-navy.png")));
Pieces.add(ImageIO.read(new File("rect-maroon.png")));
Pieces.add(ImageIO.read(new File("rect-lilac.png")));
Pieces.add(ImageIO.read(new File("rect-yellow.png")));
Pieces.add(ImageIO.read(new File("rect-orange.png")));
Pieces.add(ImageIO.read(new File("rect-green.png")));
Pieces.add(ImageIO.read(new File("rect-brown.png")));
//load black game pieces
Pieces.add(ImageIO.read(new File("rev-brown.png")));
Pieces.add(ImageIO.read(new File("rev-green.png")));
Pieces.add(ImageIO.read(new File("rev-orange.png")));
Pieces.add(ImageIO.read(new File("rev-yellow.png")));
Pieces.add(ImageIO.read(new File("rev-lilac.png")));
Pieces.add(ImageIO.read(new File("rev-maroon.png")));
Pieces.add(ImageIO.read(new File("rev-navy.png")));
Pieces.add(ImageIO.read(new File("rev-lighOrange.png")));
//You can get the Piece class from the observer which you can then use to store that Piece's icon
int i = 0;
for(Piece p : observer.getCurrentState().getPieces().getPieces()){
p.setIcon(Pieces.get(i));
i++;
}
//draws the initial board
board = new JPanel(){
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(gboard, 0, 0, this);
starterPieces(g);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(480, 480);
}
};
}
catch (IOException e) {
e.printStackTrace();
}
return board;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(pieceIcon, movedToX, movedToY, this);
}
public void starterPieces(Graphics g){
int x = 5;
int y = 5;
for(int i = 0; i <8; i++){
g.drawImage(Pieces.get(i), x, y, this);
x += 60;
}
x = 5;
y = 425;
for(int i = 8; i <16; i++){
g.drawImage(Pieces.get(i), x, y, this);
x += 60;
}
}
//Here is where my main problem lies: this method translates the users input (a string) to something which the GUI can use to repaint the board
public void updateBoard(String pieceInput, String squareInput){
Graphics g = this.getGraphics();
//each square object know its own id (e.g. C4) which you can use to search a certain square as well as knowing its location in the form of a Point2D object
Square sq = observer.getCurrentState().getBoard().getStringSquare(squareInput);
movedToX = (int) sq.getSquareLocation().getX();
movedToY = (int) sq.getSquareLocation().getY();
pieceIcon = observer.getCurrentState().getPiece(pieceInput).getIcon();
repaint();
}
public void clearOldPieces(){
// to be added
}
}
The GUI class is the main user interface which calls the Draw method once the user reaches the game screen
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class GUI extends Frame implements ActionListener {
private static final long serialVersionUID = 1L;
Observer observer = new Observer();
String piece;
String square;
JFrame screen;
JLabel updates;
public GUI(){
welcome();
}
//One method per screen
public void welcome(){
observer.createState();
final JTextField accountName = new JTextField(20);
updates = new JLabel();
updates.setText("Watch this space for feedback through out your game!");
updates.setForeground(Color.WHITE);
screen = new JFrame("Welcome");
JPanel welcome = new JPanel();
JPanel footer = new JPanel();
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
playerOneName = accountName.getText();
CurrentState cs = observer.getCurrentState();
cs.createPlayer();
observer.getCurrentState().getPlayer(1).setName(playerOneName);
welcome.setVisible(false);
updates.setText("Player one created!");
observer.getCurrentState().getPlayer(1).activatePlayer();
//choose(playerOneName); --> usually there is a few more screens here before the board but for now we can directly go to it
drawBoard();
}
});
JLabel message = new JLabel();
message.setText("Welcome to Kamisado, please enter your name");
message.setForeground(Color.WHITE);
welcome.add(message);
welcome.add(accountName);
welcome.add(start);
welcome.setVisible(true);
welcome.setBackground(Color.darkGray);
footer.add(updates);
footer.setVisible(true);
footer.setBackground(Color.darkGray);
screen.add(welcome);
screen.add(footer, BorderLayout.PAGE_END);
screen.setVisible(true);
screen.pack();
//screen.getContentPane().setBackground(Color.darkGray);
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void drawBoard(){
JPanel gameScreen = new JPanel();
JButton loadGame = new JButton("Load Game");
JButton settings = new JButton("Settings");
JButton reset = new JButton("Reset");
JButton undo = new JButton("Undo");
JButton save = new JButton("Save");
JButton quit = new JButton("Quit");
Draw boardImg = new Draw();
JPanel keyInput = new JPanel();
JLabel message = new JLabel();
message.setText("Enter the piece to move and the square to move to, comma seperated: ");
message.setForeground(Color.white);
JTextField pieceSquare = new JTextField(10);
JButton move = new JButton("Move");
move.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
piece = pieceSquare.getText().substring(0,2).toUpperCase();
square = pieceSquare.getText().substring(3,5).toUpperCase();
System.out.println("Piece from text field " + piece);
System.out.println("Square from text field " + square);
if(!gameMode.startsWith("A")){
if(movePiece()){
updates.setText("Success!");
boardImg.updateBoard(piece,square);
}
}
else{
if(moveAIPiece()){
updates.setText("Success!");
boardImg.updateBoard(piece,square);
}
}
}
});
keyInput.add(message);
keyInput.add(pieceSquare);
keyInput.add(move);
keyInput.setBackground(Color.darkGray);
keyInput.setVisible(true);
gameScreen.add(boardImg.makeABoard(), BorderLayout.LINE_END);
gameScreen.add(keyInput, BorderLayout.LINE_END);
gameScreen.setVisible(true);
gameScreen.setBackground(Color.DARK_GRAY);
gameScreen.setMinimumSize(new Dimension(520,520));
screen.add(gameScreen);
}
public boolean movePiece(){
if(gameMode.equals("H")){
if(gameInterface.play(piece, square, playerColour)){
return true;
}
}
else if(gameMode.equals("T")){
if(gameInterface.playTimed(piece, square, playerColour, timeLength){
return true;
}
}
return false;
}
public boolean moveAIPiece(){
if(gameMode.equals("A")){
if(gameInterface.play(piece, square, playerColour)){
if(aiDiff.equals("E")){
gameInterface.playAI(piece, square, playerColour);
return true;
}
else{
gameInterface.playHardAI(piece, square, playerColour);
return true;
}
}
}
else{
if(gameInterface.playTimed(piece, square, playerColour, timeLength){
if(aiDiff.equals("E")){
gameInterface.playAI(piece, square, playerColour);
switchPlayer();
return true;
}
else{
gameInterface.playHardAI(piece, square, playerColour);
return true;
}
}
}
return false;
}
}
Output:
Pattern recognition from input data stream, Frame Sync c++
I am new to programming and need some help on frame sync in c++.
I have an input data stream of 1's and 0's. If the specific pattern (01010101010101) in this incoming data stream is recognized, then pass the whole frame of 360 elements to include the 1st element of pattern to next 359 elements.
oops design feature vs other programming models
I am going through the concepts of OOPS and I am wondering what is the unique design feature that makes Object Oriented Programming different than other programming models ?
- It uses mathematical logic for computer programming.
- It describes the desired outcome of a program without explicitly listing the steps that need to be carried out.
- It specifies the steps the program must take to reach the desired state.
- It is broken down into discrete units capable of receiving messages, processing data, and sending messages onto other units.
I am stuck on this question.
Updating options on dynamic selector with Vuejs2
I have a problem updating the options
array in a select
tag in a VueJS component.
I have several rows and on select
on each row. Each select
will use the same options
array. When one option is selected, that option should disappear from the others select
.
I have try several ways to do that, but i'm not able to update the other options array (Using the Vue.set(...)
function and all the caveats available).
The question in similar to this one but: - selector's array has to be dynamic - Options are the same for each selector
That's why the solution on that question doesn't work for me.
Design of a Wrapper Class in C++
I have to work with an old class with a very clumsy interface. Since I cannot change it and am reliant to it, I want to build a wrapper, offering a clean interface. Let's say I have a class ClumsyClass. Basically, I have three approaches:
1. Reference Member
Class Wrapper {
public:
Wrapper (ClumsyClass& clumsyClass)
: m_clumsyClass(clumsyClass)
{ }
int getSmth() {
return m_clumsyClass.getSmth();
}
private:
ClumsyClass& m_clumsyClass;
}
2. Pointer Member
Class Wrapper {
public:
Wrapper (ClumsyClass* clumsyClass)
: m_clumsyClass(clumsyClass)
{ }
int getSmth() {
return m_clumsyClass->getSmth();
}
private:
ClumsyClass* m_clumsyClass;
}
3. Inheritance
Class Wrapper : public ClumsyClass {
...
}
Which approach is the "cleanest" way to implement a wrapper? I prefer the third one, but when I already have a ClumsyClass object and then create a Wrapper object (copy constructor), more memory will be needed (since an instance of the original class is necessary in my case).
Implement overload with differents return types
I need to overload a method with two differents return types, and in java is not possible, so does it make sense if i have a super class with "Object" return type an then i override this method in two different classes?
class A{
Object method()
{
...
}
}
class B extends A{
@override
Integer method()
{
...
}
}
class C extends A{
@override
Double method()
{
...
}
}
or is there a better way to do this? or simply other solutions?
dimanche 23 avril 2017
Design Pattern for Movie ticket booking system
I am working on movie ticket booking system. The system has to deal with multiple screens with different size and different showtime list. The ticket is basically dependent on cinemas, showtime and date, taxes. Admin will control it regularly. I am little bit of confused that which design pattern will good for this system, specially for the screens, showtime and seating allotment section. Please advice.
How to avoid spaghetti code when using nested promises?
Say you have 6 methods that return promises, A(), B(), C(), D(), E(), F() and G().
Several of them cannot execute properly until others have. For instance, C() requires A(). F() & E() require C(). B() requires A() and F(). G() requires all others to be complete.
A().then(() => {
C().then(() => {
F().then(() => {
B();
});
E();
});
}).then(() => {
G();
});
D();
Now, say that some logic needs to be run between several of these functions that affect their behavior.
A().then(() => {
let foop = this._service.getFoop();
C(foop).then((noop) => {
noop.forEach((n) => { n *= -1; });
F(noop).then((boop) => {
boop = boop.flatten();
B(foop, boop);
});
E('MonkeyWrench');
});
}).then(() => {
let glipglop = this._service.findGlip(this.LOCAL_GLOP_KEY);
G(glipglop, 42);
});
D();
And then, on top of that, we need to make sure that each of these promises catches and handles errors.
A().then(() => {
let foop = this._service.getFoop();
C(foop).then((noop) => {
noop.forEach((n) => { n *= -1; });
F(noop).then((boop) => {
boop = boop.flatten();
B(foop, boop).catch((e) => {
this.handleErrorB(e);
});;
}).catch((e) => {
this.handleErrorF(e);
});
E('MonkeyWrench').catch((e) => {
this.handleErrorE(e);
});
}).catch((e) => {
this.handleErrorC(e);
});
}).then(() => {
let glipglop = _service.findGlip(this.LOCAL_GLOP_KEY);
G(glipglop, 42);
}).catch((e) => {
this.handleErrorA(e);
});
D().catch((e) => {
this.handleErrorD(e);
});
So now we have a complete async program made up of promises - and it looks like a complete mess.
What is a way to take a program like this and make it easier to read so that future contributors can avoid diving into spaghetti code? Are nested promise structures inherently messy, or are there accepted protocols to clean this up and make it more readable?
I read http://ift.tt/1HoXyIN and it had some good ideas such as using promise.all([...]) to run multiple promises at once, but it didn't include any support for having logic between nested promise calls.
Thanks in advance to anyone willing to impart some wisdom for me on this.
Design pattern to address invitation race condition
Before I begin describing the problem I'm facing, let me assure you that I've checked if there already is another thread where this has been talked about. After about 5-6 tries clicking on suggestions, I gave up, since it's hard to get an idea from threads with generic names like "What design pattern can I use?"
So I've given this question as descriptive a title as I could come up with. The reason for my concern about this being asked already is that it feels like it should be a fairly common problem (surely others would've encountered this in their client-server program).
=====
So here's my problem...
I've got a single server S, and several clients C1, C2, ..., Cn. A client can do 1 of three things at any given time:
- Create an event.
- Invite other clients to created events.
- Accept or reject invitations to events created by other clients.
A client sees names for events they've created (and possibly invited other clients to) as well as names for events they've accepted invitations to. The server processes all invitations; when a client invites another client to an event, the invitation goes through S but S knows nothing about an event E other than the name associated with it, the inviting client, and the invited client. Let's symbolise the name of an event E as |E|.
Now for two events Ea and Eb, |Ea| != |Eb| does not imply Ea != Eb. That is, just because two events have different names does not mean they are different. I won't formally define what makes two events the same here, but as a use-case, let's say two events are the same if they have the same location/time. However the server never knows this info remember, only the clients do, but the clients may not communicate well enough beforehand with each other and so may choose different names to represent the same event.
My problem: I want to avoid a situation where a client Ca accepts an invitation from a client Cb to an event Eb, and Cb accepts an invitation from Ca to Ea, where Ea = Eb. This would lead to each client seeing both |Ea| and |Eb|, which actually represent the same event.
Question: How do I avoid the above? Is there a design pattern that can work on the server alone, client alone, or both server and client together? The solution can include dialogs/prompts for clients.