Using DI with a shared library across applications - c#

I'm facing a design challenge that I just can't seem to solve in a satisfactory way. I've got a class library assembly that contains all of my shared ORM objects (using EntitySpaces framework). These objects are used in 2 or more different applications which is why they are in their own assembly. This setup has worked fine for 4+ years for me.
I also have a couple of applications built on the Composite Application Block (CAB) from Microsoft's Patterns & Practices group (P&P). Yes, I know this is really old but I'm a part time developer, one-man-shop and can't afford to update to whatever the current framework is.
Here is where my problem comes in: I have been exercising my OO design skills and whenever doing a substantial refactoring I try to shift from a procedural approach to a more OO approach. Of course a major aspect of OO design is placing the operations close to the data they work with, this means that my ORM objects need to have functionality added to them where appropriate. This is proving a real head scratcher when I also consider that I'm using P&P's Object Builder DI container within CAB and that much of the functionality I would move into my ORM objects will need access to the services exposed by my applications.
In other words, let's say I have a shared business object called "Person" (original, I know) and I have two applications that do ENTIRELY different things with a person. Application A provides a set of services that the Person object would need to have DI'ed in order for it to take on some of the methods that are currently littered throughout my services layers. Application B also has a different set of services that IT needs to have DI'ed into the person object.
Considering how the P&P Object Builder resolves dependencies using attribute decoration and Type reflection I don't see how I can accomplish this. In a nutshell, I have a shared object that when used in various applications I would need to inject dependencies so that it can perform certain operations specific to that application.
The only approach I can come up with is to inherit a new Type in Application A & B from the Person object. I would then add my non-shared functionality and DI code into this application-specific specialized Person object. Now that I write that it seems so obvious, however it's still my only solution I can come up with and I wanted to ask here to see if anyone else had a different solution they would like to propose?
One problem I would have with my solution is that I can see myself getting caught up on naming my inherited type - I mean... it's a person, so what else would you call it? Anyways, hopefully you will have some ideas for me.
Also, I'm not hip on the current technologies that are out there and really, to be honest only barely grasp the ones I'm currently using. So if I've said something contradictory or confusing I hope you can understand enough from the rest of the post to get what I'm asking.

It sounds like you're breaking the Single Responsibility Principle.
A Person object should just be holding the data for a person record. The services would then take in a Person object and manipulate it rather than having methods on the Person object that did that manipulation.
A classic example of this would be populating the Person object. Lets say app A grabs the data from a WebService, and app B grabs it from a database. In these cases I'd have some sort of Storage service that you call to get your Person object. Then implementation of that storage can be specific to each application, and be put into your IOC by the app, rather than trying to have a common interface in your shared assembly.

I agree with Cameron MacFarland on this: You are breaking SRP.
Of course a major aspect of OO design
is placing the operations close to the
data they work with, this means that
my ORM objects need to have
functionality added to them where
appropriate
Placing data AND functionality from A AND functionality from B is two responsibilities too much. Adhearing to SRP will almost always result in seperating data and functionality in seperate classes (data structures and objects). Thus, using Cameron MacFarlands sugestion is probably the best way to go.

I could think of couple of approaches to address this.
Separate out the behavior specific to each person/application separately. Perform dependency injection using setter in the application itself.
Apporach1
public interface IPerson
{
IPersonApp1 Person1 {get; set;}
IPersonApp2 person2 {get; set;}
}
class Person : IPerson
{
IPerson1 Person1 {get; set;}
IPerson2 Person2 {get; set;}
}
public interface IPerson1
{
// App1 specific behavior here
void App1SpecificMethod1();
}
class Person1: IPerson1
{
void App1SpecificMethod1()
{
// implementation
}
}
class App1
{
IPerson objPerson;
// Dependency injection using framework
App1(IPerson objPerson)
{
this.objPerson = objPerson;
// Dependency injection using setter
this.objPerson.Person1 = new Person1();
}
}
Separate out the behavior specific to each person/application separately. Perform dependency injection in the Person constructor.
Apporach2
class Person : IPerson
{
IPerson1 Person1 {get; private set;}
IPerson2 Person2 {get; private set;}
// DI through constructor. If the type IPerson1 or IPerson2 are not registered, it will be set to null.
Person(IPerson1 objPerson1, IPerson2 objPerson2)
{
this.Person1 = objPerson1;
this.Person2 = objPerson2;
}
}
Person interface project need to have reference to IPerson1 and IPerson2 or you can declare IPerson1 and IPerson2 in the Person interface project itself.

Related

Working with concrete type of a base parameter passed in a strategy method

