Encapsulation concept - encapsulation

I have problem with concept and implementation of encapsulation.
Can someone explain it to me?

Encapsulation is a moderately easy concept once you realise it (probably) comes from the same base word as capsule.
It's simply a containment of information.
Encapsulation means that a class publishes only what is needed for others to use it, and no more. This is called information hiding and it means classes can totally change their internals without having an effect on any of their users.
In other words, a dictionary class can begin life as a simple array and progress to a binary tree of words then even maybe to some database access functions, all without changing the interface to it.
In an object oriented world, objects hold both their data and the methods used to manipulate data and that is the pinnacle of encapsulation. One way this is done is to make sure each object knows which functions to call to manipulate its data, and ensure the correct ones are called.
As an example, here's a class for maintaining integer lists in my mythical, but strangely Python-like and therefore hopefully easy to understand, language:
class intlist:
private int val[10] # Slots for storing numbers.
private bool used[10] # Whether slot is used or not.
public constructor:
# Mark all slots unused.
for i in 0..9:
used[i] = false
public function add(int v) throws out-of-memory:
# Check each slot.
for i in 0..9:
# If unused, store value, mark used, return.
if not used[i]:
used[i] = true
val[i] = v
return
# No free slots, so throw exception.
throw out-of-memory
public function del(int v) throws bad-value:
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
# Mark unused and return.
used[i] = false
return
# Value not found in any used slot, throw exception.
throw bad-value
public function has(int v):
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
return true
# Value not found in any used slot.
return false
Now the only information published here are the constructor and three functions for adding, deleting, and checking for values (including what exceptions can be thrown).
Callers need know nothing about the internal data structures being used (val and used), or the properties of the functions beyond their "signatures" (the content of the "function" lines).
Because everything else is encapsulated, it can changed it at will without breaking the code that uses it.
I could, for example, do any of the following:
make the arrays longer;
store the data sorted, or in a binary tree instead of an array to make it faster.
change the used array into a count array (initialised to zero) so that many occurrences of a single number use just the one slot, increasing the quantity of numbers that can be stored where there are duplicates.
store the numbers in a database, located on a ZX-80 retro-computer located in outback Australia, and powered by methane produced from kangaroo droppings (though you may notice a latency change).
Basically, as long as the published API doesn't change, we am free to do whatever we want. In fact, we can also add things to the API without breaking other code, I just can't delete or change anything that users already rely on.
You should note that encapsulation isn't something new with object orientation. It's been around for ages, even in C by ensuring that information is hidden within a module (usually a source file or group thereof with private headers).
In fact, the stdio.h FILE* stuff is a good example of this. You don't care what's actually behind the pointer since all the functions which use it know how to do their stuff.

link text
I always explain it to people is think of yourself as an object. Other people can see your height, they can see if your smiling, but your inner thoughts, maybe the reason while your smiling, only you know.

Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.
The beauty of encapsulation is the power of changing things without affecting its users.
In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).
Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.
The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.
There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:
You can limit the values that can be stored in a field (i.e. gender must be F or M).
You can take actions when the field is modified (trigger event, validate, etc).
You can provide thread safety by synchronizing the method.
You can switch to a new data representation (i.e. calculated fields, different data type)
However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.
The Beauty of Encapsulation
Now, in my opinion, to really understand encapsulation, one must first understand abstraction.
Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a break system, a fuel system, etc.
However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.
However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users where interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.
Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.
So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.
I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.

