I have a few questions about "best practices" in my application structure. I make use of skinny models, and have service layers which do most (all) of the database interaction. The models call the service layer when they need a database transaction.
I also have a factory class which can return forms, models, and service layer classes. This factory class may also return a "search" class which acts as a very simple DBAL and is used by my service layer.
This search class has helper methods such as getAll() and getById().
I'm slightly confused about which parts of my application should have access to the search class; currently my model uses the static factory to build the search class when it needs to retrieve an entity by it's ID. Should my models instead be calling my service layer to make this call, thus negating the need to use my factory class to return the searcher?
I guess I don't like the idea that my database can potentially be accessed from multiple parts of my application, when really I'd rather everything need to go through my service layer first.
Tips and feedback are much appreciated!
I would end up creating a SearchService (which implements an interface i.e. ISearchService) class which the model, or any other code, that wants to access the Searcher would interact with.
This way you keep a clear separation from the Searcher class, or factory, which could change in the future. The other benefit is that, by having all the search related code in the SearchService, it becomes a lot easier for devs to understand the code, since they know that search related code is in the SearchService, rather then dotted around the codebase, calling factory methods, etc.
Also, by using an ISearchService, you allow yourself the option to use Dependency Injection, which is a nice way of having your object initialised for you, and not having to worry about implementation changes.
That's just my preference though, rather then this being a right/wrong way to do things.
Related
I have a question about Facade design pattern. As i started learning design patterns from the book: Elements of re-useable object -oriented-software, there is a good explaination of what it is and how it solves the problem.
This Picture comes from that book:
Problem:
Suppose i add some extra functionality in the subsystem for which Domain is an Facade/interface. With this design, i think it's not possible to add extra functionality in the subsystem without changing the Domain class?
Second, suppose i use an abstract class Domain(to create a hierarchical structure) and delegate all the requests to it's subclasses so that whenever i want to add new functionality , i simply extend my new class/subsystem with Domain(abstract), would that be wrong or still i will have a Facade structure?
Same thing happends in Adapter pattern. We can have different kind of adapter and instead of hard-coding one class , can we create such an hierarchial structure without violating any OOD rule?
The facade as well as the adapter design patterns are part of the so called "wrapper" patterns (along with decorator and proxy). They essentially wrap certain functionality and provide a different interface. Their difference is on their intent:
facade: is used to provide a simple interface to clients, hiding the complexities of the operations it provides behind it
adapter: allows two incompatible interfaces to work together without changing their internal structure
decorator: allows new functionalities to be added to an object statically or dynamically without affecting the behavior of objects of the same class
proxy: a class (proxy) is used to represent and allow access to the
functionality of another class
If your components "in the back" add new functionality and you want your facade to expose this functionality, you would have to adjust your facade to do so.
If you have the Domain class (facade in your scenario) as an abstract class that others extend, you do not have a facade, you have whatever inheritance you created with your classes. Simply put there is no "wrapping" for achieving the intent of the facade pattern.
With this design, I think it's not possible to add extra functionality in the subsystem without changing the Domain class?
True. However, the changes you make may (or may not) affect the client (Process) class. If you add a new method to the Façade, it won't break the "old" clients. Although it's not its explicit intention (which is to hide complexities of a sub-system), Façade can provide a stable interface to its clients that can be extended. When I say interface, I don't mean a Java or C# interface. It's a programming interface.
A real-world example is the JOptionPane Façade in Java/Swing. Check the Java doc at the link I put and you'll see that some of its methods existed in 1.4, some in 1.6, etc. Basically, since this class is part of a Swing library, it had to remain stable so old clients of it's interface would not break. But it was still extended with new functionality by simply adding new methods.
I would say this is how Façades are typically extended, not with sub classing or hierarchy. Hierarchies are difficult to maintain, because they are brittle. If you get the abstraction wrong (the root of the hierarchy), then it affects the entire tree when you need to change it. Hierarchies make sense when the abstraction in the hierarchy is stable (certain).
The Adapter pattern has hierarchy because an Adapter adapts a method to work with several variants of a service that cannot be changed. You can see examples of several stable (abstract) services such as tax calculation, accounting services, credit authorization, etc. at https://stackoverflow.com/a/13323703/1168342.
In cases of MVC applications where the model is split into separate domain and mapper layers, why would you give each of the mapper classes its own interface?
I have seen a few examples now, some from well respected developers such as the case with this blog, http://site.svn.dasprids.de/trunk/application/modules/blog/models/
I suspect that its because the developers are expecting the code to be re-used by others who may have their own back-ends. Is this the case? Or am I missing something?
Note that in the examples I have seen, developers are not necessarily creating interfaces for the domain objects.
Since interfaces are contracts between classes (I'm kinda assuming that you already know that). When a class expects you to pass an object with as specific interface, the goal is to inform you, that this class instance expect specific method to be executable on said object.
The only case that i can think of, when having a defined interface for data mappers make sense might be when using unit of work to manage the persistence. But even then it would make more sense to simply inject a factory, that can create data mappers.
TL;DR: someone's been overdoing.
P.S.: it is quite possible, that I am completely wrong about this one, since I'm a bit biased on the subject - my mappers contain only 3 (+constructor) public methods: fetch(), store() and remove() .. though names method names tend to change. I prefer to take the retrieval conditions from domain object, as described here.
I see most projects creating separate factory classes, so for example, they'll have a User class, and a UserFactory class. This makes sense if your factory needs more methods than just a CreateUser method, but most of these factories only have a constructor and a CreateUser method (or equivalent for whatever the factory creates). So, are there other reasons why you would create a separate factory class over just adding a static User.create() method to classes?
In my experience, separate factory classes are mainly used if you often want to change the implementation, especially for test cases. For example, if User has methods that hit a database and are "too slow" for a Unit Test, you might want to have a MockUser that doesn't use the database. Then you can have a RealUserFactory for the actual app, and a MockUserFactory for the unit tests.
But there may be real world examples where you want to change, say from a SecurityClearedUser in your military spec app to a AnyOldUser in another. So a config file would declare the class of the factory, e.g. a MilitaryUserFactory or an AnyOldFactory.
Of course, User.create() could read the actual class to create from a config file. So, in practice, I'm not sure if there's that much of a difference. Depends on how things are setup.
Another thing to consider is 'separation of concerns'. In the case of User.Create, the user class will be doing more than it should, hence the need of a class that does precisely that, creating a User.
By using User.Create, you would have coupled the creation of an object to the class itself and in other instances, you will be confronted by scenarios were the user creation consists of various steps, and if that is the case, the User.Create method becomes inappropriate.
So to be brief, keep the user object responsible for being a user, and outsource the creation of the user to an external concern, Factory.
and from a readability perspective, User.Create vs UserFactory.Create... think of it as 'a car cannot create a car', but a factory can.
I am designing a system that lets a user assign a specific task to be performed when a button is pressed. The task to be performed can be assigned to all sorts of things. So I have an abstract base class called "ButtonTask", and all other tasks inherit from this base to implement the task to be performed along with the associated data it needs to know. This way I can use polymorphism to abstract away all the specifics, I just call "PerformTask" without having to care about what type it actually is. So far so good.
The actual task itself can be set in may different ways, the user may change the task with a UI menu, the task may be read from a file, and also the task may be set remotely via a network message.
At the moment I have a factory function that will create the correct derived type based on the network message, and return a pointer to the base type. The problem is that the UI menu and the file reading feel like they need their own factory method for object creation, as they are inherently different from one another. Is it generally a good idea to have multiple factories for this kind of problem? I can't really think of another way around this problem but perhaps there's something neater I can do.
The only good reason I see to implement multiple factory methods is if you want to be able to create the objects with different sets of initial attributes, for instance by allowing the caller to specify some attributes and setting default values for others - the equivalent of having multiple public constructors.
If the idea is that the tasks are independent of the way they were initiated (GUI, network, etc), then I don't see a need for separate factory methods. Instead, I would say that one of the duties of the factory is to achieve this very abstraction. In other words, calling the same factory from three different parts of the code is absolutely fine. It is probably a good idea to make the factory method static or to make the factory a singleton object, though.
If on the other hand you have a situation where certain tasks can only ever be initiated from the network and others from the GUI, and only a few can be initiated in all three ways, then it might be worthwhile to rethink the design a bit. You should then consider adding another level of abstract Task classes, eg CommonTask, GuiTask, NetworkTask, FileTask, and have factories for them instead of ButtonTask. This is obviously more complex and whether or not it's worth it depends on the number of task classes and the structure of your code.
What you want to avoid is a situation where users of the factory are aware of which specific subclasses of ButtonTask they can receive from the factory. That's a "false base class" situation, ie one where the base class is not a true abstraction of the whole set of its subclasses, and you get out of it by adding the extra subclass layer as outlined above.
Other than that, you might also want to consider renaming ButtonTask; it sounds like a GUI-only task just from the name.
From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.
Is this correct and is it a rule that should always be followed?
The reason I ask is I have recently worked on a system with 100’s of very different objects. A few shared common interfaces but most do not and wonder if it should have had an interface mirroring every property and function in those classes?
I am using C# and dot net 2.0 however I believe this question would fit many languages.
It's useful for objects which really provide a service - authentication, storage etc. For simple types which don't have any further dependencies, and where there are never going to be any alternative implementations, I think it's okay to use the concrete types.
If you go overboard with this kind of thing, you end up spending a lot of time mocking/stubbing everything in the world - which can often end up creating brittle tests.
Not really. Service components (class that do things for your application) are a good fit for interfaces, but as a rule I wouldn't bother having interfaces for, say, basic entity classes.
For example:
If you're working on a domain model, then that model shouldn't be interfaces. However if that domain model wants to call service classes (like data access, operating system functions etc) then you should be looking at interfaces for those components. This reduces coupling between the classes and means it's the interface, or "contract" that is coupled.
In this situation you then start to find it much easier to write unit tests (because you can have stubs/mocks/fakes for database access etc) and can use IoC to swap components without recompiling your applications.
I'd only use interfaces where that level of abstraction was required - i.e. you need to use polymorphic behaviour. Common examples would be dependency injection or where you have a factory-type scenario going on somewhere, or you need to establish a "multiple inheritance" type behaviour.
In my case, with my development style, this is quite often (I favour aggregation over deep inheritance hierarchies for most things other than UI controls), but I have seen perfectly fine apps that use very little. It all depends...
Oh yes, and if you do go heavily into interfaces - beware web services. If you need to expose your object methods via a web service they can't really return or take interface types, only concrete types (unless you are going to hand-write all your own serialization/deserialization). Yes, that has bitten me big time...
A downside to interface is that they can't be versioned. Once you shipped the interface you won't be making changes to it. If you use abstract classes then you can easily extend the contract over time by adding new methods and flagging them as virtual.
As an example, all stream objects in .NET derive from System.IO.Stream which is an abstract class. This makes it easy for Microsoft to add new features. In version 2 of the frameworkj they added the ReadTimeout and WriteTimeout properties without breaking any code. If they used an interface(say IStream) then they wouldn't have been able to do this. Instead they'd have had to create a new interface to define the timeout methods and we'd have to write code to conditionally cast to this interface if we wanted to use the functionality.
Interfaces should be used when you want to clearly define the interaction between two different sections of your software. Especially when it is possible that you want to rip out either end of the connection and replace it with something else.
For example in my CAM application I have a CuttingPath connected to a Collection of Points. It makes no sense to have a IPointList interface as CuttingPaths are always going to be comprised of Points in my application.
However I uses the interface IMotionController to communicate with the machine because we support many different types of cutting machine each with their own commend set and method of communications. So in that case it makes sense to put it behind a interface as one installation may be using a different machine than another.
Our applications has been maintain since the mid 80s and went to a object oriented design in late 90s. I have found that what could change greatly exceeded what I originally thought and the use of interfaces has grown. For example it used to be that our DrawingPath was comprised of points. But now it is comprised of entities (splines, arcs, ec) So it is pointed to a EntityList that is a collection of Object implementing IEntity interface.
But that change was propelled by the realization that a DrawingPath could be drawn using many different methods. Once that it was realized that a variety of drawing methods was needed then the need for a interface as opposed to a fixed relationship to a Entity Object was indicated.
Note that in our system DrawingPaths are rendered down to a low level cutting path which are always series of point segments.
I tried to take the advice of 'code to an interface' literally on a recent project. The end result was essentially duplication of the public interface (small i) of each class precisely once in an Interface (big I) implementation. This is pretty pointless in practice.
A better strategy I feel is to confine your interface implementations to verbs:
Print()
Draw()
Save()
Serialize()
Update()
...etc etc. This means that classes whose primary role is to store data - and if your code is well-designed they would usually only do that - don't want or need interface implementations. Anywhere you might want runtime-configurable behaviour, for example a variety of different graph styles representing the same data.
It's better still when the thing asking for the work really doesn't want to know how the work is done. This means you can give it a macguffin that it can simply trust will do whatever its public interface says it does, and let the component in question simply choose when to do the work.
I agree with kpollock. Interfaces are used to get a common ground for objects. The fact that they can be used in IOC containers and other purposes is an added feature.
Let's say you have several types of customer classes that vary slightly but have common properties. In this case it is great to have a ICustomer interface to bound them together, logicaly. By doing that you could create a CustomerHander class/method that handels ICustomer objects the same way instead of creating a handerl method for each variation of customers.
This is the strength of interfaces.
If you only have a single class that implements an interface, then the interface isn't to much help, it just sits there and does nothing.