I ran at a major architectural problem.
CONTEXT
I'm trying to build an ASP.NET Core microservice application that implements the strategy pattern.
The application communicates with other microservices.
I have a main entity that aggregates all the information I need to work with, let's call it "MainContext". The goal is that this entiy is loaded and built only one time (as we need to get that information from other microservices) and then is processed throughout the whole application.
public class MainContext
{
public DeterminerAttribute Attribute {get; set; }
public OtherContextA ContextA { get; set; }
public OtherContextB ContextB { get; set; }
}
As you can see, the MainContext aggregates other contexts. These 'OtherContexts' are base classes that have their own child classes. They are somehow different and have different types and quantities of fields.
The application builds the MainContext in one separate place. The process looks something like this:
We get a specific attribute from other microservice and use this attribute as a determiner in a switch expression. The attribute is also saved in MainContext.
In switch expression we load specific implementations of OtherContextA and OtherContextB classes and wrap them up in their base classes. This step is important, as I don't want to ask for information that I don't need from other services.
The method returns MainContext with all information loaded, ready to use.
Then, I use strategy pattern, because different contexts require different treatment.
THE PROBLEM
The strategies have the same interface, and thus should implement the same methods that have the same signature. In my case, there is only one method, that looks something like this:
public class SomeStrategyToProcessContext : StrategyInterface
{
public async Task ProcessContext(MainContext mainContext, ...);
}
Now, in strategies I want to work with concrete implementations of Contexts. It makes sense as I KNOW, as a programmer who made that mess, that the strategies to be used are chosen based on the same attribute that I used to load contexts and therefore should work with the concrete implementations, as I need data stored in them. But this:
var concreteContext = (OtherConcreteContextA) mainContex.ContextA
is considered a bad pratice, AFAIK.
Obviously, base classes have only base, unspecific data. In strategy classes, I want to provide access only to the NEEDED data, no more, no less.
My quistion is: is there any safe and sustainable way of implementing this witin OOP (or other) paradigm? I want to avoid the casting, as it breaks the abstraction and contradics every programming principle I've learned about. Any advice, even if it's toxic or/and suggests to change the whole architecture is as good as gold. Thanks!

Passing config values as parameters to an instance method C#

I come across this regularly when refactoring code. Say I have a base class and I read some configuration parameters and stuff them into properties like this
public BaseClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
And then I call a method in another class like this
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod(_property1, _property2, _property3);
Is it better to do that? What if I only needed the AppSettings values inside of the OtherClass class? then I could just load them up as private props and initialize them in the constructor and the referencing class/caller wouldn't need to be concerned with the settings.
public OtherClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
My implementation would then simply be
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod();
This one bugs me but I am not really sure why. Which is a better practice and why? And I apologise I am missing something obvious. It happens sometimes lol.
Thanks -Frank
In my view, it depends on what goal of your class.
If class belongs to domain classes, so there is no need to have a dependency to ConfigurationManager class. You can create a constructor and supply necessary data:
public class FooClass()
{
public Property1 {get; private set;}
public FooClass(string property1)
{
Property1 = property1;
}
}
If FooClass belongs to Service Layer, then, in my view, it is eligible to have a dependency to ConfigurationManager class.
I can't really comment on "better" as that's quite subjective, but it's at the very least factual to say that passing the parameters into the method, rather than having the method go and get them itself, is a form of dependency injection. Dependency injection has advantages in that it reduces the number of things the class has to know how to do/reduces the number of other classes any given class needs to do its work. Typically in OO design we look for ways to reduce the dependencies a class has on other classes. You might also see the concept referred to in general as low coupling. Classes that are not highly coupled to other classes are easier to reuse as independent modules within multiple programs
In your example, OtherClass (and/or BaseClass) needs to know what a ConfigurationManager is, which means it needs a reference to its namespace, needs to have system.configuration.dll available on the target etc just so that it can go and get some basic things (strings) that contain info necessary to do its work. If you instead give the strings to the method then it can do its work without knowing what a ConfigurationManager is - you can use it in an app that doesn't even have a ConfigurationManager anywhere, maybe because it gets its config from a database or perhaps it's part of a unit test that gets some contrived data directly from hard coding to ensure a given result is always obtained
When you're down with the concept that the data a class needs to do its work can come from above it starts to make more sense why systems that pass data around like this can work with an inversion-of-control container; essentially software that creates instances of objects for you according to some preconfigured rules about where to get the data that should be passed in. An IoC container can look at an object and decide what arguments to pass to (e.g. its constructor) based on a consistent set of rules, and take another step towards removing dependencies by further reducing use of the word "new". Think of it like writing a config file to describe which of your objects need what instances of other classes to do the work. You craft your IoC container setup so it makes one IniFileConfigSettingsProvider instance and then provides that instance to any object that needs some kind of IConfigSettingsProvider to do its work. Later you switch away form ini files and go to Xml files. You create a class called XmlFileConfigSettingProvider, register it with the IoC and it becomes the new instance that is passed to any class needing an IConfigSettingsProvider. Critically, you made another class, registered it with the IoC and then it gets used throughout your program but you never made an instance of it yourself
If you ever heard the phrase "new is glue" concepts like this are generally what it alludes to - when your OtherClass says var x = new ConfigurationManager... x.Settings["a"].... the use of the word new has suddenly hard wired it to needing a ConfigurationManager; it can't function without knowing what it is. The strive these days is generally to have a class accepting a "passed-in provider of settings that complies with some interface" or "passed-in primitives that are settings" - things that are either implementation specific but obey a generic interface, or ubiquitous in the language and need no special imports respectively. Perhaps either of your mentioned approaches bug you because deep down you feel that neither of them need to depend on ConfigManager; whether they both need settings or not, they can get them passed in, from something higher up the chain that should be making the decisions as to what settings to use
There will be pros and cons of every design and coding choice. As they say, same pattern may not fit everyone. So one has to customize based on need.
Mainly, decision should be based on use cases of your application. Let me provide few scenarios to describe it. Suppose items configured in AppSettings will not change in life-time of the your application then you can have an approach in which dependencies with AppSettings are least. In particular an approach as var foo = otherClass.SomeMethod(_property1, _property2, _property3);. This matches with OOD principles as classes will focus on business logic.
But if you see add/modifying/deleting items (even in rare situations) during life time then above approach would be difficult to maintain. For example without restarting your application/WebServer if AppSettings needs to be reloaded based on certain conditions. One may argue why such settings will be kept in AppSettings, which is very valid too. If your application demands such scenarios then it would be better to use ConfigurationManager.AppSettings without worrying about dependencies. One can opt to extend it have wrapper class (Singleton pattern) to manage and provide access to ConfigurationManager.AppSettings.