Encapsulation - wrapping of data in single unit. also we can say hiding the information of essential details.
example
You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.
hide/bind something : eg: a capsule (which we consume when v r ill)hide/bind some powder form in itself,, means that capsule encapsulate the powder contained it.
Binding of data and behavior i.e functionality of an object in a secured and controlled manner.
or the best example of encapsulation is a CLASS because a class hides class variables/functions from outside d class..
Encapsulation:
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Eg: we can consider a capsule. Encapsulation means hiding the internal details of an object, i.e. how an object does something. Here capsule is a single Unit contain many things. But we cant see what is there in side capsule.
This is the technique used to protect information about an object from other objects. Like variable we can set as private and property as Public. When we access the property then we validate and set it.
We can go through some other examples. Our Laptop. We can use Laptop but what operations are happening inside that we are not knowing. But we can use that. Same like mobile, TV etc.
We can conclude that a group of related properties, methods, and other members are treated as a single unit or object.An encapsulated object is often called an abstract data type.
There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
//Declare as Private
private string _LegName;
// Property Set as public
public string LegName
{
get
{
return _LegName;
}
set
{
_LegName=value;
}
public class LegMain
{
public static int Main(string[] args)
{
Leg L= new Leg();
d.LegName="Right Leg";
Console.WriteLine("The Legis :{0}",d.LegName);return 0;
}
}
Note: Encapsulation provides a way to protect data from accidental corruption.
Thank you

Encapsulation means hiding the data. In other words a class only exposes those properties or information which is authorized to be seen. Consider the below exapmle where a certain property called ConfidentialMessage is accesible only to the Admin role. This property is made private and is returned through another method which checks the role of an user and return the message only for admin.
public class Message
{
public Message()
{
ConfidentialMessage = "I am Nemo";
}
private string ConfidentialMessage { get; set; }
public string GetMessage(string name)
{
string message = string.Empty;
if (name == "Admin")
{
message = this.ConfidentialMessage;
}
return message;
}
}

Putting definition of encapsulate
enclose in a capsule, from en- "make, put in" + capsule + -ate .
now capsule meaning is box, case
In real life example if you put things on desk open then it is accessible to anyone but if you put in case then it is accessible with the key of case to open.
Same way in class if you create a variable then it accessible whenever you create object of that class.But if you create function to access the variable then you have created case and function is key to access the variable.
So in programming language we are creating wrapper of the data by using getter and setter and making it private variable.

Encapsulation is a capsule, consider it to be a class enclosing or hiding fields, properties and functions.
Please check below url encapsulation is simplified with simple programming example.
http://itsforlavanya.blogspot.com/2020/08/encapsulation.html?m=1

Related

Is it bad programming practice to store objects of type Foo into a static array of type Foo belonging to Foo in their construction?

Say I wanted to store objects statically inside their own class. Like this:
public class Foo
{
private static int instance_id = 0;
public static List<Foo> instances = new List<Foo>();
public Foo()
{
instances[instance_id++] = this;
}
}
Why?
I don't need to create unique array structures outside the class (one will do).
I want to map each object to a unique id according to their time of birth.
I will only have one thread with the class in use. Foo will only exist as one set in the program.
I did searching, but could find no mention of this data structure. Is this bad practice? If so, why? Thank you.
{please note, this question is not specific to any language}
There are a couple of potential problems I can see with this setup.
First, since you only have a single array of objects, if you need to update the code so that you have lots of different groups of objects in different contexts, you'll need to do a significant rewrite so that each object ends up getting associated with a different context. Depending on your setup this may not be a problem, but I suspect that in the long term this decision may come back to haunt you.
Second, this approach assumes that you never need to dispose of any objects. Imagine that you want to update your code so that you do a number of different simulations and aggregate the results. If you do this, then you'll end up having your giant array storing pointers to objects you're not using. This means that you'll (1) have a memory leak and (2) have to update all your looping code to skip over objects you no longer care about.
Third, this approach makes it the responsibility of the class, rather than the client, to keep track of all the instances. In some sense, if the purpose of what you're doing is to make it easier for clients to have access to a global list of all the objects that exist, you may want to consider just putting a different list somewhere else that's globally accessible so that the objects themselves aren't the ones responsible for keeping track of themselves.
I would recommend using one of a number of alternate approaches:
Just have the client do this. If the client needs to keep track of all the instances, just have them always create the array they need and populate it. That way, if multiple clients need different arrays, they can do so. You also avoid the memory leak issues if you do this properly.
Have each object take, as part of its constructor, a context in which to be constructed. For example, if all of these objects are nodes in a quadtree, have them take a pointer to the quadtree in which they'll live as a constructor parameter, then have the quadtree object store the list of the nodes in it. After all, it seems like it's really the quadtree's responsibility to keep track of everything.
Keep doing what you're doing, but using something with weak references. For example, you might consider using some variation on a WeakHashMap so that you do store everything, but if the objects are no longer needed, you at least don't have a memory leak.

Immutable data model for an WPF application with MVVM implementation

I have an application which has a data tree as a databackend. To implement the the MVVM pattern I have a logic layer of classes which encapsulate the data tree. Therefore the logic also is arranged in a tree. If the input is in a valid state the data should be copied to a second thread which works as a double buffer of the last valid state. Therefore one way would be cloning.
Another approach would be to implement the complete data backend to be immutable. This would imply to rebuild the whole data tree if something new is entered. My question is, is there a practical way to do this? I'm stuck at the point where I have to reassign the data tree efficently to the logic layer.
**UPDATE - Some Code
What we are doing is to abstract hardware devices which we use to run our experiments. Therefore we defined classes like "chassis, sequence, card, channel, step". Those build a tree structure like this:
Chassis
/ \
Sequence1 Sequence2
/ | \
Card1 Card2 Card3
/ \
Channel1 Channel2
/ \
Step1 Step2
In code it looks like this:
public class Chassis{
readonly var List<Sequence> Sequences = new List<Sequence>();
}
public class Sequence{
readonly var List<Card> Cards = new List<Card>();
}
and so on. Of course each class has some more properties but those are easy to handle. My Problem now is that List is a mutable object. I can call List.Add() and it changed. Ok there is a ReadOnlyList but I'm not sure if it implements the immutability the right way. Right as in copy by value not reference and not just blocking to write to it by blocking the set methods.
The next problem is that the amount of sequences and step can vary. For this reason I need an atomic exchange of list elements.
At the moment I don't have any more code as I'm still thinking if this way would help me and if it is possible at all to implement it in a reasonable amount of time.
Note that there are new immutable collections for .NET that could help you achieve your goal.
Be very cautious about Dave Turvey's statement (I would downvote/comment if I could):
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
This is incorrect. The private member could still be changed by its container class. The public member could be cast to List<T>, IList<T>, or ICollection<T> without throwing an exception. Thus anything that depends on the immutability of the public IEnumerable<T> could break.
I'm not sure if I understand 100% what you're asking. It sounds like you have a tree of objects in a particular state and you want to perform some processing on a copy of that without modifying the original object state. You should look into cloning via a "Deep Copy". This question should get you started.
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
public class Chassis
{
List<Sequence> _sequences = new List<Sequence>();
public IEnumerable<Sequence> Sequences { get { return _sequences; } }
}
18/04/13 Update in response to Brandon Bonds comments
The library linked in Brandon Bonds answer is certainly interesting and offers advantages over IEnumerable<>. In many cases it is probably a better solution. However, there are a couple of caveats that you should be aware of if you use this library.
As of 18/04/2013 This is a beta library. It is obviously still in development and may not be ready for production use. For example, The code sample for list creation in the linked article doesn't work in the current nuget package.
This is a .net 4.5 library. so it will not be suitable for programs targeting an older framework.
It does not guarantee immutability of objects contained in the collections only of the collection itself. It is possible to modify objects in an immutable list You will still need to consider a deep copy for copying collections.
This is addressed in the FAQ at the end of the article
Q: Can I only store immutable data in these immutable collections?
A: You can store all types of data in these collections. The only immutable aspect is the collections themselves, not the items they contain.
In addition the following code sample illustrates this point (using version 1.0.8-beta)
class Data
{
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
var test = ImmutableList.Create<Data>();
test = test.Add(new Data { Value = 1 });
Console.WriteLine(test[0].Value);
test[0].Value = 2;
Console.WriteLine(test[0].Value);
Console.ReadKey();
}
}
This code will allow modification of the Data object and output
1
2
Here are a couple of articles for further reading on this topic
Read only, frozen, and immutable collections
Immutability in C# Part One: Kinds of Immutability

