Class design 'dilemma' - class-design

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.

Related

Any way to trigger creation of a list of all classes in a hierarchy in Swift 4?

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.

Autofac Repository Pattern and Unit Of Work

I have searched a little bit and I am confused.
First Approach uses a repository and a service for each entity with Autofac. Unit of work class does not have repositories. Therefore, you should create each repository instead of just creating one unit of work class in caller constructor.
OrderService(IUnitOfWork unitOfWork, IUserRepository userRepository,IOrderRepository orderRepository,IBalanceRepository balanceRepository)
Second Approach uses just a generic repository. It uses extension classes instead of using one repository for each entity. Unit of work class has generic repositories.Therefore, you can just create a unit of work class on caller class constructor.
OrderService(IUnitOfWork unitOfWork)
In this approach we use one generic class for repositories but we create a repository object for each entity. If this approach is fine how can I implement it with Autofac ?
Third Approach uses one generic repository and one object for generic repository with Autofac. It uses generic methods instead of generic class. But generic repository has unit of work class instead of opposite. Is this anti pattern ?
OrderService(IUnitOfWork unitOfWork,IGenericRepository repository)
Which approach should I use ?
The sense of the unit of work and the repository pattern is to describe exactly what is needed for example for a use case. So the unit of work which has repositories for every entity or can create a repository for any entity by a generic method is as much to avoid, as a repository that returns an IQueryable. The last flaw will move your Dal to your domain model or even UI (imagine where the filter logic is written and exactly when the filter is executed and where any exceptions will be thrown), the first creates a kind of monolytic application and makes it hard to write unit tests. A unit of work (interface) that only has the 3 Repositories your use case needs and the three repository (interfaces) that have only the methods needed, returning either a single object or a list of objects is more easy to mock and test and specifies exactly what the use case needs and communicates it to your fellow developers (or yourself in 2 years). The interfaces could be implemented (if you choose to) by one big unit of work class and perhaps a few standard repository classes, but thats a different decision that should be guided by the technology (EF code first in earlier versions was not able to have multiple contexts in one database) and the complexity of your application.
i use the 2nd,IUnitOfWork is only an interface,the behind i use ef.
public interface IUnitOfWork:IDisposable
{
IRepository<T> GetRepository<T>() where T:class;
int SaveChanges();
}
and create dbcontext class
public class DataContext:DbContext,IUnitOfWork
implement the GetRepository method,you should add a adapter class,from dbset to irepository
public IRepository<T> GetRepository<T>() where T:class
{
return new RepositoryEfAdapter<T>(Set<T>(), this);
}
this is a sample,you can register datacontext as iunitofwork

Can Not Set Protected Members on Zend View

I had convenience methods littered all over the place. I have now pushed these in to a couple of helper classes and I made the helper classes protected members of my layer supertypes.
Everything was going along swimmingly until I came to Zend View. I have extended Zend View to make my layer supertype but when I try to attach a protected member it throws a:
Zend View Exception: Setting private or protected class members is not
allowed.
Firstly, why would such members not be allowed? Any ideas? Secondly, have you circumvented it in the past? And how did that go? (It seems that the framework detects protected members by the presence of a leading underscore. This seems a bit hit-and-miss, and also easy to get around).
Note - I'm not saying that I would circumvent it. I'm just trying to find out what others have done in the past (since it seems an odd constraint).
It's an important point for me since I am using traits to bring the helpers and associated proxy methods into each superclass. I don't want to maintain a separate trait just for the View. Alternatively, I don't want to make the helpers public members of each superclass.
Thank you!
Data encapsulation.
Underscore properties are not allowed primarily so that the developer can't accidentally overwrite View properties that are part of the framework.
This essentially protects all of the framework's View properties and allows you, the developer, free rain over any public properties you wish to set.
The authors of Zend View can then be sure of two things: (1) they control (and author) the private and protected class properties and (2) you control the public properties. This makes for logical data encapsulation and maintainable class overloading.

Base Classes "Entity" and "ValueObject" in Domain-Driven Design

Do you always create these two abstract base classes as the basis of any new project in DDD?
I've read that Entity should have two things. First, an identity property, probably of a generic type. Second, an Equals() method that determines whether it's the same as another Entity. Anything else? Any other natural methods or rules of thumb?
I like to have a common abstract ancestor for all my Domain objects but that is a matter of preference and overall infrastructure requirements.
After that, yes I have abstract classes for Entity and Value objects.
Don't forget that also overriding Equals for Value objects to return equality based on equal property state can be important.
Also people frequently overlook the value of packages. Put all these core base classes in their own "kernel" library and don't be reluctant to split your domain model into multiple assemblies instead of winding up with a single large "Domain Library".
If you're using .NET/C#, I've published a set of DDD interfaces and classes for public use. Take a look to see what typically goes inside them. The embedded code comments should hint towards their usage.
You can [download it here][1]. Project is dead now.
I've never needed the Equals() method in my applications thus far. Your mileage may vary though.
However, I create empty interfaces and use them as descriptors:
public interface IAggregateRoot {}
public interface IEntity {}
public interface IValueObject {}
public class Order : IAggregateRoot
{
...
}
public class State : IValueObject
{
...
}

Tell C# to use Castle to create objects

I think my question is a long shot.
Lets say I have an attribute:
public sealed class MyCustomAttribute: ActionFilterAttribute
Used on a class method
[MyCustomAttribute]
public virtual ActionResult Options(FormCollection collection)
Now, I need to add a contructor's parameter
public MyCustomAttribute(IMyDependentObject dependentObject)
{
(...)
}
(You propably notice that it's some Asp.NET MCV code)
I would like to use DI to create this attribute. Asp.NET MVC code automatically create it and I don't know how/where I could write code to use Castle istead.
Any ideas?
As far a I konw castle does not support injection of existing objects, which makes it impossible to inject attributes as their construction is not under your control. Other IoC containers such as Ninject support injection of existing objects. They inject properties of your attribut filter. See http://github.com/ninject/ninject.web.mvc for an extension that exactly does what you need.
What you can do if you want to stay on castle is to inject your own ControllerActionInvoker derived from ControllerActionInvoker (AsyncControllerActionInvoker in case of async controller) into all controllers. In your own invoker you override GetFilters. Additionally to the Filters returned by the base you add FilterInfos that are created by castle.
The decision which filters infos are created and added can be achieved with various strategies e.g.:
Add an own custom attribute that contains the information e.g. name of a binding
A configuration file/database
May you consider switching to MVC3 this makes all a bit easier. As you can register your own FilterProvider which makes all much easier. In this FilterProvider you have to decide which filter info you want to add. See again the two strategies above. See http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html for information about MVC3 and filters.