I am using backbone.js for a web app.
I have different component views which are derived from few base classes.
Each of the view has few static methods for initializing and creating instances.
For example:
class Base extends Backbone.View
#create:(config)->
*do some processing based on config*
*generate view parameters*
viewparams = ....
return new #(viewparams)
class Derived extends Base
**some customizations and functions**
**at some point some where**
instanceDerived = Derived.create(*some params*)
The advantage of this method is that, it becomes natural to re-use the create method. The "#" or "this" refers to the Derived class (constructor) and hence the object can be created easily.
The code works well when both the classes are in same module. However, when the objects are in different modules, the "#" or "this" inside create function refers to "Base.create" instead of the Derived class constructor.
I dont know if I am doing some unconventional coding here. Can some one please advice of how to resolve/structure this problem?
Related
Edit: So far it looks like the answer to my question is, "You can't do that in Swift." I currently have a solution whereby the subclass names are listed in an array and I loop around and instantiate them to trigger the process I'm describing below. If this is the best that can be done, I'll switch it to a plist so that least it's externally defined. Another option would be to scan a directory and load all files found, then I would just need to make sure the compiler output for certain classes is put into that directory...
I'm looking for a way to do something that I've done in C++ a few times. Essentially, I want to build a series of concrete classes that implement a particular protocol, and I want to those classes to automatically register themselves such that I can obtain a list of all such classes. It's a classic Prototype pattern (see GoF book) with a twist.
Here's my approach in C++; perhaps you can give me some ideas for how to do this in Swift 4? (This code is grossly simplified, but it should demonstrate the technique.)
class Base {
private:
static set<Base*> allClasses;
Base(Base &); // never defined
protected:
Base() {
allClasses.put(this);
}
public:
static set<Base*> getAllClasses();
virtual Base* clone() = 0;
};
As you can see, every time a subclass is instantiated, a pointer to the object will be added to the static Base::allClasses by the base class constructor.
This means every class inherited from Base can follow a simple pattern and it will be registered in Base::allClasses. My application can then retrieve the list of registered objects and manipulate them as required (clone new ones, call getter/setter methods, etc).
class Derived: public Base {
private:
static Derived global; // force default constructor call
Derived() {
// initialize the properties...
}
Derived(Derived &d) {
// whatever is needed for cloning...
}
public:
virtual Derived* clone() {
return new Derived(this);
}
};
My main application can retrieve the list of objects and use it to create new objects of classes that it knows nothing about. The base class could have a getName() method that the application uses to populate a menu; now the menu automatically updates when new subclasses are created with no code changes anywhere else in the application. This is a very powerful pattern in terms of producing extensible, loosely coupled code...
I want to do something similar in Swift. However, it looks like Swift is similar to Java, in that it has some kind of runtime loader and the subclasses in this scheme (such as Derived) are not loaded because they're never referenced. And if they're not loaded, then the global variable never triggers the constructor call and the object isn't registered with the base class. Breakpoints in the subclass constructor shows that it's not being invoked.
Is there a way to do the above? My goal is to be able to add a new subclass and have the application automatically pick up the fact that the class exists without me having to edit a plist file or doing anything other than writing the code and building the app.
Thanks for reading this far — I'm sure this is a bit of a tricky question to comprehend (I've had difficulty in the past explaining it!).
I'm answering my own question; maybe it'll help someone else.
My goal is to auto initialize subclasses such that they can register with a central authority and allow the application to retrieve a list of all such classes. As I put in my edited question, above, there doesn't appear to be a way to do this in Swift. I have confirmed this now.
I've tried a bunch of different techniques and nothing seems to work. My goal was to be able to add a .swift file with a class in it and rebuild, and have everything automagically know about the new class. I will be doing this a little differently, though.
I now plan to put all subclasses that need to be initialized this way into a particular directory in my application bundle, then my AppDelegate (or similar class) will be responsible for invoking a method that scans the directory using the filenames as the class names, and instantiating each one, thus building the list of "registered" subclasses.
When I have this working, I'll come back and post the code here (or in a GitHub project and link to it).
Same boat. So far the solution I've found is to list classes manually, but not as an array of strings (which is error-prone). An a array of classes such as this does the job:
class AClass {
class var subclasses: [AClass.Type] {
return [BClass.self, CClass.self, DClass.self]
}
}
As a bonus, this approach allows me to handle trees of classes, simply by overriding subclasses in each subclass.
This is a bit of a generic software design question. Suppose you have a base class and lots of classes that derive from it (around 10).
There is some common functionality that is being shared between some of the classes (3-4 of derived classes need it). Basically a field for a UI control, an abstract method to create a UI control and the common code that uses the abstract method to recycle the UI piece (8-9 lines of code) using the abstract method. Something like this:
class BaseClass {
...
protected UIControl control;
protected abstract UIControl CreateUI();
protected void RecycleUI() {
if (/* some condition is met */) {
if (this.control != null) {
control.Dispose();
}
this.control = this.CreateUI();
this.AddToUITree(control);
}
}
...
}
Do you think it is OK to put this to base class instead of replicating the code in derived classes.
Drawback is that this piece of code is only used for some of the base classes and completely irrelevant for the other classes.
One alternative is to create an intermediate class that derives from BaseClass and use it as the base to the ones that need the functionality. I felt like creating a derived class for a couple line of code for a very specific purpose felt heavy. It doesn't feel like it is worth interrupting the inheritance tree for this. We try to keep the hierarchy as simple as possible so that it is easy to follow and understand the inheritance tree. Maybe if this was C++ where multiple inheritance is an option, it wouldn't be a big issue but multiple inheritance is not available.
Another option is to create a utility method and an interface to create/update the UI control:
interface UIContainer {
UIControl CreateUIControl();
UIControl GetUIControl();
void SetUIControl(UIControl control);
}
class UIControlUtil {
public void RecycleUI(UIContainer container) {
if (/* some condition is met */) {
if (container.GetUIControl() != null) {
container.GetUIControl().Dispose();
}
UIControl control = container.CreateUI();
container.SetUIControl(control);
container.AddToUITree(control);
}
}
}
I don't like this option because it bleeds UI logic externally which is less secure as its UI state can be manipulated externally. Also derived classes have to implement getter/setter now. One advantage is that there is another class outside of the aforementioned inheritance tree and it needs this functionality and it can use this utility function as well.
Do you have any other suggestions? Should I just suppress the urges that brew inside me to have common code not repeated?
One alternative is to create an intermediate class that derives from
BaseClass and use it as the base to the ones that need the
functionality.
Well, this is what I thought is the most appropriate. But it depends. The main question here is the following: are objects, that require UI recycling and really different from those, that do not? If they are really different, you have to create a new base class for them. If difference is really negligible, I think it's ok to leave things in a base class.
Do not forget about LSP.
We try to keep the hierarchy as simple as possible so that it is easy
to follow and understand the inheritance tree
I think more important here is to keep things not only simple, but also close to your real world things so that modeling new entities would be easy. Seeming easiness now may cause real troubles in the future.
How do I extend /include/SearchForm/SearchForm2.php in upgrade safe manner?
You could create /custom/include/SeachForm/CustomSearchForm2.php which extends SearchForm2 (the class name for SearchForm2) traditionally (e.g. CustomSearchForm2 extends SearchForm). The harder task is accessing your custom class at that point.
SearchForm is instantiated from include/MVC/View/views/view.list.php - in a couple of possible places: the protected method getSearchForm2() and [assumed] public method prepareSearchForm().
So how do you extend view.list.php? That one's easier. For any module you'd like a custom list view, create a file at /custom/modules/MyModule/views/view.list.php and define it as CustomMyModuleViewList extends ViewList. Some modules already have their own ViewList (e.g. Accounts, Calls) so for those you'd want to extend their original extended ViewList, e.g. CustomAccountsViewList extends AccountsViewList.
So create your custom ViewList extension, copy-paste the methods you need to alter (prepareSearchForm and getSearchForm2) and adjust as needed to load in your custom SearchForm class.
Assuming the question relates to SugarCRM 6.5.x (and potentially earlier 6.x versions - I haven't checked), Matthew Poer's answer is exactly right except for one thing: the class to extend is called SearchForm instead of SearchForm2. To do this:
Copy include/SearchForm/SearchForm2.php to custom/include/SearchForm/SearchForm2.php
Edit custom/include/SearchForm/SearchForm2.php and edit the class declaration, changing it to:
require_once('include/SearchForm/SearchForm2.php');
class CustomSearchForm extends SearchForm {
Copy include/MVC/View/views/view.list.php to custom/include/MVC/View/views/view.list.php
Edit custom/include/MVC/View/views/view.list.php and edit the class declaration, changing it to:
require_once('include/MVC/View/views/view.list.php');
class CustomViewList extends ViewList {
In the function prepareSearchForm in the CustomViewList class, change the line
require_once('include/SearchForm/SearchForm2.php');
to
require_once('custom/include/SearchForm/SearchForm2.php');
and the line
$searchMetaData = SearchForm::retrieveSearchDefs($this->module);
to
$searchMetaData = CustomSearchForm::retrieveSearchDefs($this->module);
In the function getSearchForm2 in the CustomViewList class, change the line
return new SearchForm($seed, $module, $action);
to
return new CustomSearchForm($seed, $module, $action);
The other functions of CustomSeachForm and CustomViewList can be subsequently overriden as needed. If you have module-specific view.list.php files, you will, of course, need to change them to extend CustomViewList instead of ViewList.
I am very new to GWT.
I am using ext-gwt widgets.
I found many places in my office code containing like,
class A extends BaseModel{
private UserAccountDetailsDto userAccountDetailsDto = null;
//SETTER & GETTER IN BASEMODEL WAY
}
Also, the DTO reference is unused.
public class UserAccountDetailsDto implements Serializable{
private Long userId=null;
private String userName=null;
private String userAccount=null;
private String userPermissions=null;
//NORMAL SETTER & GETTER
}
Now, I am able to get the result from GWT Server side Code and things Work fine, but when I comment the DTO reference inside the class A, I am not getting any Result.
Please explain me the need of that.
Thanks
Well the problem is in implementation of GXT BaseModel and GWT-RPC serialization.
BaseModel is based around special GXT map, RpcMap. This map has defined special serialization rules, which let's avoid RPC type explosion, but as side effect, only some simple types stored in map will be serialized. E.g. you can put any type inside the map, but if you serialize/deserialize it, only values of type Integer, String ,Double,Byte, Float and Short (and arrays of this types) will be present. So the meaning behind putting reference to the DTO inside BaseModel, is to tell GWT-RPC that this type is also have to be serialized.
Detailed explanation
Basically GWT-RPC works like this:
When you define an interface for service, GWT-RPC analyzes all the classes used in parameters/ return type, to create serializers/deserializers. If you return something like Map<Object,Object> from your service, GWT-RPC will have to create a serializer for each class which implements Map and Serializable interfaces, but also it will generate serializers for each class which implements Serializable. In the end it is quite a bad situation, because the size of your compiled js file will be much biggger. This situation is called GWT-RPC type explosion.
So, in the BaseModel, all values are stored in RpcMap. And RpcMap has custom written serializer (RpcMap_CustomFieldSerializer you can see it's code if you interested how to create such things), so it doesn't cause the problem described above. But since it has custom serializer GWT dosn't know which custom class have been put inside RpcMap, and it doesn't generate serializers for them. So when you put some field into your BaseModel class, gwt knows that it might need to be able to serialize this class, so it will generate all the required stuff for this class.
Porting GXT2 Application code using BaseModel to GXT3 Model is uphill task. It would be more or less completely rewrite on model side with ModelProviders from GXT3 providing some flexibility. Any code that relies on Model's events, store, record etc are in for a rewrite.
I never did proper class design, so bear with me.
Let's say we have a Project class. Then let's say we have a ProjectGroup class that has the same members as the Project class, plus a list of Projects.
Should ProjectGroup be the superclass of Project or is ProjectGroup a specialization of Project and the former should be a subclass of the latter?
I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:
If your two classes are actually implying they should be related by inheritance then ProjectGroup should inherit from Project class. This is how it would look like in C#:
public class ProjectGroup: Project ...
If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:
public interface ICommonState ...
public class Project: ICommonState ...
public class ProjectGroup: ICommonState
{
IEnumerable<ICommonState> projects
...
}
Edit
If your classes are actually Project and ProjectGroup and they both have properties like ID and Name in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.
They could both either
implement an ICommonEntity interface - use it when they have the same state+functionality but functionality behaves differently in each of them
inherit from CommonEntity class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophy
So your component may be an interface or a class (when using composite pattern).
Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User and Person classes. They can be inherited either way. Depending on the business scenario.
class User: Person
This would be the case where you have an application with contacts. Some of them are also users of this very same application.
class Person: User
This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person.
It sounds like you might want the Composite pattern. Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.
if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.