is it wasteful/bad design to use a vector/list where in most instances it will only have one element?

is it wasteful/bad design to use a vector/list where in most instances it will only have one element?
example:
class dragon
{
ArrayList<head> = new ArrayList<head> Heads;
tail Tail = new tail();
body Body = new body();
dragon()
{
theHead=new head();
Heads.add(theHead);
}
void nod()
{
for (int i=0;i<Heads.size();i++)
{
heads.get(i).GoUpAndDown();
}
}
}
class firedragon extends dragon
{
}
class icedragon extends dragon
{
}
class lightningdragon extends dragon
{
}
// 10 other one-headed dragon declarations here
class hydra extends dragon
{
hydra()
{
anotherHead=new head();
for (int i=0;i<2;i++)
{
Heads.add(anotherHead);
}
}
}
class superhydra extends dragon
{
superhydra()
{
anotherHead=new head();
for (int i=0;i<4;i++)
{
Heads.add(anotherHead);
}
}
}
EDIT:(part 2 of the question)
Thanks for the replies. They have been very helpful.
I've actually run into this situation more than once, and I'd like to give a second example that is unrelated to inheritance. This is actually a real-world example, and though I've decided my current project is small scale enough to be safe with using vectors based on your answers, it's a concept that I imagine I'll use on a much larger scale at some point.
In creating an engine for my current Android game project, I found it necessary to create an Imagepoint object that is basically a set of XY coordinates that are used to track significant parts of a sprite image. Say you have a bone character made up of several bitmaps, it's useful to know where the neck attaches to the torso, the forearm to the bicep, etc. This xy offset data is used later to calculate the position for various purposes, such as where to position other sprites by using trigonometric functions to find the xy offset given the current angle.
Most sprite objects will need only one image point. The bicep needs one for the forearm, the forearm needs one for the hand, the neck needs one for the head, etc. The torsos in my current character models are the exception, and they need several for the shoulders, the legs, the neck, and any removable decorative sprites.
The sprite is the object that contains the imagepoint vectors, there will be no inherited classes, because each : torso, leg, etc is simply an instance of the sprite class, which is strictly a graphical object, containing a pointer to the bitmap, these imagepoints, and assorted position/orientation data, and will not be used for any specialized purposes. If I were to use this concept on a large scale game with massive numbers of instances, where most would require only a single imagepoint, with a few objects requiring several or none, and where there would be no special cases meriting the use of inheritance. What would your thoughts be?
Yes and no.
I mean your question really depends on how are you going to use these objects.. personally I like to split behaviours and attributes as much as possible to "clusterize" them according to the kind of object they represent without caring about reusing some code a little bit less compared to a really inheritance approach like the one you proposed. Something like:
interface BigLizard
{
void nod();
}
class Dragon implements BigLizard
{
Head head;
void nod() { head.upAndDown(); }
}
class ReallyScaryDragon extends Dragon { ... }
class Hydra implements BigLizard
{
ArrayList<Head> heads;
void nod() { for (Head h : heads) h.upAndDown(); }
}
And so on. This approach is like "having just exactly what you need for your objects without force anything to be a specific case". Of course this means that it will have two different implementations of nod() but when you don't need to optimize (and you should care about it only at the end) just stick with your personal preference, assuming that it doesn't go against any standard, widely accepted convention.
You don't have to make anything inherit from a single object, just customize the hierarchy as you like.. also a composite solution (like already suggested) would be a solution also if the concept of "head part" is not the same for your Dragon and for your Hydra..
A third solution for your specific case could be to use a LinkedList instead that an ArrayList. In this case whenever you have just one head you won't waste space (except for instantiation of the list) and you'll have just the next pointer of the head (of the list :D ) pointing nowhere.
If the head is publicly accessible, it'll need to be available as an array/list/collection so that consumers can deal with it.
Another way of dealing with this may be to switch to a more behavioral design rather than a stateful design. In other words, instead of having code telling the dragon to nod, have the dragon respond to an event that would cause him to nod, if that makes sense.
say("Dragon, would you like a yummy princess?");
if(dragon.Stomach.Contents.IsEmpty)
{
dragon.Nod();
}
compared with:
say("Dragon, would you like a yummy princess?");
dragon.offerFood(princess);
// in dragon class
void offerFood(Food yummyFood)
{
if(Stomach.Contents.Empty)
{
head.Nod(); // can be overridden by subclasses.
}
}
In the second example, the consumer of the dragon class isn't asserting authority to make the dragon do things... all the consumer is doing is things (saying things, offering a princess) that he has the authority to do - the dragon gets to decide whether it wants to nod its head or not (which makes sense. I doubt that I'd be able to get a dragon to nod its head if it didn't want to!)
I call this 'behavioral' because the interfaces focus on the interactions between the objects (the dragon and whatever is offering the yummy princess) rather than the state of the dragon (its heads).
I don't think there is a single answer to this question. It seems to me like it would be application dependent. If the application is a relatively lightweight dragon simulation that will never deal with more than a few thousand dragons at any one time, then it probably isn't a big deal to use a vector. If, though, it is a game involving millions of dragons, then it might make sense to optimize it slightly differently and maybe save a bit of memory and possibly shorten access time. But even that probably depends on the underlying class implementation. It is quite possible that the vector class you use could be optimized to handle a single element without extra overhead.
In this particular case, it'd probably be better to override nod() for your multi-headed dragons. Whether they have 1 head or 5 is a detail that really shouldn't be worried about in the base class (which should be as simple as you can reasonably make it).
You don't want to have to account for every possibility that every one of your code's users (even you) will ever need at every point in time. Otherwise, you'd need to account for 2-headed dogs (which are a lot more real than even 1-headed dragons). People extending your classes and such will be developers, too; let them do the work to account for the more exotic/bizarre cases, if they need to.
You could change the Head implementation to be a Composite type. That way, each extension of Dragon needs only one instance of Head and the Head takes care of GoUpAndDown().
I would implement such features in deriving classes. To make this behaviour work, you have to be able to override methods (in your case, the nod() method). The baseclass shouldn't cater for all possibilities, it should present the base case, which can be extended. Just make the appropiate methods overrideable, so the deriving classes can implement the specific behaviour, and everything will work out fine.