How to separate/decouple instance creation of children when creating core model in DDD

A course can have multiple activities, i.e. Training, Exam, Project, Book, Article, and Task.
Following are the requirements:
Allow the teacher to schedule a course.
Allow the teacher to schedule different activities in the said course.
Display list of activities to the student for a selected course, in a specified date range.
The above requirements lead me to create two aggregates.
CourseAggregate
ActivityAggregate
Why?
A course can be created without any activities, but only in draft state. A course can be scheduled on for a different set of students.
An activity can be created independent of course, and later on, linked to a course.
Activities can be fetched with a date range only for a given student.
protected abstract class Activity
{
public Guid Id {get; private set;}
}
protected class Training : Activity
{
..... Addiontal properties
}
protected class Exam : Activity
{
....Addiontal properties and behavior.
public bool AllowGrading => true;
}
.... Other childern of activity..hence more classes.
Questions:
Is it the right approach to go with inheritance?
Since I marked the constructor protected, so the client code will not use the new operator, and will not have direct knowledge of children. I am struggling to figure out how the client should create an instance of the activity. For example:
[Test]
public void ActivityFactoryShouldCreateCorrectActivityType(){
var activity= ActivityFactory.CreateActivity(activityType:"Training", title:"Training", DueDate: "date".......)
}
Problem is, each subtype might want to enforce different invariants for the entity to be correctly created. For example, Exam activity requires information about the scale of grading.
How to solve correctly implement it or which pattern suits better here?
That is one of the problem that frquently pops up when using a language like C# or Java. That is an implementational problem more than it is modeling issue.
The thing is that you do have these concepts: Exam, Training etc. that are concrete. On the other hand you can derive a common concept for them: Activity.
Here are couple of questions that we need to ask before we consider an implementation.
What it needs to do with these concepts?
How does it works with them?
How many parts of the system are interested in the concrete concepts Exam, Training etc. and how many of it is interested in the common concept of Activity?
Do you expect to add many more concepts that will be Activities? This will affect how you evolve your system.
Let's say that your system doesn't use the concept of Activity much and it wont have many more activities added. In this case we can just ignore Activity and just use concrete concepts. This say there is no problem in creating them.
Let's say that your system will use the concept of Activity and you need to add more types of activities.
This doesn't undermine the fact that your system will know of the different concrete types of activities. It will create them, work with them etc. Even when your system is working with the concept of activity it will probably still need to know the concrete type of the activity so it can do something with it.
This kind of logic shows a problem with the way that we think when we use an OOP language like C# of Java. We are trained as developers. usually people say that casting is bad. You sould somehow define a base class or an interface and let subclasses of interface implementers define a behavior and the other parts of the system shouldn't know the concrete type.
And this it true for some parts of the system and for come concepts. Take for example a Serializer. You can define an interface ISerializer with a method Serialize. The system that uses a serializer may use the interface without having to know the concrete type as each class that implements the ISerializer interface will add a different implementation of the same interface.
Not every problem is like that. Sometimes your system needs to know what it deals with. This is where i thing we can learn something from languages like JavaScript. There what you have is an object that is non specific and use can just attach properties to it. The object is what it's properties define it to be.
The concept of Duck Typing is interesting: "If it walks like a duck and it quacks like a duck, then it must be a duck"
If you system needs to work with Exam it should work with it not with an Activity. If it has an Activity it should be able to figure out it it's indeed an Exam because this is that it needs.
Now we live in the strong typed world and it has it's good parts. I love strong typing and what it gives you, but also some problems are more difficult to deal with.
You can use classes with inheritance to implement this. You also use interfaces instead of having classes to capture different concepts. Yet your system will need to do some casting to determine the concrete type of what is working with. We can make it's life a bit easier if we capture the fact that we have different types of Activities explicitly
Here's an example:
public enum ActivityType { Exam, Trainig, Project, Task }
public class Activity {
public Guid ID { get; private set; }
public abstract ActivityType Type { get; }
// other stuff
}
public class Exam : Activity {
public override ActivityType Type {
get { return ActivityType.Exam; }
}
// other stuff
}
public class SomeClass {
public void SomeAction(Activity activity) {
if(activity.Type == ActivityType.Exam) {
var examActivity = (Exam)activity;
// do something with examActivity
}
}
}
If creating your activities have some logic related to them you can use a Factory to create them by using their concrete types.
public class ExamFactory {
public Exam CreateSummerExam(string name, //other stuff) {
// Enfore constraints
return new Exam(new Guid(), name,....);
}
}
Or add a Factory to the concrete type:
public class Exam : Activity {
public static Exam CreateSummerExam() {
// Enfore constraints
return new Exam();
}
private Exam() { }
}
Or just use a public constructor if creating these objects is not complex.
If you realy want to hide the classes to allow yourself some freedom of implementation then use interfaces:
// **Domain.dll**
public enum ActivityType { Exam, Training }
public interface IActivity {
ActivityType Type { get; }
}
public interface IExam : IActivity { }
internal class Exam : IExam { }
public class ActivityFactory {
public IExam CreateExam() { return new Exam(); }
public ITraining CreateTraining() { return new Training(); }
// other concrete activities
}
This way you don't allow clien code to have access to classes. You can give them access to public interfaces and keep other implementation specific methods internal to your Domain.dll. Clients of these concepts can still use casting to use the appropriate type that they need, but this time they will use interfaces.
Here's a good article on this. In it Martin Fowler says:
With OO programs you try to avoid asking an object whether it is an
instance of a type. But sometimes that is legitamate information for a
client to use, perhaps for a GUI display. Remember that asking an
object if it is an instance of a type is something different than
asking it if it is an instance of a class, since the types
(interfaces) and the classes (implementations) can be different.
EDIT:
Another implementation of this is to treat an Activity as a container that you can attach different things to it. This will give you a more flexible system. Unfortunately this won't remove the need for switching and checking if various features are present in your entity. It's possible to some degree but depending on your concrete case you may need to process an Activity from some external component and will need to swith and check.
For example you may want to generate some report. You may need to get some activities, process them and then generate some report based on some data stored in them. This cannot happen with attaching components to one activity as this operation requires multiple activities not a single one.
There are a lot of systems that do this kind of thing. Here are some examples:
Computer Games use something that is called Entity Component System.These systems are data oriented where an Entity is comprised of different Components. Each system then checks to see if a Component is attached to an Entity. For example you have a Rendering system that renders your scene with all players and stuff. This system will check if an entity has attached 3D model component. If it has it will render it.
The same approach is used in Flow Based Programming. It is also data driven where you send Information Packets that are composed of different properties. These properties can be simple or complex. Then you have Processes that are connected and pass data between each other. Each Process will search for specific type of data in a IP to check if it's supported by it.
Unity also supports using Entity Component System. But it also supports another similar approach to having active components that contain behavior and logic instead of passive data that is processed from external systems.
Feature based programming. Uses the notion of features that you can add to an object. It's used in CAD/CAM system, banking systems and many more
It's a good approach to use when having dynamic data that needs to be processed. Unfortunately this won't remove the need to do some if/else and swich. As already mentioned, when you need to process collections of Activities you will need to do some checking.
Note that the systems above don't try to avoid this. On the contrary. They embrace this fact and use dynamic data. It's no different then having a type fo the activities and switching on it. It's just that their approach give a more flexible system at the expence of doing a lot of checks.
If you system doesn't require that kind of dynamic data you can just use concrete classes instead of data objects that can store unlimited number of things. This will simplify some parts of your application. If you do need to compose different objects then you can use one of the approaches above.
Thank for taking the time to answer the question in detail & with beautiful insights.
Consider we are developing https://coursera.org site. There are two major high-level goals which system has to achieve.
- Teacher/Course Creator should be able to create (schedule) a Course. From creator point of view, he/she want to add Exam, training or other activities to course. But he/she will refer to it as "I am scheduling an exam activity in this course for the following dates, with the following criteria of fail/pass" or "I am scheduling a training activity, in this course." Now, if we go with IActivity interface approach along with ActvityType Enum, all the client code, will be using switch or if/else to see what type of activity it is, and this will flow to top-level i.e. UI, or even controllers or consumer classes,
if(activity.type==exam){ ((Exam)IActivity).DoSomething();}
But this looks acceptable given there is no good alternative, but it really clutters your code.
- From a student perspective, he/she is only interested in the following
-- show me the list of all activities I have to perform, but tell me what type of activities they are
-- Once I attempt/do an activity, he/she expect different behavior as well, for example, Training does not have any grading attached to it, while exam does.
--- Exam is allowed to take only once.
--- Summary Exam grading is different than Full Exam.
--- Summary Exam Allow Late Submission while Exam does not have that feature at all.
Now again in order to call the correct behavior of IActivity, enum is helpful but it is cluttering the code base at all levels, where the decision has to be made. And IActivity does not know about the behavior Exam at all, and exam can be of multiple types, thus adding to the complexity so another enum to see what kind of exam it is since Summary Exam and Full Exam only differs in grading behavior, and everything else is same. Now with this, another switch statement or if/else on all consumer classes.
* Factories will help with this, but I am worried it will become too complex, having different methods in factories, since Exam can be in a valid state (draft) with a different combination of properties.
So the system is interested both in Activity and concrete types i.e. Exam, Training, etc but in different scope.
** Additional complexity, what if the teacher wants to create a new type of activity which is saying "Its Path activity, the exam is only available when the student takes this training." Now, the student is still interested to see a list of all activities, just want to know the type of it (as a label).
Lately, I have been thinking about composition instead of inheritance, where there is only one type, Activity, and it has a set of a feature collection. Each feature contains its own behavior in its own class. Have not done it before, not sure if this sort of approach exists or even beneficial.
Thanks again for the detailed answer again, would love to hear your thoughts.

