What's a good name for a façade class? - oop

A little background: We're building a library/framework for working with scientific models. We have an interface Model which defines the operations that a model must implement, which is pretty minimal. That is: the Model interface defines the contract of a model from the point of view of a model implementor.
The framework adds a bunch of other functionality around the model, but right now client code has to access that functionality by using a bunch of other classes, such as ModelInfo, ModelHost, ModelInstance, etc.
In our application that uses this framework, we don't want to actually have to deal with all this mechanism of running models, etc. So we've decided to use the façade pattern to wrap up the framework functionality in an easy-to-use object. (We've already applied this pattern to other parts of the framework, with good success.)
Here is the question: given that we already have an interface Model, what would be a good name for the façade class? The Model interface is the contract between the framework and the model implementation, and the new class will define the contract between the framework and the client application.
Or, more generally: when we have an abstraction provided by a library or framework, how can we name the "two sides" of the abstraction so as to clearly identify the "provider" and "consumer" interfaces to the abstraction?
(If it matters, for this project we're using Java 6.)

I know this seems trite, but... have you considered using "ModelFacade" as the class name for the facade class? I think with documentation that indicates that the interface was already named Model, it seems relatively straightforward, and makes it very clear which design pattern you're using.

How about *Provider and *Consumer? I think you said it yourself in your question. Perhaps *Producer and *Consumer is a better match?

In discussions within our team, another option has been proposed: we can rename the existing Model interface to something else, and just call the new façade Model. In fact, they can both be called Model right now, because they will live in separate packages. (Although I'm not a fan of identically-named classes in different namespaces.)

Sounds like ModelInfo, ModelHost, and ModelInstance should all be members of Model.
See https://softwareengineering.stackexchange.com/questions/316840/is-it-bad-practice-to-name-a-class-with-a-facade-suffix for why you generally shouldn't name classes with the specific implementation used. Basically, some day you may want to use a different implementation of Model, which happens to not be a facade.

PureMVC uses a singleton named ApplicationFacade and registers all the models with methods like registerProxy which are defined in IFacade

Related

Converting the interfaces in hierarchical structure in OOD

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.

Should a class named `User` be an implementation of Singleton Pattern?

Today I read a lot of articles about how Singleton Pattern is bad, such as
violating single responsibility principle
inability to subclass
inability to use abstract or interface classes
High coupling across the application
make unit test difficult
And then I remember I have a program with a class named User which has field userName and password and something else related to User. In my conceive the program should only have one user instance, which is created when a human logins in my program. Based on this, should I insist design User class as Singleton Pattern, or is there any good design conceive I should use?
Additionl:
Another doubt. Using Singleton Pattern, I can get the only instance myUser everywhere. If I should not go with Singletion Pattern, How should I get the only instance myUser?
You might want to look at dependency injection. These days there exist many frameworks to assist you with wiring of the dependency injections so that you can specify in the framework that you expect a certain object to behave like a singleton. In other words if another object also requires the same "singleton" object, the framework should not create a new instance, but "inject" the already existing instance.
If you develop in Java, you may for example look at the way Guice did it: https://github.com/google/guice/wiki/Scopes They allow you to specify whether you want to create an "eager singletons" (created even if not needed yet) or "lazy singletons" (created on the fly only when required). Even if you are not using Java other programming languages got similar concepts that you could look out for.
What I would suggest is that you make the "User" object not a singleton and "inject" your "User" object into the classes that requires the "User" object. If possible, let the dependency injection framework of your choice handle the wiring so that you do not accidentally create more than one instance.
This way you will still be able to achieve most of the above mentioned advantages you posted in your question and still enjoy the benefits of a "singleton".
It depends on your context. If your application must have one and only one User, then use Singleton pattern. Your 5 points mentioned will be completely counter-productive.
In your example, this is not the case. But just one and only one instance is mandatory for the execution of one process. You should take in account #Koning response then.
For example, Spring security implements some common patterns of user logged with static methods :
SecurityContextHolder.getContext(). getAuthentication()
If you look at Microsoft memberhship than you will see that they store all data on session level. The best way I see to implement such logic which will be stored on all session level is Singleton pattern, because you won't need two classes working with user data. As alternative you can use static classes, but you couldn't serialize your user data in this case

Why would I create an interface for each mapper class?

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.

What exactly is "persistence ignorance"?

Persistence ignorance is typically defined as the ability to persist & retrieve standard .NET objects (or POCOs if you really insist on giving them a name). And a seemingly well accepted definition of a standard .NET object is:
"...ordinary classes where you focus on the business problem at hand without adding stuff for infrastructure-related reasons..."
However, I see people describing NHibernate as a framework that allows persistence ignorance, and yet it is a framework that cannot work on any standard .NET object, only standard .NET objects that adhere to particular design requirements, for example (source):
All classes must have a default constructor
Some features don't work unless classes are unsealed and all members are virtual
Object identity doesn't work properly unless you abuse Equals/GetHashCode
(Aside: Before anybody gets upset, I don't mean to pick on NHibernate here, it's just a frequently quoted example of a framework that supposedly permits persistence ignorance. I'm sure similar arguments could be applied to other ORMs that claim the same.)
Now although the class in itself does not have any persistence-framework-specific attributes or base classes etc., to me it is not really "persistence ignorant" because it must follow a set of design guidelines to facilitate use by the chosen persistence framework. You must design and implement the class with the requirements of the persistence framework in mind; if you are ignorant of it the class may not work with it.
Where I'm having trouble with the definition of "persistence ignorance"/"POCO" is that I don't see how, conceptually, this is really any different to adding attributes such as [Serializable] or [DataContract] or [XmlType] or any other persistence-framework-specific annotations that facilitate the persistence and retrieval of the entity using that framework.
So, what exactly is "persistence ignorance"?
Clearly the definition of it as being able to persist "ordinary classes" is a fallacy because the NHibernate ones are only ordinary insofar as not referencing framework-specific classes, whereas they are extraordinary inasmuch as they require unusual design choices such as default constructors and all-virtual members and Equals/GetHashCode implementations on mutable types.
Is it therefore reasonable to say that "persistence ignorance" is true when objects facilitate the use of a persistence framework (either in design and structure or by use of framework-specific annotations) but do not perform any persistence logic themselves?
I would claim that, like most things, its a sliding scale. There are things that we make that want to have the property of persistence. On one end of the scale is this thing having all of the guts, dependencies, and code that is custom built to persist just this one thing in its particular way. On the other end of the scale is something that just magically happens, all without us doing much more than adding a token or setting a property somewhere that causes that thing to 'just persist'. In order to get to the magical side of the scale, there are frameworks, design guidelines, conventions, etc that assist the magic in happening. I think you could argue that a tool could be produced that had fewer requirements and restrictions than NHibernate but pursued the same goal; that hypothetical tool would be further along our scale.
I don't know that I like the term 'persistence ignorance' so much; its really about an object being ignorant of the implementation, the backing store, the cache, that sort of thing - an object is typically aware of whether or not it is persistent, though. But that's just semantics.
I don't believe your understanding (or definition) of "Persistence Ingorance" is wrong.
The real issue is that of leaky abstractions. Quite simply, the existing technology makes it very difficult to implement true PI.
A persistant ignorant class, is a class that is not tied to a persistancy framework.
That is, the class has absolutely no knowledge that there's a persistancy framework present, it does not inherit from a class that is defined by that framework nor does it implement an interface that is required for that persistance framework in order to work.
I agree with Mikeb - "persistance ignorance" is a sliding scale, not a true/false property of a given ORM.
My definition of true 100% PI would be that you could persist ANY possible POCO class, no matter how convoluted and linked to other classes, without otherwise changing the class in any way.
Adding ID fields, decorating with attributes, inheriting from ORM classes, having to design your classes so they map well to the underlying tables in an RDB - all reduce the "PI score" below 100%.
This said, I've chosen to use Fluent NHibernate Automapping because it seems to have the highest PI score of any of the ORM options I've looked at.
I'd agree with your definition:
Is it therefore reasonable to say that
"persistence ignorance" is true when
objects facilitate the use of a
persistence framework, but do not
perform any persistence logic
themselves?
The code (as opposed to atributes) in your classes has no features that are intrinsic to persistence. Default constructors might be needed for persistence, but have no code that actually does persistence. The persistence layer could be changed quite substantially, different databases could be used and the business logic would remain unchanged.
While there may be certain minor constraints that any given persistence-ignorance framework requires, persistence-ignorance nevertheless remains in place.
While a class in your domain model (transparently persisted with NHibernate) must have a no-arguments constructor so that it can be constructed "dynamically," it is not required to have a certain base class dictated by the framework nor is it required to have or override certain framework-specified methods.
In my opinion, "persistence ignorance" is a property of your model (domain model, business model or whatever you might refer to it as). The model is persistence ignorant because it retrieves instances of the entities it contains through abstractions (sometimes referred to as repositories). These abstractions can be implemened by using an ORM directly, but as you state yourself this may sometimes add requirements to the objects that do not naturally belong in your model. Therefore I would not say that a model that adheres to some requirements of a specific ORM is 100% persistence ignorant.
you can implement persisrtence ignorance using a class for the domain or you application and a POCO class in the persistence, when you are going to persist the domain object map it into your persistence class and use the persistence object to store with nhibernate o other framework
your domain class must to ignore how is persisted the information, so you must no include any rules of a persistence framework like (empty constructor, virtual properties etc.)
these persistence framework rules can be in your persistence class.

Should every single object have an interface and all objects loosely coupled?

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.