Encapsulation of modules - c#

I have a concrete idea of a structure but I can't identify any pattern to this. So I guess that I do some thing that I should avoid and do in a different way.
My application will control multiple devices (all of the same type) which have multiple communication interfaces and multiple sensors (it's a simplified example to demonstrate the concept!).
Now, below you can find the example code. Now let's only focus on the "Device" class. This is some kind of a man in the middle that doesn't provide any own functionality but only implements other classes.
This sounds for me like a "Facade". But the difference is that a facade implemenets other classes as private instances and provide functions, where in my example instead I declare the implemented instances as public to let the user access them directly.
Achievement:
The (in my real case high) number of services provided by the "Device" get splitted into specific topics (here e.g. "CommunicationServices" and "MeasurementServices"). This should help the user to gain a better orientation over the code.
So, is there an pattern (which I simply can't identify) that represents this implementation below?
Or would that still be called a "Facade"?
class Application()
{
List<IDevice> _listOfDevices = new List<IDevice>;
readonly Device.Factory _deviceFactory;
Application(Device.Factory df)
{
_deviceFactory = df;
}
void DoSomething()
{
// e.g. instantiate 2 devices
_listOfDevices.Add(_deviceFactory);
_listOfDevices.Add(_deviceFactory);
foreach(IDevice device in _listOfDevices)
{
int temperature = device.MeasurementServices.TemperatureSensor.ReadTemperature();
device.CommunicationServices.Wifi.SendMessage(temperature);
//... and so on
}
}
}
public class Device : IDevice
{
public delegate Device Factory();
public ICommunicationServices CommunicationServices { get; }
public IMeasurementServices MeasurementServices { get; }
public Device (ICommunicationServices comServices, IMeasurementServices measurementServices)
{
CommunicationServices = comServices;
MeasurementServices = measurementServices;
}
}
public class CommunicationServices : ICommunicationServices
{
IBluetooth Bluetooth { get; }
IWifi Wifi { get; }
ISerial Serial { get; }
// ... more interfaces
public CommunicationServices(IBluetooth bt, IWifi wf, ISerial sr)
{
Bluetooth = bt;
Wifi = wf;
Serial = sr;
}
}
public class MeasurementServices : IMeasurementServices
{
ITemperatureSensor TemperatureSensor { get; }
IHumiditySensor HumiditySensor { get; }
// ... more sensors
public MeasurementServices (ITemperatureSensor ts, IHumiditySensor hs)
{
TemperatureSensor = ts;
HumiditySensor = hs;
}
}
Added after receiving the first input:
Mark wrote: "The hierarchy that makes sense to you may not fit the mental model that other people have".
Well this is always going to be a problem, thinking about setting up a data structure on a data server that every one is satisfied with is simply impossible.
So the alternative is to define an accessor for each data of the device in the device's interface?
That would be for example:
// Interface that is going to have a huge number of accessors...
public interface IDevice
{
string Device.GetSsid();
void Device.SetSsid(string ssid);
int Device.GetLoggerInterval();
void Device.SetLoggerInterval(int interval_ms);
// ...
}
Talking in a hirarchy
SSID is part of "CommunicationServices => Wifi => Settings"
Interval is part of "MeasurementSerivces => Logger => Settings"
The issue which I'm concerned about is just represented in this example: the two data "SSID" and "Interval" are very different topics but would appear aside each other. This doesn't really make it easy to learn the code either.
Or what other approaches are out there to face this issue "train wracking" vs. "single huge interface"? Maybe a mix of both (that would be an inconsequent solution)?

Even if you have a clear vision of the structure of the code, it doesn't have to be a design pattern. Some code is just code, and some common code structures are rather antipatterns (or code smells) than patterns.
I agree that this doesn't look like a Facade. If anything, it looks more like a Train Wreck - a code smell. Train Wrecks violate the Law of Demeter. This 'law', however, is controversial:
"I'd prefer it to be called the Occasionally Useful Suggestion of Demeter."
― Martin Fowler
Over the years, I've come to increasingly agree with Martin Fowler that this 'law' may not be all that. The OP, however, asks whether the proposed design fits a particular design pattern. I don't think that it does, but I take the liberty to expand the topic slightly to also include various named design principles.
Whether or not you consider the Law of Demeter a proper design principle, I would challenge that the proposed design meets the stated objective:
This should help the user to gain a better orientation over the code.
I would argue that it does the opposite. The design makes it harder to learn and use the code.
This question is about C# code, and the way that most C# developers interact with an unfamiliar library is via IntelliSense. Given an object device of type Device, they'd typically start typing a dot (.) after device to see what options they have. IntelliSense will give them a GUI (an advanced drop-down control) that enumerates the instance members of Device. (Phil Trelford calls this dot-driven development).
So if you type device. (notice the trailing dot), you'll be presented with a list of other objects:
CommunicationServices
MeasurementServices
etc.
When you're 'dotting into' an object, you're typically looking for some behaviour - a method to invoke. None of the sub-objects are methods, so you're essentially guaranteed that the first dot never produces a useful member.
Users will have to 'dot into' one of the sub-objects to see if the behaviour they're looking for is there. They may, for example, 'dot into' CommunicationServices and type another dot to see if the behaviour they're looking for should hang off of it. If it doesn't, they have to delete the CommunicationServices property access that the IDE just 'helpfully' created for them, and try the next one.
I've worked with APIs like that, and I understand that they're supposed to be helpful, but they're not - they're exasperating.
You should be wary of introducing hierarchies to help people. There's rarely only one single way to model a given problem domain as a hierarchy, and the hierarchy that makes sense to you may not fit the mental model that other people have.
It'd be more helpful to users to present all members directly on Device so that programmers need only 'dot' once.
If you feel that you have too many members on Device this might be another code smell, but I can't tell from the OP.

Related

How to properly build a script architecture in unity C#

I've been writing unity games for some time now using C#. After each game I became more and more experienced, my code changed, I started using best practices.
However, today I have a question: how to build the application architecture correctly?
I don't like that there are a lot of fields in my code that are mixed together with the main logic, I feel that this should not be the case. The solution I have come to so far is to make 2 classes, one contains all the information, and the second implements all the logic, but the class in which all the logic is located becomes dependent on the class with information.
Tell me, more experienced colleagues, what is the right thing to do?
To begin with, try to divide the class that contains logic into smaller parts so that every part only has one responsibility and does one particular thing. Then move these parts into other classes. Try to find a balance when splitting the logic class. Making new class for each method is one extreme, having one class with all the logic is another extreme, the solution is somewhere in the middle. When it's done move on to the next step.
The next step is to name these classes. It might seem easy, but it's really important. Some good examples of naming:
PlayerMover or PlayerMovement, the class which responsibility is to move the player in the chosen direction.
PlayerInput, the class which responsibility is to interact with input and translate it into the language that other components can understand. For example translating keyboard input into Vector3, so PlayerMovement doesn't have to worry about which key was pressed, it only knows where to move, so their responsibilities don't intercept more than necessary.
Tips on naming:
Classes represent entities, so they should be named as entities, it means that their names should be nouns
If giving a name to a class seems hard then the class is most likely formed wrong and has too many responsibilities or doesn't have a whole one
The next step is to separate different layers. Try to make logic independent of UI, so UI can be changed or removed without affecting logic layer. Continuing with the example of player subsystems, make PlayerMovement independent of type of input it uses with abstractions if needed, so it can be keyboard input or joystick input and PlayerMovement doesn't care which one. Also make PlayerInput independent of whether someone uses it or not, for example with properties or events. It will allow to create components once and then use in any project without rewriting everything.
Talking about dividing data from logic, it'll most likely result in having two very similar inheritance hierarchies, so it's better to store the data right where it's used, unlike it's a special case with settings file or big amounts of data.
These are basic tips on this topic and of course building a project architecture is much more complicated than that, but these are great things to start with.
You can continue with Solid (some principles are already mentioned here) and things like Zenject
I get the feeling like you might be looking to incorporate complicated design patterns into your code just because you can, not because it's solving any problems.
You could use interfaces in order to decouple your system classes from your data classes:
public interface IHealth
{
int Current { get; set; }
int Max { get; set; }
}
public class Health : IHealth
{
public int Current { get; set; }
public int Max { get; set; }
}
public class DamageCommand
{
public void Invoke(IHealth health, int amount)
{
health.Current -= amount;
}
}
However, before you go down this route, I'd recommend you first stop and ask yourself if this is offering you any actual tangible benefits to offset the increase in complexity?
Removing dependencies between concrete classes can often be useful for the concrete benefits this can offer, such as making the code more easily unit testable and making it easier to swap a class with another implementation later on. But when we are talking about just pure data objects, how often would you really run into a scenario where you want to swap out the implementation?
If you like keeping your data and systems separate, then I recommend looking into Unity's entity component system (ECS) for a good data-oriented architecture. Or if you want to build your own architecture, still consider using data-oriented design, as this can give a huge boost to performance.

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.

Having trouble with making lots of spells in a game

So I'm having trouble with figuring out a way to implement spells in my game. The problem is that I want to add many spells that are different(like teleportation, telekinesis, fire control etc.). The first thing I tried was making a big class hierarchy like :
Spell -> Passive ->Speed
->Flying
-> Active ->Teleportation
Telekinesis
At the start it seemed good but when I started implementing a lot of spells it started to get messy.
I've searched for other solution and I found about the Entity-Component based system. But I don't think it'll be a good solution.
So do any of you know of any other approach to this problem?
What if you used something like the Strategy Design Pattern and you where to have an interface which defines an method such as ApplySpell() and maybe a Name property and the concrete spell implemented said interface?
That way, for each character, you could iterate over their assigned spells and use the Name property to get the name (maybe you want to list them through a UI or something like that), or maybe store them in a dictionary where the name of the spell is the key, and the actual spell implementation is the value.
What you could do then is that once that the user has selected the spell, all that you need to do is to call ApplySpell() and what the actual spell does is delegated to the class which represents the spell.
In this way, you would not need to worry which spell you need to invoke because everything is being done behind the scenes.
Inheritance is ok, but for properties you can use interfaces or base classes as properties:
class SpellBase
{
public string Name { get; protected set; } // all spells have to have name
public virtual void Animate() { ... } // abstract?
...
}
Then for teleportation
class TeleportationSpell: SpellBase, IEffect
{
... // set name, override Animate() and implement IAreaEffect (as OnSelfEffect() for teleport)
}
interface IEffect
{
public EffectBase Effect {get; set;}
...
}
class EffectBase { ... }
class OnSelfEffect: EffectBase { ... }
class OnTargetEffect: EffectBase { ... }
class OnSelfAndTargetEffect: EffectBase { ... }
Interfaces will make your hierarchy less branchy, but will required more code to implement (which is not really a problem, as you can move common code into methods and call them).
The Entity-Component approch is a good solution for your problem. :)
You should invest more time in understanding it.
You always have to make a decision between "is a" or "have a" relationship.
Where "is a" means inheritance and "have a" means composition.
The thing on EntityComponents is to put every game object attribute into a component class and then just put these components together. You could create every combination of properties without or less code changes (depending on the implementation).
With using that approch it's also easy to create a multiplayer game, because you have just a few places in your code to put the communication stuff.
The other side is you will have a lot of classes and everything is highly decoupled. In general that's a plus and what we want as OO developers.
But for a new developer or a developer with not that high skills, this could be horrible to read.
So i would advise you to choose the entity component approach, because your game will be easier to extend in the future.
Instead of creating multiple classes for each type of magic, just start casing them all in one Magic class and handle them from there as per a trigger?
switch(castID) {
default:
break;
case 1: //air strike
Spell AirStrike = new Spell('AirStrike');
break;
case 2:
...
}
And then have a class for Spell and handle each spell in there based on params sent

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. 

What is the name of this bad practice / anti-pattern?

I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.

Categories