OOP Best Practices When One Object Needs to Modify Another

(this is a C-like environment) Say I have two instance objects, a car and a bodyShop. The car has a color iVar and corresponding accesors. The bodyShop has a method named "paintCar" that will take in a car object and change its color.
As far as implementation, in order to get the bodyShop to actually be able to change a car object's color, I see two ways to go about it.
Use the "&" operator to pass in a pointer to the car. Then the bodyShop can either tell the car to perform some method that it has to change color, or it can use the car's accessors directly.
Pass in the car object by value, do the same sort of thing to get the color changed, then have the method return a car object with a new color. Then assign the original car object to the new car object.
Option 1 seems more straightforward to me, but I'm wondering if it is in-line with OOP best practices. In general for "maximum OOP", is the "&" operator good or bad? Or, maybe I'm completely missing a better option that would make this super OOPer. Please advise :)
Option 1 is prefered:
The bodyShop can either tell the car
to perform some method that it has to
change color, or it can use the car's
accessors directly.
Even better still...create an IPaintable interface. Have Car implement IPaintable. Have BodyShop depend on IPaintable instead of Car. The benefits of this are:
Now BodyShop can paint anything that implements IPaintable (Cars, Boats, Planes, Scooters)
BodyShop is no longer tightly coupled to Car.
BodyShop has a more testable design.
I would assume that the responsibility of the bodyShop is to modify car objects, so #1 seems like the right way to go to me. I've never used a language where the "&" operator is necessary. Normally, my bodyShop object would call car.setColor(newColor) and that would be that. This way you don't have to worry about the rest of the original car's attributes, including persistence issues - you just leave them alone.
Since you're interested in the best OOP practice, you should ignore the performance hit you get with option 2. The only things you should be interested in is do either option unnecessarily increase coupling between the two classes, is encapsulation violated and is identity preserved.
Given this, option 2 is less desirable since you can't determine which other objects are holding references to the original car or worse, contain the car. In short you violate the identity constraint since two objects in the system may have different ideas of the state of the car. You run the risk of making the overall system inconsistent.
Of-course your particular environment may avoid this but it certainly would be best practice to avoid it.
Last point, does your bodyShop object have state; behaviour and identity? I realise that you have explained only the minimum necessary but possibly the bodyShop isn't really an object.
Functional v OO approaches
As an interesting aside, option 2 would close to the approach in a functional programming environment - since state changes are not allowed, your only approach would be to create a new car if it's colour changed. That's not quite what you're suggesting but it's close.
That may sound like complete overkill but it does have some interesting implications for proving the correctness of the code and parallelism.
Option 1 wins for me. The & operator is implicit in many OO languages (like Java, Python etc). You don't use "passing by value" in that languages often - only primitive types are passed in that way.
Option 2 comes with multiple problems: You might have a collection of cars, and some function unaware of it might send a car to bodyShop for painting, receive new car in return and don't update your collection of cars. See? And from more ideologic point of view - you don't create new object each time you want to modify it in real world - why should you do so in virtual one? This will lead to confusion, because it's just counterintuitive. :-)
I am not sure what this "C-like environment" mean. In C, you need this:
int paintCar(const bodyShop_t *bs, car_t *car);
where you modify the contents pointed by car. For big struct in C, you should always pass the pointer, rather than the value to a function. So, use solution 1 (if by "&" you mean the C operator).
I too agree with the first 1. I can't say it's best practice because i'm never really sure what best practice is in other peoples minds... I can tell you that best practice in my mind is the most simple method that works for the job. I've also seen this aproach taken in the hunspell win api and other c-ish api's that i've had to use. So yea i agree with scott.
http://hunspell.sourceforge.net/
//just in-case your interested in looking at other peoples code
It depends on whether the body shop's method can fail and leave the car in an indeterminate state. In that case, you're better off operating on a copy of the car, or a copy of all relevant attributes of the car. Then, only when the operation succeeds, you copy those values to the car. So you end up assigning the new car to the old car within the body shop method. Doing this correctly is necessary for exception safety in C++, and can get nasty.
It's also possible and sometimes desirable to use the other pattern - returning a new object on modification. This is useful for interactive systems which require Undo/Redo, backtracking search, and for anything involving modelling how a system of objects evolves over time.
In addition to other optinions, option 1 lets paintCar method return a completion code that indicates if the car has changed the color successfully or there were problems with it

