Best Practices recommend setting the new method as protected and using instead static new... methods to mitigate the lack of method overloading.
So I use this pattern as explained here
But static methods are not inherited.
So we have to define for each sub class the static construct and the static new... methods.
Therefore we lose some of inheritance's benefits.
I had a look on system classes hoping to find a better solution but what I saw did not really help me :
- some respect the static new pattern and declare the methods in the sub classes
- some just use the instance new without protecting it
- some use the mother class as a "class factory", like SalesFormLetter
static SalesFormLetter construct(DocumentStatus document,
boolean getParmId = true)
{
switch(document)
{
case DocumentStatus::Confirmation : return new SalesFormLetter_Confirm (getParmId);
case DocumentStatus::PickingList : return SalesFormLetter_PickingList::construct(getParmId);
case DocumentStatus::PackingSlip : return new SalesFormLetter_PackingSlip (getParmId);
case DocumentStatus::ProjectPackingSlip : return new SalesFormLetter_PackingSlipProject(getParmId);
case DocumentStatus::Invoice : return new SalesFormLetter_Invoice (getParmId);
case DocumentStatus::ProjectInvoice : return new SalesFormLetter_InvoiceProject (getParmId);
default : throw error(strfmt("#SYS19306",funcname()));
}
throw error(strfmt("#SYS19306",funcname()));
}
So I am wondering if there is a better solution, and if not what would be the best among these ?
A better solution to object construction?
Well, the new have to go somewhere, and putting a lot of new in the client code is fragile and inflexible. So go with the class "factories" especially for related classes.
Two options:
Make new protected. Make a construct for each sub-class, put the factory construct in the base class calling the sub-class constructors. But anyone can then call the sub-class construct method.
Make new public. Don't make a construct for each sub-class, put factory the construct in the base class, new'ing the sub-classes. The new can't be protected as the base class does not descend from the sub-class.
Whether or not you go with 1 or 2 is your choice, you end up with exposing the sub-class constructor. Personally I prefer option 2, as it is the least hassle.
Advice: make your object dependencies explicit using arguments to new. This will complicate your factories, but that is okay as it moves the complexity from your client code. Setter methods (parm methods) is evil, but is needed for RunBase because the it is required by the batch system.
Also go see what Uncle Bob writes.
Related
I've got a class called ArtificialIntelligenceBase from which you can create your own artificial intelligence configuration sending some variables to the constructor or you can make a class that inherits from ArtificialIntelligenceBase and in the constructor of this new class just call the function super() with the parameters of the configurations.
I've also created some examples of artificial intelligences in classes, AIPassive, AIAgressive and AIDefensive. Obviously all of them inherits from ArtificialIntelligenceBase.
The point is that there're only few public functions in the base class. The variables in the base class are read only and the non public functions are protected in case you need to apply some modifications on them when created another pre-defined AI.
You can also create another AI just calling the base class sending some parameters in the constructor like this: new ArtificialIntelligenceBase(param1, param2, param3, param4);
I've tought about make the classes as a singleton because the classes can never change and once setted, their variables never change.
The question is: Is the singleton the best pattern to do this? Because I'm not sure.
PD: You don't need to explain any patter, just mention the name and I'll search for how it works
PPD: I'm developing in AS3. Just in case it helps
Thanks
In general, singletons are evil. I don't see any reason in your case to use a singleton, either. It sounds like you're using your own version of a factory method pattern (using a constructor somehow?) or maybe a prototype (I don't know AS3 one bit), but if you're looking for other patterns a couple of other ones are abstract factory and builder.
You don't need to use the singleton pattern to limit yourself to using only one instance per type of class, though. It doesn't help avoid redundancy.
Ok, ObjectUtil.copy is a good technique for copying Objects. But after having a lot of problems using it to copy other classes, I guess it is not the solution I'm after.
How would you approach the copying/cloning of instances of a class that you've defined? Maybe defining a function withing the class to copy it?
It is cool that most variables are passed by reference in flex, but sometimes is annoying not having control over this (sorry, I'm too used to plain C).
Thanks!
UPDATE:
To be more precise, as I can't make the ObjectUtil.copy() work with a custom class is... is there a way to copy, by using serialization, a custom class? Did you use successfully a ByteArray copy with a custom class?
Thanks for all the replies.
If you determine that implementing a clone interface is not the correct approach in your situation, I suggest looking at the ByteArray object. I haven't used it myself, but it appears to give you all the control you should need over individual bytes. You can reading and writing from and to any object.
Senocular does a quick overview of it here.
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
Good luck!
ObjectUtil.copy uses ByteArray internally to create a copy. In order for the copy to be successful, ByteArray requires that the flash player will be aware of you custom class. You do that by registering your class using the global registerClassAlias method.
For example:
//one time globally to the application.
registerClassAlias(getQualifiedClassName(CustomClass), CustomClass);
//then
var c1:CustomClass = new CustomClass();
c1.name = "customClass";
var c2:CustomClass = ObjectUtil.copy(c1);
trace(ObjectUtil.toString(c1))
trace(ObjectUtil.toString(c2))
If you have control over the whole class hierarchy, I recommend implementing a clone() interface in every class. It's tedious, but will pay off as complexity increases.
(Forgive me if the syntax is a bit off, it's been a while)
// define a "cloneable" interface
public interface ICloneable {
function clone() : Object;
}
For every class, implement the method...
public class MyClass1 implements ICloneable {
...
public function clone() : Object {
var copy:MyClass1 = new MyClass1();
// copy member variables... if it is a user-defined object,
// make sure you call its clone() function as well.
return copy;
}
}
To create a copy of the object, simply invoke the clone() function.
var copy:MyClass1 = original.clone();
As a side note, both Java and .NET seem to have adopted the clone methods on their base Object classes. I know of no analogous method for ActionScript's Object class.
Two common idioms:
a clone method
a copy constructor
Both of these let you define what exactly making a copy means--you may want some things copied shallowly and others deeply.
I'm working on a site and there are two projects in the solution a business logic project and the website project. I understand that I want to keep the entity context out of the web project and only use the business objects the framework creates but I can't figure out how to save a modified object this way.
Let's say my entity model created this class:
public class Person //Person entity
{
Int32 Id {get;set;}
String Name {get;set;}
Address Address {get;set;} //Address entity
}
And I created this class to get a specific person:
public static class PersonController
{
public static Person GetById(int id)
{
using (Entities context = new Entities())
{
return context.Persons.FirstOrDefault(x => x.Id == id);
}
}
}
This allows me to get a person without a context by calling PersonController.GetById(1); and I can change the persons properties after I get them but I can't figure out how to save the modified information back to the database. Ideally I would like to partial class Person and add a .Save() method which would handle creating a context adding the person to it and saving the changes. But when I tried this a while ago there were all kinds of issues with it still being attached to the old context and even if I detatch it and attatch it to a new context it gets attached as EntityState.Unchanged, if I remember right, so when I call context.SaveChages() after attaching it nothing actually gets updated.
I guess I have two questions:
1) Am I going about this in a good way/is there a better way? If I'm doing this in a really terrible way I would appreciate some psudo-code to point me in the right direction; a link to a post explaining how to go about this type of thing would work just as well.
2) Can someone provide some psudo-code for a save method? The save method would also need to handle if an address was attached or removed.
There are many ways to handle Entity Framework as a persistence layer.
For one, it looks like you're not using pure POCOs. That is, you let EF generate the classes for your (in the EDMX.designer.cs file).
Nothing wrong with that, but it does inhibit a clean separation of concerns (especially when it comes to unit testing).
Have you considering implementing the Repository pattern to encapsulate your EF logic? This would be a good way to isolate the logic from your UI.
In terms of Save - this is where it gets difficult. You're right, most people use partial classes. Generally, you would have a base class which exposes a virtual "Save" method, which the partial classes can then override.
I personally don't like this pattern - i believe POCOs should not care about persistence, or the underlying infrastructure. Therefore I like to use pure POCOs (no code gen), Repository pattern and Unit of Work.
The Unit of Work handles the context opening/saving/closing for you.
This is how (my) Unit of Work does the magic. Consider this some code in your "Web" project:
var uOw = new UnitOfWork(); // this is class i created, implementing the UOW pattern
var person = repository.Find(10); // find's a "Person" entity (pure POCO), with id 10.
person.Name = "Scott";
uOw.Commit();
Or adding a new Person:
var uOw = new UnitOfWork();
var newPerson = new Person { Name = "Bob" };
repository.Add(newPerson);
uOw.Commit();
How nice is that? :)
Line 1 creates a new sql context for you.
Line 2 uses that same context to retrieve a single "Person" object, which is a hand-coded POCO (not generated by EF).
Line 3 changes the name of the Person (pure POCO setter).
Line 4 Saves the changes to the data context, and closes the context.
Now, there is a LOT more to these patterns than that, so I suggest you read up on these patterns to see if it suits you.
My repository is also implemented with Generics, so I can re-use this interface for all business entity persistence.
Also take a look at some of the other questions I have asked on Stack Overflow - and you can see how I've implemented these patterns.
Not sure if this is the "answer" you're looking for, but thought I'd give you some alternative options.
This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language. It should be [mostly] obvious how to apply it in different languages.
If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.
This is easy enough. But I don't understand why you have the capacity to cast an interfaced instance back to its original base class. Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)
Here's a sample interface:
public interface IFooable extends IUIComponent {
function runFoo():void;
}
Let's say I create a base class, which extends VBox and implements the interface:
public class Foo extends VBox implements IFooable {
public Foo() {
super();
//stuff here to create Foo..blah blah
}
public function runFoo():void {
// do something to run foo
}
}
Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented. It is a common piece of functionality all of my classes should have, regardless of how they implement it. Thus, my parent class (an Application) will instantiate Foo via its interface:
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100; //works because of IUIComponent
}
But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100;
addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type
//could also do this:
//addChild(foo as VBox);
}
Wasn't the original intention to hide the implementation of Foo? There is still an assumption that Foo is a DisplayObject. Unfortunately, being able to add the custom object to a container seems impossible without casting.
Am I missing something entirely? Is this really just a phenomenon in Flex/AS3? If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?
For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).
2nd Thought:
Abstract Classes:
As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface. Thus, any class which extends the abstract class would then be required to implement the methods therein.
Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).
So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor. Unfortunately, this is run-time checking as opposed to compile-time enforcement.
It's still a solution, though.
Context:
Some context might help:
I have an application which can have any number of sub-containers. Each of these sub-containers will have their own respective configuration options, parameters, etc. The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options. Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu. This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.
Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar. But when I add them to the application, they need to be the base class.
#James Ward, That's definitely something I wish was in the language, probably a interface IDisplayObject. That would solve a lot of issues in OOP display programing in AS3.
In regards the the original question, something I've used in the past, and have seen mentioned on www.as3dp.com is to include a getDisplay():DisplayObject method in the interface, which would typically return "this" by its implementor. It's less than ideal, but works.
#Matthew Flaschen, While we don't have Abstarct Classes native to AS3, common practice is to name the class with the word Abstract ie: AbstarctMyObject, and then just treat it like the abstarct objects in Java and other languages. Our want for true abstarct classes is something the Flash player team is well aware of, and we'll likly see it in the next version of the ActionScript language.
Okay, I'm anaswering generally, because you said, "Is this really just a phenomenon in Flex/AS3?".
In your init method, obviously you're always calling addChild with foo. That means foo must always be an instance of DisplayObject. You also want it to be an instance of IFooable (though it's not clear here why). Since DisplayObject is a class, you would consider using a subclass of DisplayObject (e.g. FooableDisplayObject), that implemented IFooable. In Java, this would the below. I'm not familiar with AS, but I think this shows there's not any general flaw in interfaces here.
interface IFooable
{
public void runFoo();
}
class DisplayObject
{
}
abstract class FooableDisplayObject extends DisplayObject implements IFooable
{
}
class Foo extends FooableDisplayObject
{
public void runFoo()
{
}
}
public void init()
{
FooableDisplayObject foo = new Foo();
foo.percentHeight = 100;
addChild(foo);
}
I think this is a place where Flex's/Flash's API is not correct. I think that addChild should take an interface not a class. However since that is not the case you have to cast it. Another option would be to monkey patch UIComponent so that it takes an interface or maybe add another method like addIChild(IUIComponent). But that's messy. So I recommend you file a bug.
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.
Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.
Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.
Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.
public class Page extends Sprite{...}
public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
public class Homepage extends Page implements IPageLoader
{ function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }
var currentpage:Page;
var currentpageLoader:IPageLoader;
currentpage = new Homepage;
currentpageLoader = currentpage as IPageLoader;
currentpageLoader.loadPage();
currentpageLoader.initPage();
addChild(currentpage);
Tween(currentpage, x, CENTER);
Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.