C# IoC Instantiation when the injected objects are conditional

I have an IoC question that for the moment is abstract. I have not yet chosen an IoC framework for started coding. I am still mentally planning the methods I am going to use for an imminent project.
My coding style generally follows this pattern:
A Processor of some kind is instantiated and passed a Business Object.
The processor in turn will instantiate a Validator to validate that the passed business object is valid for the given process.
If the Business Object is found to be valid, then a Persistence Object will be instantiated. The Persistence object is responsible for transformations such as encryption, caching, and grouping multiple requests together in a single transaction for object graphs.
Then, the business object instantiates a DataLayer that will have the job of persisting the Business Object to the database, or pulling it from the database as the case may be (or a text file, or a webservice, whereever the data may live.)
My ideal structure is that a Processor knows about a Validator and a Peristence object, but not an AccessLayer. A persistence object knows about an access layer, but cannot directly instantiate or invoke a process. This way there are clearly defined layers that can be seperated as necessary
Finally, this process is agnostic to input or output and immutable based on the application type. In other words, I could use the same Processor to add a business object in a web app as I would in a desktop app. Obviously, the Model/View/Controller would change depending on the app type, but the rules for adding or selecting a business object remain universal.
My problem is this. I don't like that my AccessLayer in turn needs to pull the connection string from the config file, for instance. Maybe I want my users to be able to specify a config file or a Db Table for settings. Having the access layer check the config file to see if it should use the config file is circular and silly. And the Access Layer cannot likewise call a Persistence object to pull the settings, or query the Application Framework to see if it is a web app with a Web.Config or a desktop app with DbSettings.
So I was thinking that the best thing for me to do is to use an IoC container of some kind. I could then inject whatever settings I needed. This could also allow me to mock objects for testing, which is another difficult (but not impossible) task with my current method. So from my reading, my vague Processor implementation would look like this:
public class VagueProcessor{
public VagueProcessor(IValidator validator,
IPersistence persistence,
IAccessLayer accessLayer,
ISettings settings) { ... }
}
Here is my snag. In the application I am planning, the Business Object have a variety of implementations each with their own configurable rules. Say one BO is for the state of CA and another for the state of NY, and both states have their own special rules to be validated by their governing bodies. So the validator could be a CAValidator or a NYValidator just depending on the state of the Business Object.
Ok, so my question after all that preamble and backstory is this: in this scenario, would I pass a ValidatorFactory to the Processor and the Factory would instantiate the appropriate type of Validator based on the state of the Business Object? And if so, would I register each type with the IoC container, or just the Factory?
Thanks for your thoughts on this matter!!
That's a vague question as you don't have a problem yet, only the idea.
From what I understand from your question, I'd say:
The IOC solves the problem of creating the new object, not exactly deciding which object to create. In most IOC containers you can at some level choose the implementation you're asking, but in your case the logic looks very application centric, and no IOC container will help you deciding which one to use. In that case, you should indeed have a factory passed to your processor where you can ask something like factory.CreateValidatorFrom(myBusinessObject).
Internally, that factory can still use DI to instantiate each component. If you use .NET Core DI for example, you can pass a IServiceProvider to the factory, and call inside the factory serviceProvider.GetService<CAValidator>(). All DI providers will have an object like that.
So, in a sense, the factory and the DI can co-exist and each of them solve part of the problem. If you're using DI, you shouldn't ever have to instantiate the actual class. That will make it easier for each validator to have their own dependencies and you don't have to care how to get them.
And yes, in that case you'd register each validator in the DI, and also the factory. In cases like this, you can easily loop through all of them through reflection and register them dynamically by name or interface, if that is bothering you.
And in the end, if you're using .NET Core, I strongly suggest you to simply use the built-in DI. It's simple and good enough for most cases.
Validation is a crosscutting concern, so typically the validation service doesn't know about the details of the object it is validating. It only knows about its boolean valid state and how to get validation errors that are typically displayed on the UI.
As a crosscutting concern, the validation rules are abstracted from the services that read them. This is usually done via an interface and/or .NET attributes.
public class ValidateMe : IValidatableObject
{
[Required]
public bool Enable { get; set; }
[Range(1, 5)]
public int Prop1 { get; set; }
[Range(1, 5)]
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
/* Return valid result here.
* I don't care if Prop1 and Prop2 are out of range
* if the whole object is not "enabled"
*/
}
else
{
/* Check if Prop1 and Prop2 meet their range requirements here
* and return accordingly.
*/
}
}
}
The validation service then only needs to have a mechanism to process the rules (returning a true/false for each rule) in order to ensure all of them are valid, and a way to retrieve the errors for display.
The validation service can do all of this by simply passing the model (the runtime state) to the service.
if (validationService.IsValid(model));
{
// persist
}
This can also be done using a proxy pattern to ensure that it always happens if the interface and/or attributes are available to process.
NOTE: The term Business Object implies that you want to build some sort of Smart Object Framework using objects that know how to save and retrieve their own state (internally implementing CRUD). This sort of design doesn't lend itself to DI very well. That isn't to say you can't use DI and a Smart Object design at the same time, it is just more difficult to build, more difficult to test, and then more difficult to maintain.
A design that uses models to abstract the runtime state of the application away from the services that use the models makes for an easier path. A design that I have found works pretty well for some applications is Command Query Segregation, which turns every update or request for data into its own object. It works well with a proxy or a decorator pattern to implement crosscutting concerns. It sounds strange if you are used to working with smart objects, but a loosely coupled design like this is simpler to test which makes it just as reliable, and since query and command classes are used like
var productDetails = this.queryProcessor.Execute(new GetProductDetailsQuery
{
ProductId = id
});
Or
// This command executes a long and complicated workflow,
// but this is all that is done inside of the action method
var command = new AddToCartCommand
{
ProductId = model.Id,
Quantity = model.Qty,
Selections = model.Selections,
ShoppingCartId = this.anonymousIdAccessor.AnonymousID
};
this.addToCartHandler.Handle(command);
it is almost as easy to use. You can even easily break out different steps of a complicated workflow into their own commands so it can be tested and verified at each step of the way, which is something that is difficult to do on a smart object design.