Some snarks are boojums: list of boojums, or is_boojum property on all snarks?

The problem domain features a large population of named snarks. Some of the snarks are boojums.
There are at least two ways to model this:
// as a property:
class Snark {
string name;
bool is_boojum;
};
// as a list:
class Snark {
typedef long Id;
Id id;
string name;
};
tree<Snark::Id> boojums;
It seems intuitive that if we determined that snarks come in male and female, we would add a "sex" property to the snark class definition; and if we determined that all but five snarks were vanquished subjects, we would make a list of royals.
Are there principles one can apply, or is it a matter of architectural preference?
What problem are you trying to solve?
If the purpose of recording the royalty of the snarks is to display a crown on their heads in the GUI, then it makes sense for it to merely be an attribute. (Alternatively, there could be a RoyalSnark subclass, with an overridden Render method.)
If the purpose is to quickly find all the royal snarks, then a list is more appropriate - otherwise you would need to look at every snark and check its attribute.
I believe that the information entropy associated with the classification can be a guide to which method to use. Low-entropy classifications (i.e. most of the objects have the same value) suggest a list implementation tracking the exceptional cases, while high-entropy classifications (you cannot make any very good predictions about which classification an object will have) suggest a property implementation.
As a derived class:
class Snark
{
virtual void Approach(Creature& approacher) {};
};
class Boojum : public Snark
{
virtual void Approach(Creature& approacher)
{
approacher.softlySuddenlyVanishAway();
}
};
That natural way to do it seems to be a property in all cases.
You might use a list for performance, or to optimise space. Both reasons strike me as potential cases of premature optimisation, breaking encapsulation, and/or storing redundant data with the consequent risk of lack of integrity (because I should still be able to query the object itself to find out if it is royal - I shouldn't have to know that this property is handled in a special way for reasons of performance). You could I suppose hide the list implementation behind a getter, to make it behave as a property.
Also, if these objects were stored in a DB, the performance issue pretty much goes away as the DB layer can create the list at runtime using a query anyway.
If you're asking about database modeling, then it's most straightforward to treat is_boojum as an attribute column in the table Snarks. If you need to search for all boojums, the query is simple:
SELECT * FROM Snarks WHERE is_boojum = 1
This gives logically correct answers, and it's easy to model. It might not be so speedy, because indexing a column with low selectivity (many rows with identical values) isn't very efficient, and might not benefit from the index at all.
But your question was about modeling, not optimization.
Hmmm. My first thought is that, indeed, Boojum is a subtype of Snark. but the specification seems to argue against it, for "the snark was a boojum, you see." Well, that means the snark is_a Boojum, and that would make the inheritance graph cyclic. Can't have that.
On the other hand, I do'nt think there's any indication that a Snark can become a Boojum; either it's a Boojum or it's not.
I think probably you want a Boojum mixin --
abstract class Snark { /*...*/ };
class PlainSnark extends Snark {/*...*/};
class RoyalSnark extends Snark implements Boojum {/*...*/};

Resources