As I read and understood, Façade pattern provide different high-level views of subsystems whose details are hidden from users. This lead me to think, Sql Views are a some kind of Facade. Sql Views help hiding some data(vertical and horizontal partitioning) in the tables. Am I correct in thinking Sql Views are facade? Note Facade pattern, as I read is from OO world, and Sql is relational.
dimanche 31 janvier 2016
Does all Object Oriented design come down to reducing conditionals?
I'm getting the sense that reputable OO design and patterns come down to reducing conditional statements (if
statements). This would be very general statement, and wondering if it's true. If it's not true, can you provide an example.
To be clear - My question is purely academic. It is not concerned with the realities and practicalities of crafting software. For example, the question is ignoring tradeoffs like understandability vs complexity.
Creating a text-based map for a text based RPG
Currently, I am creating a text based RPG. I am wondering how I could go about creating a somewhat interactive map, defining specific tiles to hold certain world information like enemy AI and loot or places like towns and dungeons, how to create text based maps for those places, and how to track player movement throughout the world.
I want the world to be borderless, so that player's could hypothetically play the game forever. If I were to create a few classes defining a town, how could I pull a random town object to a certain tile in the world environment for the player to interact with?
How would I go about structuring my player classes, enemy and character AI classes, and room classes?
Lastly, how could I go about creating a text-based visual map for the player to use?
Thanks for any help
Applying State Pattern
I'm trying to apply State pattern on certain program. But can't find out what to do with this one..
Short Description :
There's security system that works like :
To get to the "treasure" you have to pull the lever inside a room, but the door leading to the room has to be closed. Then a Control System is opened.
You can insert a key and get to the treasure, but before you do that, you have to place lever to the original position otherwise you get trapped...
The code of Class I should apply State pattern to :
public class ControlSystem {
private State state1, state2;
private boolean st1, st2;
public ControlSystem() {
state1 = new Door(true);
state2 = new Lever(false);
st1 = true;
st2 = false;
}
public void open() {
state1 = new Door(true);
state1.handle();
st1 = true;
}
public void close() {
state1 = new Door(false);
state1.handle();
st1 = false;
}
public void pull() {
state2 = new Lever(true);
state2.handle();
st2 = true;
}
public void push() {
state2 = new Lever(false);
state2.handle();
st2 = false;
}
public void info() {
if (!st1 && st2) {
System.out.println("Control System is opened");
if (!st2) {
System.out.println("You can take the treasure");
} else {
System.out.println("Oww... You get trapped");
}
}
}
}
The handle()
method just prints the actual state of certain thing.
I know that the condition in method info()
is nonsense, but I let it be that way so I could get help from you guys how to edit it....
How to implement Template Method in Servlet
I'd like to create two HttpServlets with some variation of template method (GOF). So I created abstract class extended from HttpServlet:
abstract public class AbstractServlet extends HttpServlet {
abstract void doSomeAction();
@Override
protected void service(HttpServletRequest rq, HttpServletResponse rs){
try {
//here some logging, getting headers etc.
System.out.println("Nothing really matters");
//invoke concrete class
doSomeAction();
//write response
rs.getOutputStream().write(new String("Simple response from class " + this.getClass().getCanonicalName()).getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
And two concrete class:
public class A extends AbstractServlet {
@Override
void doSomeAction() {
System.out.println("I'm doing something in A");
}
}
public class B extends AbstractServlet {
@Override
void doSomeAction() {
System.out.println("I'm doing something in B");
}
}
After invoke (successfully) one of those services, I can't get any response. After some debugging, it'seems like Tomcat has some problem with NIO channels and latch:
2016-01-31 19:13:52 Http11NioProtocol [DEBUG] Socket: [org.apache.tomcat.util.net.NioEndpoint$KeyAttachment@6bc6f271:org.apache.tomcat.util.net.NioChannel@2072289:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:57585]], Status in: [OPEN_READ], State out: [CLOSED]
2016-01-31 19:13:52 LimitLatch [DEBUG] Counting down[http-nio-8080-exec-2] latch=1
But to be honest, I don't know what's going on. The funny part is, when servlet consume all servletrequest input stream by for example IOUtils.toByteArray(InputStream is), everything works fine!
abstract public class AbstractServlet extends HttpServlet {
abstract void doSomeAction();
@Override
protected void service(HttpServletRequest rq, HttpServletResponse rs){
try {
//here some logging, getting headers etc.
//Consume all inputStream
org.apache.commons.io.IOUtils.toByteArray(rq.getInputStream());
//invoke concrete class
doSomeAction();
//write response
rs.getOutputStream().write(new String("Simple response from class " + this.getClass().getCanonicalName()).getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where is the problem?
Best regards.
samedi 30 janvier 2016
class design in a little java, a little pattern?
I am reading A Little Java, A Few Patterns recently, Chapter 3 introduce Pizza
class and some its subclasses. It looks strange to me that Crust
, Cheese
and Olive
class are defined as subclass of Pizza
Apparently, those are ingredients of a pizza, and the relation between those ingredients and a pizza is has a
not is a
.
So why those ingredients class are defined as subclass of Pizza
?
FYI, code snippet below is the class structure used in this book.
What design patterns can help model objects whose behaviors change dynamically, or objects with many optional behaviors?
Sorry for the long-winded examples, but I've run into this type of software design problem recently, and have been thinking about it. Not sure if there's a term for it, so I'll give 2 general examples to give an idea:
Ex 1: You're working on an RPG game, and you have a class for the main character. That character's reactions to the game world changes based on what you're wearing/holding, skills allotted, basically your object's internal state.
Say you have the following items in the game:
- Ring of regeneration: allows your character to regenerate health over time
- Sneaky sneakers: increases sneak
- Magic mirror: reflects % of incoming damage
- Doofy glasses: highlights crafting resources
Ex 2: You have a Toyota Corolla. There are different configurations of it, but they're all Toyota Corollas. ABS, and Traction Control are optional features (behaviors) you can add to the baseline model.
- The baseline model does nothing extra when running.
- With ABS, the car checks and responds for sudden stops when the car's running
- With Traction Control, the car checks and responds to loss of traction when the car's running
- And obviously, when you have a car with both, you'll do both behaviors when the car's running.
Common properties of the two examples:
- the class of importance has a concrete blank slate that it can start with
- optional items/parts can add an ability or extra behavior to that object; something extra to do per game tick/while running
- may or may not mutate the object when item/behavior is added or taken off of it (increment sneak when putting on sneakers, decrement it when taking it off)
Potential solutions (but not adequate):
if statements:
if ch.isWearing 'doofy glasses':
render with doofy shader
else if ch.isWearing ...
Doesn't work. Need to add a clause for every part. Class can get big and complicated very fast.
Strategy pattern:
class TractionControlStrategy
class ABSstrategy
class Toyota:
TractionControlStrategy tcs
ABSstrategy abs
run():
if tcs not null:
tcs.run()
if abs not null:
abs.run()
carWithTCS = new Toyota(new TractionControlStrategy())
Not much better than the previous solution as you still have the long list of if statements
Strategy with subclasses:
class Toyota:
run():
// does nothing
class ToyotaWithABS : Toyota
ABSstrategy abs = new ABSstrategy()
run():
abs.run
class ToyotaWithTCS : Toyota ...
Satisfies the Open/Closed Principle I think. Better than the previous one maybe? But now you'll have to create a class for every combination of configurations. If you found out later on that there's other optional features, then the number of classes would double for every feature you need to implement...
How can these types of interactions and behaviors be modeled with OOP? What design patterns, or combinations of design patterns promote this kind of thing?
Really not sure if this is a good question or if I'm clear with what I'm asking as I've never really practiced good software design.
I'm learning OpenGL, working on my 3D mesh/model class. This question is related because in my renderer, indexing and textures are optional for a mesh. So a mesh can be vertices only, indexed vertices, vertices and textures, or all 3. Plus, I can't foresee what features I may want to add in the future as I don't know what I'll be learning like a month down the line, so I need the class to be flexible, and extensible
Is view and controller coupled to each other in iOS mvc design pattern?
I have read lot of articles on MVC. I came to one conclusion. M- it's a model object represents business logic. V- it's basically a view. Example any class that represents itself a view or subclass of a view. C- it helps to communicate between model and view.
But I have read multiple answers for mvc in iOS where it says view and controller tied to each other. That's the reason it is usually called viewcontroller? In other article it just says it follows proper mvc which I described it above. Please help me guys which is true. Any kind of help is appreciated.
Reusing attributes - Composition over inheritance
From head first design patters (on decorator pattern):
"That is exactly right. If you have code that relies on the concrete component’s type, decorators will break that code. As long as you only write code against the abstract component type, the use of decorators will remain transparent to your code. However, once you start writing code against concrete components, you’ll want to rethink your application design and your use of decorators."
Well, i came along with this problem, i do want to apply inheritance because i have to reuse metods and attributes, but i still need to work based on class/type. Using composition over inheritance works well for methods, but how can i achive the same thing on attributes? I can't make a composition out of that... or do i?
Is it ok, from a design view, to have a class, lets name it "attributesClass" that only contain attributes i want to reuse, and it implements only getters/setters to acces them wherever i want? (not in a DTO motion). Would it be a good idea to use attributeClassInstance.getXAttr() instead of this.XAttr ?
PD: Thanks for your time and, hopefully, you can get accross with my english :P
Limiting Builder Pattern Parameter
I have simple builder example to illustrate the question "How can I stop a builder parameter from being set twice?"
SimpleVehicle kia = new SimpleVehicle.Builder().setPrice(100).setType("Kia").setPrice(120).build();
System.out.println(kia.toString());
The price has been set to 100 and then again to 120. Is it possible to prevent this? The print returns - SimpleVehicle{price=120, type='Kia'} which is what the builder was asked to do.
The SimpleVehicle class is
public class SimpleVehicle {
private long price;
private String type;
private SimpleVehicle(Builder builder) {
this.price = builder.price;
this.type = builder.type;
}
@Override
public String toString() {
return "SimpleVehicle{" +
"price=" + price +
", type='" + type + '\'' +
'}';
}
public static class Builder {
private long price;
private String type;
public Builder(){
}
public Builder setPrice(long value) {
this.price = value;
return this;
}
public Builder setType(String value) {
this.type = value;
return this;
}
public SimpleVehicle build() {
return new SimpleVehicle(this);
}
}
}
Create a 3x3 Matrix like Android's Lock Screen Pattern View
have you ever put a lock pattern in your android device?
Well i want to make a 9 point 3x3 matrix where i can draw different patterns, its a kinda game app, i will show a figure and the user will use the 3x3 matrix to draw that pattern, like we do when we unlock our phone, so i was wondering how can I do that, there is a library with this or there is a android native class to do this, or how?
I will really help me if you help guys. Thanks.
Implement Neighbors to find the d-neighborhood of a string in Python
Input: A string Pattern and an integer d. Output: The collection of strings Neighbors(Pattern, d).
Sample Input: ACG 1 Sample Output: TCG ACG GCG CCG ACA ACT AGG AAG ATG ACC
What is the algorithm to solve this problem?? Much appreciated of help!
Combine separate entities in one such that they are not tightly coupled
I am initiating a process to create something that process is further divided into 4 step and each step represents a class , i have separated all 4 step by considering Single responsibility principle.each class is composed of set get methods . so far my code is
public class manipulator{
private A a;
private B b;
private C c;
private D d;
public manipulator(){
a= new A();
b= new B();
c= new C();
d= new D();
}
//getters and setters of all 4steps
}
manipulator is main class that contains all 4 steps , each step in constructor is further initiated but i am considering this as tightly coupled system as there are initiating inside constructor . How should i engage interface in it to provide abstraction and to make it loosely coupled.
Any help will be greatly appreciated.
Who and how should use a global service in response to a GUI event
There are many client-side frameworks which encourage the developer to split the GUI into a tree of components. In this question I do not assume any particular framework, or even language, but rather seek for lessons learned from all the diverse frameworks like React, Vue, Ember, Aurelia, or Windows Forms or XAML, that could be useful for someone who'd like to maintain a single page app in Backbone.js.
To make the question concrete, let's think about something like facebook's main page. I have one component (ListOfPostsComponent) which displays a list of posts, where each post is actually displayed by a child component (PostComponent) which in turn might have some component for displaying comments (ListOfCommentsComponent) in which there are multiple instances of CommentComponent, and an instance of AddCommentComponent which lets the user add a comment if she types in text into NewCommentTextComponent and presses the AddCommentButtonComponent.
The goal is to POST a request trough API, on success add the comment to the list of comments, and update the number of comments displayed in the post summary. Realistic enough?
Now, it seems obvious that the click into the button triggers some chain of events starting in AddCommentButtonComponent. What follows is the interesting part. I see several different ways to approach the two problems:
Problem 1. which component should take action of initiating the POST Problem 2. how exactly it should initiate it
Here are several ideas I considered, but I invite you to propose others:
For problem 1:
Option A) (silly) the AddCommentButtonComponent is in charge of adding the comment, so it performs the request. This option requires the button to know the content of the NewCommentTextComponent and that it will inform somehow it's parents about the success of the operation. Seems like too much coupling.
Option B) the AddCommentComponent which knows about both NewCommentTextComponent content and listens to AddCommentButtonComponent 'click' event performs the request. It requires at the minimum a contract which specifies how the text content is being exposed from NewCommentTextComponent, how to listen for events and what is the event name, but it seems to be a right level of coupling, and/or reason for existence of the AddCommentComponent in the first place. We still need to fire some event to inform parents that a new comment is available.
Option C) there is some global events bus/hub, and the communication between components goes by passing one-way events, probably namespaced somehow to avoid collisions. AddCommentButtonComponent sends a 'click' event to a channel/namespace for which the AddCommentComponent listens/subscribes, which in turn emits event 'i-am-about-to-create-a-comment-please-send-me-data', for which NewCommentTextComponent responds with something, etc. Seems like a total mess. Let's call it Erlang style?
Option D) the event is propagated upwards until some authority is sure that noone above it knows what to do with it. In our example the PostComponent decides that it is the last outpost on the border between interested and not interested controls. PostComponent is interested in the event because it wants to update the comments count, and ListOfPostComponents is not interested, so we have to handle it here. This solution seems to asssume a lot of knowledge about the context: PostComponent must know who is the parent and what is it interested in, and so does AddCommentComponent.
Option E) (let's call it the HTML way) the (properly namespaced) event bubbles up to the root accumulating any additional pieces of information as it goes up. For example the AddCommentButtonComponent emits just a simple 'click', but the AddCommentComponent adds a new field with text content to it (and changes name of the event to 'add-comment'), then PostComponent decides to initiate the request but it does not stop event bubling, but might enhance the event with additional name/properties. The problem with this is that it does not answer the question: who should perform the request.
Option F) similar to Option E) but request is issued by some separate service which simply listens to events at the root.
For problem 2:
Option A) (silly) the control simply uses $.ajax.
Option B) (global app) the control uses app.api.addComment(post,text,callbacks)
Option C) (deps injection) the control uses this.api.addComment(post,text,callbacks) where the this.api is initialized in constructor and passed from the parent. The problem with this is that now the parent has to know about all the dependencies of children, and grand children etc.
Option D) (dependency injector) the control uses this.api.addComment(post,text,callbacks) where the this.api is magically initialized during construction by some dependency injector which knows what the control needs
Option E) (service locator) the control uses something like serviceLocator.getApi().addComment(post,text,callbacks).. which is really just app.api.addComment(post,text,callbacks) in disguise ?
Option F) (my interpretation of react) the control expresses intent of adding a post, but does not pass any callbacks or otherwise expect the answer. Someone delivers this intent to a service which can process it. Later when the answer comes it is pushed top-down from the root to all nodes of the tree of components (which allows for a parent to selectively filter information passed to children). Alternatively the response is passed to all components directly. This seems to me quite similar to ...
Option G) (events bus) the control emits an event that it wants a POST to be performed. A service listens to such events and performs the POST, and when it is done it triggers an event containing the answer. All components interested in answer simply subscribe to this global event.
Android MVC realization
I has solid understanding of what MVC is, however it seems like there should be a better way to do it on Android platform. More specifically, I am concerned about activity lifecycle.
Let's say that I have an app that at some point of time should gather data from the Web. And here I have two options : 1) Stick up with self-sufficiency and implement everything in controller's class 2) Transfer all the code into separate classes, something like NetworkWorker.java, therefore implement Single responsibility pattern
First concept is fine, it seems to be solid and independent (like I can copy paste it into a new project and it won't have any dependencies), but I seriously doubt that having 1k+ lines of code in a single file will make it any readable.
Second concept seems fine, as my code will be more readable and easier to modify, plus, considering using multithreading, that seems like the only way to go.
swift reusability of ViewControllers
There are multiple view controllers in my current project that are used more than once in the app. My question is, how should I go about approaching reusing view controllers? So far I've thought of 3 possible ways:
- Write the controller completely in code
- Create the controller in the storyboard as usual, give it a storyboard id and call `instantiateViewControllerWithId:'
- Create the controller in a nib file and load it up from nib.
My question becomes: What are the pros and cons of each method? Which one is cleaner in terms of maintenance and lastly which one would you, as a savvy/professional iOS app developper, favour?
CPP: Design and inheritance
I have this classes:
template<class T> class CNode
{
friend class CTree<T>;
private:
T data;
...
CNode(data) : data(data) {}
...
public:
...
T get_data() { return data;}
void remove() { ... }
...
};
template<class T> class CSearchTree
{
private:
CNode<T> * root;
...
public:
...
void insert(T data) { /* Insert a new node... */ }
}
Everything is good so far. but when i try to extend this class to be a "Black Red Tree" i am lost.
I have 2 new classes: CBlackRedTree that inherit from CSearchTree and CBlackRedNode that inherit from CNode. The problem: When i call to insert function from CBlackRedTree, The function do everything fine but with CNode, But i wont CBlackRedTreeNode..
How do we solve it or how can I rewrite it differently so that it could work?
Thanks
rx android vs mosby pattern load data recyclerview
I am working on an Android app. The code I attach is creating a recyclerview. The very first thing we do is to create an asynctask that would fetch data on an sqlite database and load it into the adapter->recylcerview. While the background task is working, a progressdialog is shown to the user.
public class HomeActivity extends AppCompatActivity
{
private RecyclerView recycler;
private RecyclerViewAdapter adapter;
private SwipeRefreshLayout swipeRefresh;
private progressDialog progressDialog;
// ... some code here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ... some code here
createRecyclerView();
loadRecyclerView();
// ... some code here
}
private void loadRecyclerView()
{
new LoadingBackgroundTask().execute();
}
private void createRecyclerView()
{
Context context = getApplicationContext();
recycler = (RecyclerView) findViewById(R.id.recycle_view_home);
recycler.setHasFixedSize(true);
RecyclerView.LayoutManager lManager = new LinearLayoutManager(context);
recycler.setLayoutManager(lManager);
adapter = new RecyclerViewAdapter();
recycler.setAdapter(adapter);
recycler.setItemAnimator(new DefaultItemAnimator());
}
private class LoadingBackgroundTask extends AsyncTask<Void, Void, List<items>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(HomeActivity.this, getString(R.string.dialog_load_list),getString(R.string.dialog_please_wait), false, false);
}
@Override
protected List doInBackground(Void... params) {
List<items> lists;
//Data Source Class ( SQLite)
ListDS listDS = new ListDS(getApplicationContext());
list = listDS.getList();
return list;
}
@Override
protected void onPostExecute(List result) {
super.onPostExecute(result);
//it inserts de list on recyclerview performing animation
adapter.animate(result);
progressDialog.dissmiss();
swipeRefresh.setRefreshing(false);
recycler.scrollToPosition(0);
}
}
}
So far, so good. However, as your probably know this code has some well known issues, for example if I rotate the screen while asynctask is doing its magic, it will crash the app.
I've tried an alternative I've seen googgling, rxandroid.
( sorry if I typed something wrong, I amb doing it by memory )
public class HomeActivity extends AppCompatActivity
{
private Subscriber suscriptor;
private progressDialog progressDialog;
//some code ....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
suscriptor = new Subscriber() {
@Override
public void onCompleted() {
progressDialog.dismiss();
Log.d("SUSCRIPTOR","ON COMPLETE");
}
@Override
public void onError(Throwable e) {
Log.d("SUSCRIPTOR","ON ERROR");
}
@Override
public void onNext(Object o) {
adapter.animate((List<items>)o);
}
};
Observable.create(
new Observable.OnSubscribe<List<items>>() {
@Override
public void call(Subscriber<? super List<items>> sub) {
progressDialog = ProgressDialog.show(HomeActivity.this, getString(R.string.dialog_load_list),getString(R.string.dialog_please_wait), false, false);
List<items> lists;
//Data Source Class ( SQLite)
ListDS listDS = new ListDS(getApplicationContext());
list = listDS.getList();
sub.onNext(list);
sub.onCompleted();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Log.d("OBSERAVBLE","FINALIZED");
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.cache()
.subscribe(suscriptor);
}
@Override
public void onDestroy()
{
if(suscriptor!=null)
{
if(!suscriptor.isUnsubscribed())
{
suscriptor.unsubscribe();
}
}
super.onDestroy();
}
}
Now the app is not crashing anymore when I rotate the screen. However, the observable keeps working on the background until it finish but as I unsuscribe to avoid crashings I don't receive the results properly. Moreover, progressbar disappears eventhough the observable keeps working as I mentioned.
Looking for a solution, I found there is a pattern call "ted Mosby" which seems to solve my problem. Although it looks promising, I think is too much coding for somehting I felt it is not worth it and that rxandroid may have a walkaround.
So, my question is how can I get what I want without getting inmerse in an architectural coding mess too big for my purpose? Could you give an example if you guys have solved this? Do you think I am wrong and I should implement TedMosby pattern?
Many thanks!
Best way of handling object composed of two other objects in terms of hiding implementation details?
For instance, I have a class named Car which contains of two fields of type AdminPart and PassengerPart correspondingly.
For client code using my code I want the client code to be able to do car.getLicense() and not car.getAdminPart().getlicense() . This of course is implemented as getlicense() in Car which in turn calls the relevant getter. Same for setters.
Is there a best practice for this? Something I've overlooked ? Thanks :-)
Transfering an object over multiple clase instances
I am thinking of a optimum design pattern which I can use for transfer objects to the methods in different classes other than passing them as arguments.
class A{
}
class B{
public A a;
public B()
{
a = new B();
}
}
class C
{
public void c()
{
//need to access "a" of class B other than passing "a" as argument;
}
}
Here, "a" in class A attribute need to be accessed in many other class methods, Is there any optimum design pattern or any possible way other than passing this object (a) as arguments.
vendredi 29 janvier 2016
Design for system using real-time data from multiple sources
I am a new CS student working on a project to improve the bus arrival prediction system of my university. Here is a rough diagram of what the system would look like.
I have highlighted in yellow the four sources of data that we need to make our predictions. Note that the Bus Location Listener would maintain a TCP connection with the Bus Location Stream, and the other listeners would just asynchronously fetch the data from their respective APIs using a timer.
The issue is that while it has been easy to fetch the data mentioned above, compiling the data in the Data Model is proving to be a real challenge.
I was thinking of maintaining a single instance of the Data Model that would be shared between all the listeners so that they could each independently update their variables. Yet this feels like the wrong design choice given that it implies the creation of a singleton which I've heard is bad, not to mention I have no idea how to implement it in Python.
Any suggestion would be truly appreciated!
Which design patterns for machine learning pipeline?
Which design patterns or example of a class structure would you recommend for a machine learning pipeline (Java)? I think there is the strategy patterns and also the Cake pattern for Scala.
MVC pattern for Python scraper-to-DB plus web front-end
I'm about to develop a Python program that will scrape (lxml) to a two-database (SQLite or MySQL and a simple two-table schema) and also have bare-bones web front-end that will allow the user to select fields and boolean operators that will run an SQL query under the hood, and finally, save the output of the query as a CSV.
Although my knowledge of design patterns is minimal, from what I understand so far, this is a candidate for the MVC pattern.
What is a tried-and-tested example of MVC pattern for this sort of scenario? I intend to use a web framework such as Flask, Django, Pyramind or CherryPy.
JavaFX application - design of main class
I'm currently trying to develop application using JavaFX and I'm stuck just at the beginning. I want to use MVC pattern in this implementation and also make this implementation as reusable as possible. Basic description of the app:
1) It uses configuration file in which all database connections parameters (passes, logins) and other parameters used by the app are stored.
2) It's all about configuring of workflow of other application so it has to store two database object to two different databases and make operations through them in databases.
3) The design assumes that there are few views, every one has it's own controller and different functionalities can be done through them but all can trigger operations on database or configuration file.
4) The goals is also to remember the state of previous view while changing between views during usage.
That's why I have this questions:
1) While I start the application I test the connections to the database and if successful I connect to them. Is it ok that I do this in the Main class or should I have some other class in which I store all these db objects in case of referring to them in this class? Is it ok that every controller will use an instance of the Main class just because it has to access these db objects (assuming I decided to not use other class in which I do all the connections)?
2) What is the role of the main class? Should it be used as a main view (as in MVC) and should it only launch the application and pass the further responsibility to, for example, LoginController/View...?
I would be greatefull for some clear answer which could enlighten me this problem a bit.
There are no stupid questions, they say... :D
How to get index pattern configuration from elasticsearch / Kibana?
Where are stored data about index patterns and scripted field? I need to automate import of index patterns and scripted fields. Is it possible somehow?
Designing a cache initializer
I need to write a caching solution for my web application.
Basically I have lists of different objects that are kept in memory using Hazelcast. Each time the application starts the objects are loaded into memory from a persistent store. From time to time, the objects are persisted again back into the store.
The application is real-time (lots of websockets receive client requests modifying the data) so I need to be able to obtain/retrieve those objects very fast based on different type of ids and/or simple search criterias.
I was thinking to have different maps where the key represents the id and the value is the the instance of the object.
For example a certain type of object I will have a number maps (or multimaps):
- map1: < some_internal_key, object >
- map2: < some_other_internal_key, object >
- map3: < some_other_internal_key2, object >
- map4: < a_search_criteria, list< objects_meeting_the_criteria > >
- map5: < another_search_criteria, list < objects_meeting_the_criteria > >
....
And so on.
Those objects should be synchronized across all the 10 Maps, meaning if one object is modified, those modifications should be be available into all the maps. Sometimes, because this modifications the search criterias can be affected, so some objects should be associated with other keys.
From a code perspective how would you design this mechanism ? Do you have a better idea ?
RecyclerView and ViewHolder pattern - proper design approach
I've got RecyclerView list where items views are created partially from layout in .xml file (let's say header) and partially programmatically based on list items. I'm using few different itemsViewTypes.
Which approach is better?
1) to generate Views in adapter:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
createAndAddNewViews(barsHolder);
createAndAddNewViewsBasedOnSomeParams(param1, param2);
// both createAndAddNewViews() and
// createAndAddNewViewsBasedOnSomeParams() are Adapter methods
return holder;
}
2) to generate Views in ViewHolder:
public MyViewHolder(View itemView) {
super(itemView);
... // findViewsById and so on
createAndAddNewViews();
createAndAddNewViewsBasedOnSomeParams(param1, param2);
// both createAndAddNewViews() and
// createAndAddNewViewsBasedOnSomeParams() are ViewHolder methods
}
Of course my examples are simplified just to show the case.
From code reading perspective it's better to have views generation logic inside holders. Every different item has it's own creation code inside one class. I don't have to deal with every single item in Adapter. But I'm not sure if it's ok simply from ViewHolder pattern design and from memory and speed optimization perspective.
I wonder which approach you consider as better and why.
Thanks!
Multiple User Application
I need to create a monitoring and reporting application.
Rule is, in this application select
query alone should be used in all modules.
No update
or insert
should be used.
All db inserts will be made by other application. search alone required using my application. Multiple users may search same data in same time
My doubt is whether concurrency implementation is required for this application? If so kindly suggest easiest way to achieve this.
Struts2 + DAO + Factory
The BridgePattern decouples an abstraction?
I learned Bridge pattern from different articles and i have implemented that as per understanding . One thing that is confusing me is bridge pattern says
BridgePattern decouples an abstraction from its implementation so that the two can vary independently
what is mean by this statement? Is implementation resides at in separate jar ? what is mean by vary independently ? considering the provided link elaborate the answer.
Any help be greatly appreciated.
Understanding bridge pattern and Java streams
I'm reading GoF design patterns and now I'm trying to undersand the Bridge pattern. Now, consider the Java streams (official documentation).
They introduced two kind of streams: Node streams and Filter streams. The last one uses Node streams to perform the actual wrtiting to/ reading from another stream. So Node streams incapsulate low-level io details. In the sense of GoF Bridge pattern, can Node Streams be considered as a bridge (Implementor
) which are used by Filter streams?
If so, is it a good practice to not create a separate interface for a Bridge. E.g.
public interface DataWriter{
public void write(Object);
}
In my case there might be two kind of implementatios: One that defines low-level io details, and one that performs convertions, validation and so forth ans uses underlying DataWriter to write data (to file system persistance store, Java OutputStream
and so forth). Can I consider that the first one is a bridge and just write a JavaDoc for the interface in order to avoid creating another DataWriterImplementor
interface?
Parsing command line arguments and use them to initialize application that has to be implemented using abstract factory pattern
I have written an application that parses a command line and initializes the application, but is in C language. But the required application is to be written in C++. The following code snippet extracts/parses the arguments and calls respective functions.
void (* const OptionFuncPtr[])(char *pstr) = {
(SetA),(GetB), (SetC), (SetD), (Erase), (FOptions), (GOperations),
(ShowHelp), (SetInput), (undefined), (undefined), (SetLBit), (undefined), (undefined),
(OutputData), (ProgramOptions), (ReadAll), (ReadData), (SOptions), (TestMode),
(undefined), (VerifyData), (WOptions), (FillUnspecific), (ReadLBits), (NoProgessIndicator)
};
int main(int argc, char *argv[])
{
...// some code
for( int i = 1; i < argc; i++ )
{
param = argv[i];
/* Allow parameters to start with '-' */
if( param[0] != '-' )
throw new ErrorMsg( "All parameters must start with '-'!" );
if( strlen( param ) <= 1 )
throw new ErrorMsg( "Parameters cannot be just the minus without any characters!" );
value = param[1] - 'a';
if(value > 26)
throw new ErrorMsg("You have not entered a valid command line parameter");
(*OptionFuncPtr[value])(¶m[2]);
}
//some more code
return 0;
}
As it can be seen, the code is in C. and I need to write it in C++. I am a noob to C++ and working on a deadline. I have read a lot of articles, but have not been to able to concrete any thing yet. Dont know how to implement this using C++. The methods that i am calling may be from different class. I think this is achievable using functors. But not sure. It would be helpful if any one can just give a small example, from where i will carry things forward. Need to use abstract factory pattern also.
Ps: This may seem to be a very basic question, but i am newbie to C++. :)
what is dao,dto and service layers in spring framework?
I am writing RESTfull services using spring and hibernate. I read many resource in internet, but not clarify my doubts. Please explain me detail what are dao,dto and service layers in spring framework and what are concern use these layers in spring to develop RESTfull Api services.
jeudi 28 janvier 2016
How to inherit state from multiple classes?
I have a composite like pattern in where there is different functionality for the roots of the trees, branches and leafs. The problem is that there is a shared state between both Root with Branch and Branch with Leaf. I'm searching for the cleanest solution which prevents code duplication.
The functionality among root, branch and leaf all relate to the same set of methods (though leaf has different signatures).
- Embeddable interface implicates that the implementation has a parent and some mutable properties.
- Composite has Embeddable children and provides abstract functionality methods for which Root and Branch have their separate implementations.
- Root is the actual executor of most functionality.
- Branch will most often - but not always - pass information to its parent with modified parameters.
- Leaf can appear both on the root and branches and has fewer functionality methods with smaller method signatures. Will always pass its calls to its parent with extra parameters. It is stored explicitly in every Composite where it is created and loaded lazily.
Shared state
- Root and Branch's shared state is in this case solved by Composite.
- The Embeddable interface enforces that Branch and Leaf provide its behavior.
The problem the implementation is the same for Branch and Leaf and implementing it would cause duplicate code. It's impossible to make Embeddable an abstract class because Branch already extends Composite.
I'm searching for a pattern or general solution so that Branch can share state with Embeddable and Composite at the same time. Basically a multiple-inheritance workaround.
Refactoring: when visitor pattern can't be used to replace switch/instanceof
I'm trying to do some refactoring on a piece of code using instanceof in order to determine the type. I think subtyping/polymorphism wouldnt work in this case (and even if it'd be too much of an overkill in this situation) and visitor pattern won't work here since I don't have the possibility to add an accept method to the annotation. Are there any other ways to make this sort of code cleaner/more readable?
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof DELETE) {
setHttpMethod(annotation.annotationType().getSimpleName(), false);
parsePath(((DELETE) annotation).value());
} else if (annotation instanceof GET) {
setHttpMethod(annotation.annotationType().getSimpleName(), false);
parsePath(((GET) annotation).value());....
Design Pattern to combine data from different databases
I'm getting some data from two different databases and i need to format these data to JSON.
The problem is not access both banks and get the data. The problem is that my class was more complex than it should. One of my JSON fields is dependent on data that is in another DB. Then for each time it builds the JSON data with a DB, it has to go on another DB to fill these information. Here is an example code:
public class JsonClipAlerta
{
public JsonClipAlerta()
{
}
public long Id;
public IList<string> EnderecosEletronicos { get; set; }
public IList<ExpressoesStruct> Expressoes { get; set; }
public string IdCript { get; set; }
public static JsonClipAlerta FromClipAlerta(ClipAlerta arg, Usuario usuarioLogado)
{
var crypto = ContainerHelper.Resolve<IServicoDeCriptografia>();
var jsonClipAlerta = new JsonClipAlerta();
var repositorioEnderecoEletronico = ContainerHelper.Resolve<ComuniqueSeWorkflow.Dominio.IRepositorios.IRepositorioEnderecoEletronico>();
jsonClipAlerta.Id = arg.Id;
jsonClipAlerta.IdCript = crypto.Criptografar(arg.Id);
jsonClipAlerta.Expressoes = arg.Expressoes.Select(e => new ExpressoesStruct { id = crypto.Criptografar(e.Id), text = e.Descricao }).ToList();
jsonClipAlerta.EnderecosEletronicos = repositorioEnderecoEletronico.RetornaColecao (arg.EnderecosEletronicos.ToList()).Select(ee => ee.Endereco).ToList();
return jsonClipAlerta;
}
}
public struct ExpressoesStruct {
public string id;
public string text;
}
The way to PHP MVC design pattern
In fact i need the help from the experts in this field,i want to improve my programming skills so i decided to learn PHP MVC D.P , in fact after research i found many of good resourses
like Pro PHP MVC and many group of videos on youtube
i have a good knowledge in
(OOP,basics of D.P[MVC,singletone,factory,meditor,facade])
but I irresolute to start the learning because i don't know if my skills right now can help me to start directly , in other words i need someone expert help me to start correctly
Should a respository be responsible to update specified field of model stored in external service?
I understand that the repository should be responsible for CRUD in repository pattern. My question is: should a respository be responsible to update specified field of model stored in external service?
For example:
- The
UserAccount
data is stored in external web service. - The user could have multiple
UserAccount
- By the app, the user can select target
UserAccount
and can updatedisplayName
ofUserAccount
- There are some words not allowed to use in displayName and the app doesn't know what are those words.
pesdocode:
public class MainController
{
IUserAccountService userAccountService; // injected
public void Main ()
{
userAccountService.GetUsers ().Then (UpdateUserView);
}
// ...
void OnUserAccountSelected (UserAccount selectedUserAccount, string newDisplayName)
{
userAccountService.UpdateDisplayName (selectedUserAccount, newDisplayName)
.Then (UpdateUserView)
.Catch<WordInDisplayNameNotAllowedException> (HandleWordInDisplayNameNotAllowedException)
.Catch (HandleError);
}
}
public class UserAccountService : IUserAccountSercie
{
IUserAccountRepository repository; // injected
// ...
public Promise<UserList> GetUsers ()
{
return repository.GetAll ();
}
public UpdateDisplayName (UserAccount userAccount, string newDisplayName)
{
// Should I like the following?
repository.UpdateDisplayName (userAccount, newDisplayName);
}
}
public class UserAccountRepository : IUserAccountRepository
{
public Promise<UserList> GetAll ()
{
// request to external web service...
}
public Promise<UserAccount> UpdateDisplayName (UserAccount userAccount, string newDisplayName)
{
// request to external web service...
}
}
Where should I put codes to call web API to update UserAccount::displayName
?
Search for pattern - filling model
im writing a java application where i have to fill plain objects with values.
example object
public class A {
private String a;
private String b;
// ...
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
// ...
}
i fill it like this
public class Initalizer {
public A init() {
A a = new A();
a.setA(// get it from somewhere
);
a.setB(// get it from somewhere
);
// ...
return a;
}
}
in this case, i get the values from jsoup, a html-parser
my question is: is there a more elegant way? like defining one method for filling one property. like in lego where one stone fits the other.
is there a design-pattern i don't know?
thanks for help
How to represent web pages in OOP
Let's say there's a web page: shop.com
Basic structure:
shop.com/search
shop.com/user
shop.com/user/cart/
needs authentication session.
I am building a parser for this web page using Jsoup, to extract piece of text from a target page. I would like to program it as a "web page as an API".
So my queston is, how should I design my program?
Right now I have something like this:
Shop shop = new Shop(username, login) // instantiating the user session
Document shoppingCart = shop.getShoppingCart(); // returns org.jsoup.nodes.Document
The problem here is that what if I need more data from many different pages, e.x.:
shop.findBestDeals() // would not need login session
shop.getUsedSearchTerms() // would need login session
All the parsing weight would be on Shop class. Plus logging the user in for no reason, if page doesn't need it.
So I thought of using static methods like this, where each page would be a class:
Document cart = Cart.getShoppingCart(usersession)
Document deals = Shop.findBestDeals()
Document dealsForUser = Shop.findBestDeals(usersession) // if web page would display special items for logged in users
So basically, have web pages as classes, and they would all have static methods for data retrieval. As I now think about it, each "page-class" would require lots of (the same) imports (as other classes), would it be okay, or is there a design pattern to prevent this from happening?
This is the best I can come up with as a first year student for "web page as an API" problem.
English is not my first language, so feel free to ask further questions! :)
PS: not a homework, my personal project!
How to explain design pattern of singleton with python?
I think use polygamy example is good to explain how this work does.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Phil Huang <pichuang@cs.nctu.edu.tw>
# pylint: disable=missing-docstring, line-too-long, too-few-public-methods
"""
Singleton
Reference
http://ift.tt/1kaspPp
http://ift.tt/1KCunDn
http://ift.tt/1ROVe53
"""
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Husband(metaclass=Singleton):
def __init__(self):
self.name = "pichuang"
class Wife(object):
def __init__(self, name, husband):
self.name = name
self.husband = husband
def love(self):
print("{0} love {1} (object id is {2})".format(self.name,
self.husband.name, id(self.husband)))
def main():
wife_1 = Wife(name="Arimura Kasumi", husband=Husband()) # http://ift.tt/1QuLQ3A
wife_2 = Wife(name="Hashimoto Kanna", husband=Husband()) # http://ift.tt/1ROVbq3
wife_1.love()
wife_2.love()
if __name__ == '__main__':
main()
We can know polygamy is one husband, one or more wife. So, we just create one husband instance with Husband class and create one or more wifi instance with Wifi class.
In this case, Arimura Kasumi and Hashimoto Kanna are two of wifi instances, and "pichuang" is one of husband instance. They only love their husband, and the answer is one.
Source code: pichuang/Design Pattern of Loser
Python CLIPS|Pattern for italian language
i need help to use this library with Italian Language.
I'm trying to use Pattern to create a dataset (to perform NMF) of Italian Feed RSS/ATOM but i don't know how to do it because the Lemmatizer won't work with italian sentence.
I'm using as guideline this examples with an italian text from wikipedia. but the result is the same of the input string.
Any suggestion?
What is the best way to share variables between a large number of classes?
I'm using Java to do some complicated calculations, and have a lot of classes that need access to a lot of the same variables. These variables are set at different stages of the calculations, in different classes. The problem is that my code is getting quite messy as I am being forced to pass the same parameters to a lot of different methods.
I am looking for peoples thoughts on what the best approach here would be? One idea I have is to make a superclass with all these variables set in it and extend this class everywhere it is needed.
Another option is to pass an object holding all this information around from method to method but this seems overly complex. Neither of these solutions feel like the cleanest approach to me. Any thoughts or suggestions of design patterns/ideas that may help me are appreciated. Thanks for your help.
mercredi 27 janvier 2016
elastic search matching issue
I am having an issue with finding results when I make an elastic search query. I have verified that the index has the search elements.
This is my query. The idea is to find all elements that have "ale" in whole or in part on the LOGIN, FIRST_NAME and LAST_NAME fields. I don't have any entry that has a first name or last name or login with the exact term "ale". However, I do have entries indexed that have part of the first name or last name or login as "ale".
I think I am doing something wrong, but I am not sure how I can accomplish this.
Please advise.
SEARCH: {
"query" : {
"query_string" : {
"query" : "ale",
"fields" : [ "FIRST_NAME^10.0", "LAST_NAME^10.0", "LOGIN^10.0"]
}
},
"_source" : {
"includes" : [ "FIRST_NAME", "LAST_NAME", "LOGIN"],
}
}
How to tell the object of the death of another object?
On my work I have met with one bug which can be described as follows. There are two classes, class A and class B:
class A
{
public:
void print(){}
};
class B
{
A* a;
public:
void init(A* _a) {
a = _a;
}
void PrintWithA()
{
a->print();
}
};
A* a;
B* b;
b->init(a);
// some code .....
delete a; // line 1
a = NULL;
// some code .....
b->PrintWithA(); // line 2
Object "b" doesn't know nothing about state of object "a". In line 1 "a"object has been deleted but on line 2 we continue to use it. When there are a lot of code it is very easy to make such mistake. My question is the following - which approch to use to avoid some mistakes? I guess I could use observer pattern - but I think it is unjustifiably expensive solution. Thank's.
Best code structure for pulling data, adding logic for how it is displayed
My current task is to create a dynamic email based on data from a database. The only issue is that I am going to have to add logic within the code to display what data and where.
My main question is what is probably the best way of structuring this code? Should I use 300+ if statements (i really don't want to), cluttered loops to gather data from arrays, or something that involves using OOP styled PHP?
Here's what I am trying to achieve:
For every order that is made online, there is an unique order-id
attached to it.
All order data is inserted into a MySQL database
A few days after they order online, we send them an email with instructions based on the data in the database.
For example:
Order #10
purchased a hotel stay on 02/05
that includes a shuttle ride to the grocery store,
at the specific time of 3:45 pm
In the database there would be a column for: order-id
, check-in-date
, shuttle-ride
, shuttle-ride-location
and shuttle-pickup-time
base on that data, in the email there needs to be instructions on what to do, like this:
02/05/16 : Arrive at the hotel, check in with your order id number, at 3:30 pm head to the hotel lobby to wait until 3:45 pm for your shuttle ride to the grocery store, at xx:xx xx call the driver to pick you up and bring you back to your hotel...*
02/06/16 : Check out of hotel at xx:xx xx, head to the airport X, etc.
Is there a proper way of achieving this in PHP, a certain type of style that would be considered more efficient and cleaner structure?
Thanks.
When using the builder pattern, is there a way to pass data from one of the objects being used to build to another object?
I have two objects that are put together to create another object in a builder pattern in Java. One is a PayloadData abstract class object, the other is a HeaderData object (not abstract). They inherit from an interface called MessageElement. However, I need the PayloadData object to pass its size (I already have code that creates a variable in Payload that has this stored) to the Header object. How can I do this? PayloadData is an abstract object that is overriden by "Type"Payload (the type of data stored by payload).
HeaderData has a method for calculating overall message size:
public int messageSize() //This method is finsihed already, but needs to be fixed.
{
return PayloadData.elementSize() + 16; //Something here need to be fixed.
}
But this doesn't seem to work.
PayloadData has this method (which is overridden by the class that inherits from it:
public int elementSize() {
// TODO Auto-generated method stub
return 0;
}
The concrete object has this: to override it:
@Override
public int elementSize() //This is the one override that I think will be needed. Need to figure out how to pass this to
//HeaderData, as right now it is not accepting it.
{
return (48 + 184 * tracksInMessage());
}
I think I need to modify the builder pattern I'm using to let HeaderData access elementSize, but how should I do that?
Remember there is a class that is ultimately built, a Message class in this case, which is assembled from the HeaderData class and the class that inherits from PayloadData, and there is a builder class and a class that uses the builder class to create Message objects.
Here is the pattern I followed by the way, I replaced Burger with PayloadData and replaced ColdDrink with HeaderData but made it a concrete object:
Design pattern for an optimization module
I have an application and optimization is one of the modules.
- The user selects a couple of options (option 1, option 2,...), and then run optimizations.
- I also have a couple of optimization models. Some of them can only handle option 1 type optimization, and some can handle option 1 and option 2 (by passing different parameter values), and so on.
- Some optimization models are just variants of others, e.g, some more variables, different bounds, additional constraints. So, some of the codes are actually the same among these models.
- In the future, there may be other optimization models are complete new compared with existing ones.
Currently, I am thinking the following design:
- Build interfaces for each of the optimization options;
- Build abstract classes for some of the models that have a lot similarities.
- Build optimization models that inherit from this abstract class (I still found some codes are exactly the same among these concrete classes.).
- Build implementations of the interface by calling these optimization models.
I feel it is very confusing. By the end, I still have a lot of overlap among the optimization models (adding some common variables to the solver, set their bounds, etc). What is a better design that is suitable for this module?
State Design pattern and infinite loops with MonoGame
I am trying to use state design pattern with my game(MonoGame game).I want to detect collision , so I give cell type and upon it gives me a specific action.But unfortunately this implementation gives infinite loop "Exception.StackOverflow" in player instances.
abstract class PlayerState
{
abstract public void doAction(Player player );
}
Classes implements PlayerState
class DeadState:PlayerState
{
public override void doAction(Player player)
{
player.dead();
player.setState(this);
}
}
class IncreaseGold: PlayerState
{
public override void doAction(Player player)
{
player.increaseGold();
player.setState(this);
}
}
Player.cs
public void setState(PlayerState state) { this.state = state; }
public PlayerState getState() { return state; }
ActionController.cs
Player player = new Player();
public void passCell(int cellType)
{
if (cellType == 1)
{
new DeadState().doAction(player);
}
if (cellType == 2)
{
new IncreaseGold().doAction(player);
}
}
finally in my Update method on Game1.cs
protected override void Update(GameTime gameTime)
{
player.passCell(cellType);
base.Update(gameTime);
}
Can you help me apply a Bridge pattern to an exisitng class design?
As you can see I have an interface for Debug Events and two operations Attach and Detach. On top of this I have to implement a Windows and Linux version so the current design does not scale at all.
Imagine that I have to add:
- DebugEventThread <- DebugEventThreadAttach <- DebugEventThreadDetach
- DebugEventProcess <- DebugEventProcessAttach <- DebugEventProcessDetach
This design blows out of proportions...
I know Bridge pattern would be a solution to this problem but I don't know how to apply it in this case.
ActionScript game, having trouble implementing decorator class
So, I've created a tile based "match 3" game in ActionScript and there are a few different types of tiles the main tiles are just letter tiles, and then there are special tiles like a bomb for instance and each tile has similar functionality but each one has special functionality.
Right now, I just have a Tile class that handles all of the functionality which is not the way to go. I think a decorator class would be the best route however implementing it, i am running into issues.
So below is how I have it structured, how would I handle storing the tiles in a Vector? and how would I add to stage?
Currently, I store the tiles in a Vector.(I have one Tile class that handles all of the type types which is ugly). If I were to move to a decorator pattern, it seems that I would be storing a Vector of ITile, how would I add "Itiles" which are essentially LetterTiles and BombTiles to stage? I get Type Coercion errors when trying.
Also, the decorator pattern just seems to be basically an interface, which all types would just implement, so for example, if I were to take an existing LetterTile on stage and say it needs to convert to a BombTile, How would I go about changing or updating the current tile into a Bomb tile?
example:
public interface ITile
{
function create():void;
function remove():void;
}
and BaseTile.as
public class BaseTile extends Sprite
{
public function create():void
{
throw new IllegalOperationError("Must override in concrete class");
}
public class remove():void
{
throw new IllegalOperationError("Must override in concrete class");
}
}
LetterTile.as
public class LetterTile extends BaseTile implements ITile
{
public override function create():void
{
trace("Letter Tile Created");
}
public override function remove():void
{
trace("Letter Tile Removed");
}
}
BombTile.as
public class BombTile extends BaseTile implements ITile
{
public override function create():void
{
trace('Bomb tile created');
}
public override function remove():void
{
trace('Bomb tile removed');
doExplosion();
}
public function doExplosion():void
{
//This would do something different than regular letter tile.
}
}
Hopefully this makes sense, I needed to add as much info as I could without creating a TL;DR
What's the different between ContentObservable and DataSetObservable?
They both inherit from Observable. And their functions do not differ by much, why not provide only a single class?
Xml Schema Pattern At The Beginning Of A String
I am new to XML Schema and to RegEx.
I want to define a pattern that matches the following structure:
<fantastic>:item.attribute</fantastic>
as well as:
<fantastic>:item.attribute,:item.attribute,:item.attribute</fantastic>
I would like to have pairs of items and attributes. If there is more than one pair, the pairs should be seperated by a comma. So I would like to tell the parser the following:
'If the pattern starts at the beginning of a string no comma is put before it. Else a comma needs to be put before the (repeated) string.'
The pattern for the item and the attribute is much more complicated. But it works with the exception of the comma seperation between the pairs.
I have done some research and found out that ^ is used to tell the parser that the previous character has to be at the beginning of a string.
But I could not use it in XML Schema Pattern. Does even exist in XML?
How would you write this?
Kind regards
Understanding Chapter 2 Q 22 of A Little Java, A Few Patterns
In Chapter 2 of A Little Java, A Few Patterns, Question 22 is:
Are there only Onions on this Shish^D:
new Skewer()?
Answer is:
true, because there is neither Lamb nor Tomato on new Skewer().
Skewer is a subclass of Shish^D, Onion is also a subclass of Shish^D, I don't understand why there are onions on new Skewer()
, could someone explain this a bit further?
Where to define the menu items event handler
I have a DataGridView on a WinForm. When the user right-click on the grid, I am showing a popup menu. There are 3 kinds of popup menu according to where the right-click has been done:
- on a row that is defined as readonly
- on a row that can be edited
- on any other place in the grid (rowindex is -1)
I created a new classes to manage the popup menus generation.
public class GridPopupMenuFactory
{
public ContextMenu GetMenu(int rowIndex, bool isReadOnlyRow)
{
BaseMenu _menu = null;
switch (rowIndex)
{
case -1:
_menu = new GeneralMenu();
break;
default:
if (isReadOnlyRow)
{
_menu = new ReadonlyRowMenu();
}
else
{
_menu = new EditableRowMenu();
}
break;
}
return _menu.Menu;
}
}
public abstract class BaseMenu
{
protected ContextMenu _menu;
public ContextMenu Menu
{
get
{
if (_menu.MenuItems.Count == 0)
{
GenerateMenu();
}
return _menu;
}
}
protected abstract void GenerateMenu();
}
public class GeneralMenu : BaseMenu
{
protected override void GenerateMenu()
{
var contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(new MenuItem("Sort"));
contextMenu.MenuItems.Add(new MenuItem("Print"));
_menu = contextMenu;
}
}
public class ReadonlyRowMenu : BaseMenu
{
protected override void GenerateMenu()
{
var contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(new MenuItem("View"));
_menu = contextMenu;
}
}
public class EditableRowMenu : BaseMenu
{
protected override void GenerateMenu()
{
var contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(new MenuItem("Add"));
contextMenu.MenuItems.Add(new MenuItem("Edit"));
contextMenu.MenuItems.Add(new MenuItem("Delete"));
_menu = contextMenu;
}
}
My question is where is the correct place to define the event handler for each one of the menu items?
Object oriented design for rules engine
I need some help from OOP guys to help me decide the structure of a pay rules engine I want to develop for employee's attendance. Finally I want a jar that takes csv input and returns csv output. This jar will take attendance shifts and rules as input and provide me back the outputs ie calculations from rules applied on those shifts like overtime hours and respective pay.
Basically I will have a GenericEngine
for normal employee's overtime hours and say some extended functionalities according to state overtime laws like one custom OregonEngine
, that will process a specific rule for premium hours(this wont be provided by GenericEngine)
Situation as I know it's going to be like:
RulesProcessor
will take input as shiftsList and rulesList.- If
GenericEngine
can process all the rules on all the shifts then it'll do it or ask specificEngine like OregonEngine to do so. - Every custom engine like
OregonEngine
can useGenericEngine
but not necessarily. RulesProcessor
should be able to do calculations using Generic and Custom engines. 5.Calculations has to be stored somewhere because some rule ,say weekly overtime, might require it.
mardi 26 janvier 2016
Where does apply rules of application
This question is about applying rules of my application that confuse me.
My controller is using service and the service is using repository.
public class CommentController: ApiController{
[HttpPost]
public bool EditComment(Comment comment){
commentService.Update(comment);
}
}
public class CommentService{
ICommentRepository repository;
....
....
public void Update(Comment comment){
repository.Update(comment);
}
}
If the user is authenticated, he can update a comment.
- But a user should edit own comments.
- But an admin can edit all comments.
- But comment can not edit after a specified date.
- Edit by a department
And I have something like these rules.
I am confused a bit about where can I apply the rules. In controller or in service or in repository.
Is there any standart way to do this like design patterns.
Angular pattern for ensuring single active promise
In our application, we have an search input field. Typically a request is sent while the user types (a la Google Instant) and the results are displayed.
Obviously, the following can happen:
- User types, which results in ajaxRequest1
- User continues typing, resulting in ajaxRequest2
- results2 corresponding to ajaxRequest2 are received and displayed
- After this, results1 corresponding to ajaxRequest1 are received. Obviously, since ajaxRequest2 was sent after ajaxRequest1, we only care about results2, not results1.
EDIT: The obvious answer here is "Use debounce". For reasons of confidentiality and brevity, I'll just say here that it won't work in our particular scenario. I know what debounce does and I have considered it.
In pseudo-code, we used to handle it like this:
$scope.onInput = function() {
var inputText = getInput();
SearchService.search(inputText).then(function(results) {
// only display if input hasn't changed since request was sent
if(inputText === getInput()) {
displayResults(results);
}
});
};
Since this involves a lot of boilerplate and looks ugly, we moved to a pattern where the SearchService
manages things a bit better
$scope.onInput = function() {
var inputText = getInput();
SearchService.search(inputText).then(function(results) {
displayResults(results);
});
}
function SearchService() {
var cachedSearchDeferred;
this.search = function(inputText) {
if(cachedSearchDeferred) {
//means there's an unresolved promise corresponding to an older request
cachedSearchDeferred.reject();
}
var deferred = $q.deferred();
$http.post(...).then(function(response) {
// saves us having to check the deferred's state outside
cachedSearchDeferred = null;
deferred.resolve(response.data);
});
cachedSearchDeferred = deferred;
return deferred.promise;
}
}
This works fine. The SearchService
creates a deferred containing the promise corresponding to the most recent call to SearchService.search
. If another call is made to SearchService.search
the old deferred is rejected and a new deferred is created corresponding to the new call.
Two questions:
- Is this a good pattern to do what we need - essentially request locking? We want to ensure that only the most recent request's promise resolves successfully
- If we had other
SearchService
methods that needed to behave similarly, then this deferred boilerplate needs to be inside every method. Is there a better way?
How do "static" keyword works? (a code example)
When i tried to create C and B in global namespace - it did work correctly. When i turn B::create_unit() into body of C::create_unit() -> it becomes broken and dont work.
Do someone help me with static understanding? I dont know, why it doesn't work.
Class A {
protected static $_instance;
public $methods = array();
public function __call($name, $args) {
$obj = $this->methods[$name]['obj'];
$method_name = $this->methods[$name]['method_name'];
call_user_func_array(array($obj, $method_name), $args);
}
public static function add_method($name, $obj, $method_name) {
$unit = static::get_unit();
print_r($unit); // OMG, IT PRINTS (OBJECT B)!!!
$unit->methods[$name]['obj'] = $obj;
$unit->methods[$name]['method_name'] = $method_name;
}
public static function create_unit() {
return static::$_instance = new static();
}
public static function get_unit() {
return static::$_instance;
}
}
Class B extends A {
public static function create_unit() {
return static::$_instance = new static();
}
public function log($msg) {
echo $msg;
}
}
Class C extends A {
public static function create_unit() {
$obj = static::$_instance = new static();
$b = B::create_unit();
C::add_method('foo', $b, 'log');
$obj->foo('message');
return $obj;
}
}
C::create_unit();
nodejs auto refresh view after database updates
I would like use nodeJS to refresh my view, every time a function has made changes to the database. If we take MEAN-stack as an example, I don't want to send an $http-request every x seconds to check if changes have been made to the database. I would like the front end to get notified automatically and then update the view.
What are best practices for this? I would use some kind of Oberserver pattern in the server side, but do not know how I could notify the front end with that.
New to MVC - structure for db driven website with static and article pages
I am creating a website and want to use MVC
pattern (for learning experience), but I am struggling with what structure of model / view / controllers would I need in order to achieve this and how should they interact?
-
Website consists of static pages (about, contact, mission statement etc) and "blog" pages (articles).
-
The top navigation will have links to About/Contact/Mission Statement and separate hierarchical lists of Category > Subcategory to get at the "blog" article pages. e.g.
Opinions > Politics, Current Events, The Weather
Reviews > Movies, Music, Art Exhibits
-
Clicking on a subcategory e.g. Reviews > Movies should bring up a list (in a table) of all blog entries with that subcategory with hyperlink
-
Clicking on a link to a specific entry within Reviews > Movies (or whatever) listing page should go to a detail page with the title, author, date, content etc.
-
Articles are made up of "sections" each with its own header. An article can have 1 or more sections.
-
Articles will be stored in a database (mysql)
Database structure I have so far is: Category (id, name) Subcategory (id, name, CategoryID FK) Article (id, name, date written, author ........ SubCategoryID FK)
I am not sure how to fit "ArticleList" and "Article" together in a controller or what to put for the model for each.
Design pattern for dealing with reusage of date in scenarios (BDD)
I would like your suggestion for my scenario:
I am implementing automated tests using bdd technique with Cucumber and Selenium WebDriver tools, what is currently happening is: a lot of scenarios depend of data of each other, so right now I am storing these data in the class I define the steps, so I can use in other scenarios.
But, as the application grows, and the more scenario I get, the more mess my application gets.
Do you have any design pattern, or solution I could use in this case?
Does it make sense to use composite pattern in tree view?
I have a tree view where every node is a different type of item - only the label and description property is the same. Does it make sense to represent each of these node item by composite component?
One of the reason I ask is that I have noticed while applying composite design pattern makes it easier to apply aggregate function (applied to aggregate object), it gets somewhat harder to actually access individual items inside that aggregate.
This usually means to access the individual item, it will require type casting the item back to its original type or it needs to contain the type information which is considered a bad practice in OOP. These inner objects are not really exposed anyways in common examples.
To put this in perspective, consider I have TreeView which shows tourist attraction in 3 major cities. The first level of node is the city name, which than contains attractions in that city.
New York
Time Square
Central Park
London
British Meuseum
Paris
Eiffel Tower
So now when user clicks on city, the program displays information about that city (say in right pane), if they click the attraction, it shows information on that attraction.
Is this a fit for composite design pattern? if so wouldn't it require typecasting the component back to what exactly it is like city or attraction?
Secondly wouldn't that require digging out the component out of the composite to be able to display it? Kind of against the pattern which tends to put them together?
If it matters, my environment is C++/Qt.
Redefining methods in JavaScript
First of all, sorry for my broken English - I am not a native speaker.
Now, on to the problem:
I am learning JavaScript design patterns and while trying to implement a bit more complex example of decorator pattern I realized that I cannot modify methods defined in a constructor, but I can modify methods defined with a prototype.
Can someone please explain to me why is this the case, or if I missed something really important along the way.
This is the code of the pattern:
// Basic constructor with one parameter and test method
var ExampleOne = function (param1) {
this.param1 = param1;
this.test = function () {
console.log('Test One');
}
}
// Adding logParam1 method using prototype
ExampleOne.prototype.logParam1 = function () {
console.log(this.param1);
}
// Adding testTwo method using prototype
ExampleOne.prototype.testTwo = function () {
console.log('Prototype Test');
}
// Creating instance of ExampleOne
var example = new ExampleOne('Parameter One');
// Simple decoration
example.decorate = function() {
console.log('Decoration One');
}
// More complicated decoration
var ExampleTwo = function(param1, param2) {
ExampleOne.call(this, param1);
this.param2 = param2;
}
// Creating separate prototype from original one
ExampleTwo.prototype = Object.create(ExampleOne.prototype);
// Trying to change test (defined in constructor)
ExampleTwo.prototype.test = function () {
console.log('Test Two');
}
// Trying to change logParam1 (defined using prototype)
ExampleTwo.prototype.logParam1 = function () {
console.log(this.param1 + ' ' + this.param2);
}
// Creating instance
var examplee = new ExampleTwo('Test Two', 'Decoration Two');
// Testing
example.test(); // Expecting: Test One, Returns: Test One
example.testTwo(); // Expecting: Prototype Test, Returns: Prototype Test
example.logParam1(); // Expecting: Parameter One, Returns: Parameter One
example.decorate(); // Expecting: Decoration One, Returns: Decoration One
examplee.test(); // Expecting: Test Two, Return: Test One << WHY?
examplee.testTwo(); // Expecting: Prototype Test, Returns: Prototype Test
examplee.logParam1(); // Expecting: Test Two Decoration Two, Returns: Test Two Decoration Two
// examplee.decorate(); // Expecting: error, Returns: error
Thnx.
Basic design pattern for individual based modeling
Dear stackoverflow community,
im working as a researcher at for the environmental sciences department at a university. Currently im developing individual-based-models (which are kinda similar to agent-based-models) using C#. Basically i have alot of individuals that run through processes like Eating(), Reproducing(), Ageing(), etc...
The larger and more complex those models get, its really hard keeping track of them, although i've tried my best doing it in a object-oriented way.
So my Question is:
Are there any basic design pattern for individual based modeling (object oriented) ?
I've heard of some books about system theory and i have seen some very clever implementations of models. For example one model has for each containing modules only the basic methods:
Input()
Output()
Update()
ConnectTo()
Dispose()
...
and puts all those Methods to an abstract class called Submodel().
Is there any literature about that. ? I googled alot but couldnt find anything usefull.
Thanks a lot!
Phillip
PS: Im more the mathematician but had some courses about c# and object oriented programming.
New Concepts in Programming
So I am a developer. At least I think I am a developer, or if I could say that better, I have just thought that I am a developer but I don't do it anymore. I have developed .Net applications for more than 7 years. of course it's not very short. I really developed nice and reliable applications. They really work great in both windows and web platforms. The problem is that my knowledge is very old. I was a great designer and developer if it was 7 years ago but I'm not familiar with new concepts. For example I know Asp. net web form but I don't know MVC, Or I use SqlHepler very good but I can't use ORMs. I can design a two layer Object Oriented project but I'm not familiar with DDD or SOA architecture and can't use design patterns in them. Well, so why am I asking this question? The answer to my concerns is very straightforward! You may answer: "Ok, You know what you don't know. So go and learn them!!" I know it! But I am very confused of WHERE should I learn. Now a days I see big projects in .Net that they have lots of inner projects like ServiceHost, ServiceContract, Domain and they have lots of folders like BusinessRepository and etc. I'm not sure that they are SOA that use DDD or they are DDD that use services. They use lots of frameworks like Windsor (they use IOC). I want to learn these concepts. I do not want to read a complete book for each of them, I know most of concepts explained in those books are not necessary for designing and developing a complete well formed project. In summary I want a cook book (or resource) that explains new concepts in programming (especially design and architecture patterns and frameworks). This resource would better cover: 1- Asp.net MVC 2- SOA and DDD aggregation and their patterns (if better architecture doesn't exist) 3- Common design patterns that best match number 2 (Like IOC) 4- Best known frameworks for modern programming (I know they are a lot and it's up to designer to choose from them but it's better to use one in each category, like Windsor for IOC) 5- Linq and ORM 6- any other thing that might be useful I want it to teach me a complete project. A project that uses most of new concepts in designing and developing .Net applications.
Static Factory Class in C#
i want to create an object from my apiReader Class using an static inner class.
What did i do wrong?
I use the Factory Design-pattern. (Gang Of Four)
Hope you can help me.
class apiReader
{
public enum debug{
Debug, NONdebug};
private const string api = "Look i'm allive!";
private string usrID;
private string usrCH;
private apiReader();
public static class apiReaderBuilder
{
private apiReader apicCLC;
apiReaderBuilder()
{
//QR SCANNER
apicCLC = new apiReader();
}
[Obsolete("Only for Debug")]
apiReaderBuilder(debug debe)
{
apicCLC = new apiReader();
apicCLC.usrID = "SomeUserID";
apicCLC.usrCH = "SomeUserChannel";
}
apiReaderBuilder(string usrCode, string Channel)
{
apicCLC = new apiReader();
apicCLC.usrID = usrCode;
apicCLC.usrCH = chor;
}
}
}
State Pattern share common knowdledge between state object efficient and extandable implementation
I am using the State Pattern, but the examples I found are for educational purpose and I wanted to know what are best practices in this pattern for sharing objects between states, i.e. a boolean, a List and also for one state object to change the state reference in the automata object.
I will lay down a simple model to be used as an example.
public abstract class State {
Automata automata;
public State( Automata automata){
this.automata = automata;
}
public abstract void action();
}
public class State1 extends State {
public State1(Automata automata){
super(automata)
}
@Override
public void action() {
// GET : Use obj1
// POST :Set in automata state to State2
}
}
public class State2 extends State {
public State2(Automata automata){
super(automata)
}
@Override
public void action() {
// GET :Use obj1
// POST :Set in automata state to State1
}
}
public class Automata {
private State state1 = new State1(this);
private State state2 = new State2(this);
private State state = state1;
public void takeAction() {
state.action()
}
}
I have tried the following solutions:
- For GET store
obj1
in Automata and use getters and setters. For POST store states in Automata and use getters and setters. This approach will make the code unnecessarily long by using the getters and becomes hard to maintain with a changing list ofobj1
's and states. - Use private inner classes. Declare
State, State1
andState2
as private inner classes and access directlyobj1
and states. Hard to maintain and update simply because of length of file. Can not be shared with anotherAutomata
class. - Make fields public. I do not want to expose all of this fields.
- Use a singleton/static class approach for sharing
obj1
's
I am not very found of package private access.
In my design I am combining this pattern with the Template Method Pattern as a side information.
I know a one-fits-all approach does not exist, but what are common best practices in working with this pattern?
lundi 25 janvier 2016
POCOs, DTOs, DI in an N-Layered ASP.NET MVC Application
Did I just throw a bunch of concepts and technologies that I want to learn about ?
-
First Problem (Writing maintainable code)
No, I need DI to follow best practice as the applications I'm building are starting to get complicated and I need to write more organized and maintainable code.
-
Second Problem (My POCOs are heavy)
My application has large & complex entities and when I read about DTOs they seemed like a good practice instead of using POCOs all over the place
You can help me by proposing a project structure keeping in mind the below points from my long research:
- I found out that I can implement MVVM but the articles about this topic is really limited without including WCF and other components that will distract me while I'm just getting started.
- I'm not sure if I got this right or wrong but POCOs are meant to be used by the Bussiness Layer only ? For communication betwen DL and Views I should use DTOs.
-
I should have a separate layer (mapper) to populate DTOs and POCOs but I also found that AutoMappers can complicate things, while my DTOs are quite simple and I shall ask if there's any best practices about where should I place this code in my projects ?
-
Based on these points do I need a ViewModel ? or DTOs ? or both ?
- If you can add some code to your answer along with a simple example to how the cycle will work that would be very nice.
I know some of these points or maybe all are addressed in lots of places including stackoverflow community but I couldn't really find an article or a question that addresses my exact problems and lots of articles are actually providing wrong information so I hope I can get some good advice here. Thanks!
Edit 1
To the people who will down vote this. You either have the option to do so feel free you are following the rules. or you can actually help someone who's done his research and asking a legitimate question that people write articles and books about it. I don't need a whole book just a proposed structure that you use and find it good. It's that simple! I really need some help here!
Which designer patterns used to create complex objects?
How I can simplify creating this objects? I try use Design Patterns Composite and Builder but I'm but I'm confused.
public class tcLoteRps
{
public string Id { get; set; }
public List<tcRps> Rps { get; set; }
}
public class tcRps
{
public tcInfRps InfRps { get; set; }
public string Signature { get; set; }
}
public class tcInfRps
{
public tcIdentificacaoRps IdentificacaoRps { get; set; }
public string Id { get; set; }
public tcDadosServico Servico { get; set; }
}
public class tcIdentificacaoRps
{
public string Id { get; set; }
}
public class tcDadosServico
{
public string Id { get; set; }
}
Positional Anchor System
So just for fun I try to implement an anchor system for positionable objects, being the basis for a drag and drop UI system.
As such an object has a relative position (x,y)
to a parent, if that parent exists. Else the given position is absolute.
When coming down to describing an area with (x,y,w,h)
and having it's 5 + relevant anchors (corners + center and maybe center of edge anchors) I already get a load of problems:
If I want to reposition the object, I need to change all anchors. I can of course make the position of all anchors relative to another anchor that represents the position of the area, but if I move a single anchor I also want to move the object itself. Features like "snapping anchors together" and the like come to mind. But the interaction between all these objects starts to get really complicated really quickly. Connecting each anchor with the right others and not having messages being sent between each other on every occasion or getting into loops within the system seems like a daunting task.
Since looking for information about imlementing such an anchor system seems really tedious since I get 100% HTML Anchor questions in search results, I am asking: How do I start my journey into this nightmare? Are there well working patterns that I am already missing?
Is this nested namespace inheritance pattern well implemented?
I´m trying to implement some nested namespaces with objects, and objects that inherit from those objects. I want to know if this first approach is well implemented:
// Namespaces
var firstDomain = {};
firstDomain.firstSubDomain = {};
firstDomain.firstSubDomain.secondSubDomain = {}
/*
* Base Object
*/
firstDomain.firstSubDomain.secondSubDomain.baseObject = (function(baseObject) {
baseObject.init = function() {};
return {
init: baseObject.init
}
})(firstDomain.firstSubDomain.secondSubDomain.baseObject || (firstDomain.firstSubDomain.secondSubDomain.baseObject = {}));
/*
* Extended Object
*/
firstDomain.firstSubDomain.secondSubDomain.extendedObject = (function(extendedObject) {
extendedObject.init = function() {};
extendedObject.init.prototype = Object.create(firstDomain.firstSubDomain.secondSubDomain.baseObject.init.prototype);
extendedObject.init.prototype.extraFunction = function() {};
return {
init: extendedObject.init
}
})(firstDomain.firstSubDomain.secondSubDomain.extendedObject || (firstDomain.firstSubDomain.secondSubDomain.extendedObject = {}))
// Objects instances
// Base object instance
var baseObject = new firstDomain.firstSubDomain.secondSubDomain.baseObject.init();
// Extended object instance and executing particular method
var extendedObject = new firstDomain.firstSubDomain.secondSubDomain.extendedObject.init();
extendedObject.extraFunction();
console.log(firstDomain);
Here is the repo link:
Can we clear the confusion about MVC in php?
I'm here again. Still studying MVC.
Well there's a tone of contradictions around the web. I would like to clear all those things. But i can't because i'm still a noob in that. So to avoid learning wrong things i would like to ask you about this point.
THE MODEL VIEW CONFUSION (AKA MVC)
Jokes apart, this title reflects the web confusion about the MVC pattern ''implemented'' in PHP.
There are articles who says that the MODEL and the VIEW will NEVER interact directly. Instead the CONTROLLER takes place and handle the situation.
It ask the model to do something and return something, then it ask to the view to present the data that the model returned. All fine, right?
NOPE
I've landed here, where it says the complete opposite.
For example, this article on sitepoint which states:
"It is important to note that in order to correctly apply the MVC architecture, there must be no interaction between models and views: all the logic is handled by controllers."
This is wrong. It specifies this nowhere in MVC. In fact, it states the exact opposite. This article is a good example because it epitomises the attitude of most PHP developers and what's taught as "MVC" throughout the PHP community.
So, who is right then? Can the view acess directly to the model or not?
Is there a good solution to a composite pattern, where a root element is needed, but no element can be root?
I have a structure where, executing Update(); on the root element will recursively traverse the structure and execute Update(); on all child nodes.
This works just like I want it to, however, no element seem to qualify as being the root element. It looks like this
This is what I ended up doing. I created a class called GameHandlerRoot, which does nothing, except act like a root. Call Update(); on this, and everything updates. Is this viable? There must be better solutions than a fake.
To be specific, even if you could find an element that would qualify as a root, I am only interested in a solution, where no such element exists.
Thank you in advance.
Regex pattern issue c#
I have a little trouble here. I am trying to find a Regex which will match all fallowing examples:
-
Method( "Team Details" )
Should return: Team Details
-
Method( @"Team details item
and more
and More" )
Should return: Team Details item and more and more
-
Method( "Team \"Details\"" )
Should return: Team "Details"
-
Method( @"Team ""Details""" )
Should return: Team "Details"
-
Method( @"Team
""Details""" )
Should return: Team
"Details"
I managed to create a regex pattern:
Method\(.*\"(.*)\".*\)
whcih is working in the first example and partially second one, but I found it very difficult to create one pattern for all 5 examples. Any help ?
Cheers