How abstraction and encapsulation differ?

I am preparing for an interview and decided to brush up my OOP concepts.
There are hundreds of articles available, but it seems each describes them differently.
Some says
Abstraction is "the process of identifying common patterns that have
systematic variations; an abstraction represents the common pattern
and provides a means for specifying which variation to use" (Richard
Gabriel).
and is achieved through abstract classes.
Some other says
Abstraction means to show only the necessary details to the client of
the object
and
Let’s say you have a method "CalculateSalary" in your Employee class,
which takes EmployeeId as parameter and returns the salary of the
employee for the current month as an integer value. Now if someone
wants to use that method. He does not need to care about how Employee
object calculates the salary? An only thing he needs to be concern is
name of the method, its input parameters and format of resulting
member,
I googled again and again and none of the results seem to give me a proper answer.
Now, where does encapsulation fit in all these?
I searched and found a stack overflow question. Even the answers to that questions were confusing
Here, it says
Encapsulation is a strategy used as part of abstraction. Encapsulation
refers to the state of objects - objects encapsulate their state and
hide it from the outside; outside users of the class interact with it
through its methods, but cannot access the classes state directly. So
the class abstracts away the implementation details related to its
state.
And here another reputed member says,
They are different concepts.
Abstraction is the process of refining away all the
unneeded/unimportant attributes of an object and keep only the
characteristics best suitable for your domain.
Now I m messed up with the whole concept. I know about abstract class, inheritance, access specifiers and all. I just want to know how should I answer when I am asked about abstraction and/or encapsulation in an interview.
Please don't mark it as a duplicate. I know there are several similar questions. But I want to avoid the confusion among the conflicting explanations. Can anyone suggest a credible link? A link to stackoverflow question is also welcome unless it creates confusion again. :)
EDIT: I need answers, a bit c# oriented
Encapsulation: hiding data using getters and setters etc.
Abstraction: hiding implementation using abstract classes and interfaces etc.
Abstraction means to show only the necessary details to the client of the object
Actually that is encapsulation. also see the first part of the wikipedia article in order to not be confused by encapsulation and data hiding. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
keep in mind that by simply hiding all you class members 1:1 behind properties is not encapsulation at all. encapsulation is all about protecting invariants and hiding of implementation details.
here a good article about that.
http://blog.ploeh.dk/2012/11/27/Encapsulationofproperties/
also take a look at the articles linked in that article.
classes, properties and access modifiers are tools to provide encapsulation in c#.
you do encapsulation in order to reduce complexity.
Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).
Yes, that is a good definition for abstraction.
They are different concepts.
Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.
Yes, they are different concepts. keep in mind that abstraction is actually the opposite of making an object suitable for YOUR domain ONLY. it is in order to make the object suitable for the domain in general!
if you have a actual problem and provide a specific solution, you can use abstraction to formalize a more generic solution that can also solve more problems that have the same common pattern. that way you can increase the re-usability for your components or use components made by other programmers that are made for the same domain, or even for different domains.
good examples are classes provided by the .net framework, for example list or collection. these are very abstract classes that you can use almost everywhere and in a lot of domains. Imagine if .net only implemented a EmployeeList class and a CompanyList that could only hold a list of employees and companies with specific properties. such classes would be useless in a lot of cases. and what a pain would it be if you had to re-implement the whole functionality for a CarList for example. So the "List" is ABSTRACTED away from Employee, Company and Car. The List by itself is an abstract concept that can be implemented by its own class.
Interfaces, abstract classes or inheritance and polymorphism are tools to provide abstraction in c#.
you do abstraction in order to provide reusability.
Image source
Abstraction: is shown in the top left and the top right images of the cat. The surgeon and the old lady designed (or visualized) the animal differently. In the same way, you would put different features in the Cat class, depending upon the need of the application. Every cat has a liver, bladder, heart, and lung, but if you need your cat to 'purr' only, you will abstract your application's cat to the design on top-left rather than the top-right.
Encapsulation: is demonstrated by the cat standing on the table. That's what everyone outside the cat should see the cat as. They need not worry whether the actual implementation of the cat is the top-left one or the top-right one, or even a combination of both.
Another detailed answer here.
I will try to demonstrate Encapsulation and Abstraction in a simple way.. Lets see..
The wrapping up of data and functions into a single unit (called
class) is known as encapsulation. Encapsulation containing and hiding
information about an object, such as internal data structures and
code.
Encapsulation is -
Hiding Complexity,
Binding Data and Function together,
Making Complicated Method's Private,
Making Instance Variable's Private,
Hiding Unnecessary Data and Functions from End User.
Encapsulation implements Abstraction.
And Abstraction is -
Showing Whats Necessary,
Data needs to abstract from End User,
Lets see an example-
The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".
By looking at the Image we can say that we need a Customer Class.
Step - 1: What does my Customer Class needs?
i.e.
2 variables to store Customer Code and Customer Name.
1 Function to Add the Customer Code and Customer Name into Database.
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
Now only ADD method wont work here alone.
Step -2: How will the validation work, ADD Function act?
We will need Database Connection code and Validation Code (Extra Methods).
public bool Validate()
{
//Granular Customer Code and Name
return true;
}
public bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.Validate();
obj.CreateDBObject();
obj.ADD();
}
}
Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.
Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.
So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.
In other words Simplifying Interface to End User is Encapsulation.
So now the complete code looks like as below -
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
private bool Validate()
{
//Granular Customer Code and Name
return true;
}
private bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.ADD();
}
}
Summary :
Step -1: What does my Customer Class needs? is Abstraction.
Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.
P.S. - The code above is hard and fast.
UPDATE:
There is an video on this link to explain the sample:
What is the difference between Abstraction and Encapsulation
Below is a semester long course distilled in a few paragraphs.
Object-Oriented Analysis and Design (OOAD) is actually based on not just two but four principles. They are:
Abstraction: means that you only incorporate those features of an entity which are required in your application. So, if every bank account has an opening date but your application doesn't need to know an account's opening date, then you simply don't add the OpeningDate field in your Object-Oriented Design (of the BankAccount class). †Abstraction in OOAD has nothing to do with abstract classes in OOP.
Per the principle of Abstraction, your entities are an abstraction of what they are in the real world. This way, you design an abstraction of Bank Account down to only that level of detail that is needed by your application.
Inheritance: is more of a coding-trick than an actual principle. It saves you from re-writing those functionalities that you have written somewhere else. However, the thinking is that there must be a relation between the new code you are writing and the old code you are wanting to re-use. Otherwise, nobody prevents you from writing an Animal class which is inheriting from BankAccount, even if it is totally non-sensical.
Just like you may inherit your parents' wealth, you may inherit fields and methods from your parent class. So, taking everything that parent class has and then adding something more if need be, is inheritance. Don't go looking for inheritance in your Object Oriented Design. Inheritance will naturally present itself.
Polymorphism: is a consequence of inheritance. Inheriting a method from the parent is useful, but being able to modify a method if the situation demands, is polymorphism. You may implement a method in the subclass with exactly the same signature as in parent class so that when called, the method from child class is executed. This is the principle of Polymorphism.
Encapsulation: implies bundling the related functionality together and giving access to only the needful. Encapsulation is the basis of meaningful class designing in Object Oriented Design, by:
putting related data and methods together; and,
exposing only the pieces of data and methods relevant for functioning with external entities.
Another simplified answer is here.
† People who argue that "Abstraction of OOAD results in the abstract keyword of OOP"... Well that is incorrect.
Example: When you design a University in an application using object oriented principles, you only design an "abstraction" of the university. Even though there is usually one cash dispensing ATM in almost every university, you may not incorporate that fact if it's not needed for your application. And now though you have designed only an abstraction of the university, you are not required to put abstract in your class declaration. Your abstract design of university will be a normal class in your application.
I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.
For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.
If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.
my 2c
the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).
One example has always been brought up to me in the context of abstraction; the automatic vs. manual transmission on cars. The manual transmission hides some of the workings of changing gears, but you still have to clutch and shift as a driver. Automatic transmission encapsulates all the details of changing gears, i.e. hides it from you, and it is therefore a higher abstraction of the process of changing gears.
Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.
Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.
There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.
Abstraction and Encapsulation are confusing terms and dependent on each other.
Let's take it by an example:
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id;
}
}
When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as
Person p = new Person();
p.CustomName();
Your client doesn't know anything about Id and Name in this function.
Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string LastName {get; set;}
public string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
}
}
Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.
As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.
Abstraction is the class design for itself.
Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.
Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.
I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.
Abstraction is related to "why" I am encapsulating it the first place.
I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."
This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.
I really think that abstracting and encapsulation go together.
Abstraction
In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.
Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.
Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.
Encapsulation:
Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.
If I have individual package one for wine and another one for
chocolate, and if all the classes are declared in the package as
default access modifier, we are giving package level encapsulation
for all classes.
Within a package, if we declare each class filed (member field) as
private and having a public method to access those fields, this way
giving class level encapsulation to those fields
Let's go back 6 million years,
Humans are not fully evolved. To begin with, evolution created a hole next to each body part to inject nutrients, which you can decide on yourself.
However, as humans get older, the nutrient requirements for each body part change Humans don't know which body parts need how much of which nutrient.
Evolution realised that exposing the hole next to each body part was a mistake, so it corrected it by encapsulating the entire body in skin and exposing only one opening, later it was called as "mouth." 
Also, it abstracted the whole implementation of nutrient allocation through digestive system. All you have to do is keep eating through your mouth. The digestive system will take care of the body's nutrient composition changes to meet your needs. 
In the software world, requirements will keep changing.
Encapsulating the internal data and exposing only the required functions will help with better maintenance. As a result, you have greater control over what occurs within your class/module/framework. 
Abstraction makes it easier for the client to consume a class/module/framework. So clients don't have to do(know) 100 different steps to get the desired output. Exposed function/class will do all the work. In our example, you don't have to worry about which nutrients are required for which body part. Just eat it. 

Categories