Advantages of OOP [duplicate] - oop

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What's the point of OOP?
What are the advantages of using object-orientated programming over function-orientated.
As a trivial example consider:
struct vector_t {
int x, y, z;
}
void setVector(vector_t *vector, int _x, int _y, it _z) {
vector->x = _x;
vector->y = _y;
vector->z = _z;
}
vector_t addVector(vector_t* vec1, vector_t* vec2) {
vector_t vec3;
vec3.x = vec1->x + vec2->x;
// and so on...
return vec3;
}
Now, I am not incredibly familiar with object-orientated programming, but the above would translate to OOP as:
class vector_t {
private:
int x, y, z;
public:
void set(int _x, int _y, int _z) { ... };
int getX() { return x; }
// ...
void addVector(vector_t *vec) { ... };
// ...
};
My question is this? What really makes the second code example so prefered over the first in modern programming? What are the advantages and disadvantages?

Your first code snippet is actually an example of a poor man's OO implementation in a non-OO language. You're defining an abstract data type (vector_t) and all the operations allowed on it (setVector, addVector, etc), but you're not encapsulating all the data and operations into a single logical unit (i.e. a class). This can be useful if you want or need to use C instead of C++ but still want to have some of the benefits of OOP.
Since you're already doing OOP in both examples, I think it should be obvious why the second code snippet is better.

Related

What's the most efficient way to access specific, related member variables via a single function call?

I'm trying to utilize a single function call to access multiple data members of a class called "Data." In this particular instance, I'm accessing the data fed to the class from a physical gyroscope sensor. This is what I've got:
template <typename T>
T Data<T>::getGyro_euler(char c)
{
switch (c)
{
case 'x': return m_eulerX;
case 'y': return m_eulerY;
case 'z': return m_eulerZ;
default: return 0;
}
}
The data type this function uses is always either a float or a double.
Performance is more important than clarity in this case, as this is running on an already-overburdened Arduino that needs to perform mission-critical tasks, but something just feels kind of dirty about manually passing a character to a function to get a certain variable out of it.
I've got a number of functions like this with quite a number of variables that need to be passed, so having a getter function for each variable would get quite hefty in the code.
Is there a more efficient way of doing this? Is there a better, more clear way to accomplish the same thing without sacrificing performance?
You probably named your class Data for a reason : it is (or at least should be) plain data. Don't make it a class, make it a structure, or better yet, a POD type.
That way you can access any member you want just by typing its name after a dot : data.eulerX. As a bonus, you get no performance issue, more clarity and better readability.
In my opinion your approach is too complicated for the problem you describe.
As others mentioned in the comment accessing fields would be sufficient. You could choose to group together fields that are meant to be used together to improve the readability of your code using for instance std::tuple.
Below an incomplete example (as I don't know how the data is collected).
The performance cost is not related to the number of line of code, but more to the complexity the code involve (for instance here there won't be a need for a switch occuring at runtime); for the trivial types (double) described in the question I don't think it will be an issue.
#include <tuple>
struct giroData
{
private:
double sensorX;
double sensorY;
double sensorZ;
// or
std::tuple<double, double, double> sensor;
public :
double getSensorX() { return sensorX; }
double getSensorY() { return sensorY; }
double getSensorZ() { return sensorZ; }
std::tuple<double, double, double> getSensor() { return sensor; }
};
int main()
{
double x, y, z;
giroData d;
x = d.getSensorX();
y = d.getSensorY();
z = d.getSensorZ();
// or
std::tie(x, y, z) = d.getSensor();
}

OOP - How this relationship could be done in Object-Oriented Programming

Suppose there is a class A and it has many instances from class B, and in A, it will have some shared attributes for B to access. Simply I can write this type, I just want to know if there are any pattern or some other good way to make this relationship in OOP.
My idea is straightforward :
class A {
protected int shared;
public List<B> bList;
int getShared ()
{
return shared;
}
}
class B {
protected A _a;
B (A a) {
this._a = a;
}
void hello () {
print (this._a.getShared());
}
}
As I am pretty much a novice in OOP, so I think maybe there some pattern can do this better, looking forward your ideas. Thanks.
Your code is looking like Mediator pattern. Except that classically Mediator (A class) has a set of different objects for interacting with or between them without explicit references.

Should C++/CLI data members be handles or values?

I'm new to C++/CLI and I'm wondering what is "best practice" regarding managed type data members. Declaring as handle:
public ref class A {
public:
A() : myList(gcnew List<int>()) {}
private:
List<int>^ myList;
};
or as a value:
public ref class B {
private:
List<int> myList;
};
Can't seem to find definitive advice on this.
When writing managed C++ code, I'm in favor of following the conventions used by the other managed languages. Therefore, I'd go with handles for class-level data members, and only use values (stack semantics) where you'd use a using statement in C#.
If your class member is a value, then replacing the object entirely means that the object would need a copy constructor defined, and not many .NET classes do. Also, if you want to pass the object to another method, you'll need to use the % operator to convert from List<int> to List<int>^. (Not a big deal to type %, but easy to forget, and the compiler error just says it can't convert List<int> to List<int>^.)
//Example of the `%` operator
void CSharpMethodThatDoesSomethingWithAList(List<int>^ list) { }
List<int> valueList;
CSharpMethodThatDoesSomethingWithAList(%valueList);
List<int>^ handleList = gcnew List<int>();
CSharpMethodThatDoesSomethingWithAList(handleList);
It all depends on the lifetime. When you have a private member which lives exactly as long as the owning class, the second form is preferable.
Personally, I would use the second form. I say this because I use frameworks that are written by other teams of people, and they use this form.
I believe this is because it is cleaner, uses less space, and is easier for the non-author to read. I try to keep in mind that the most concise code, while still being readable by someone with minimal knowledge of the project is best.
Also, I have not encountered any problems with the latter example in terms of readability across header files, methods, classes, or data files ...etc
Though I'm FAR from an expert in the matter, that is what I prefer. Makes more sense to me.
class AlgoCompSelector : public TSelector {
public :
AlgoCompSelector( TTree *tree = 0 );
virtual ~AlgoCompSelector(){ /* */ };
virtual void Init(TTree *tree);
virtual void SlaveBegin(TTree *tree);
virtual Bool_t Process(Long64_t entry);
virtual void Terminate();
virtual Int_t Version() const { return 1; }
void setAlgo( Int_t idx, const Char_t *name, TTree* part2, TTree* part3 );
void setPTthres( Float_t val );
void setEthres( Float_t val );
private:
std::string mAlgoName[2]; // use this for the axis labels and/or legend labels.
TTree *mPart1;
TTree *mPart2[2], *mPart3[2]; // pointers to TTrees of the various parts
TBranch *mPhotonBranch[2]; // Used branches
TClonesArray *mPhotonArray[2]; // To point to the array in the tree
for example

How the best technique to deal with objects inside objects without reducing performance?

I have classes with many properties, which consists, in some cases, other complex classes. Not allways I'm going to use this complete schemas, but sometimes I'm doing so. What's the best practice to create an object, deal with it and then retrieve information on demand?
I'm giving an very simple example to clarify:
Supose a class student which is related to a class professor. This class is related to other classes like classes, schedules, etc. Not allways I will need to use all this information.
Ough I to mantain the professor's ID in object student and then load the information when I need? Should I create a property just for storing the professorID, or I create a new professor object without loading all other data into it, just storing the ID? Or neither? What's the best practice?
Thanks.
Use the lazy loading pattern.
Suggestion 1
Does your application requires to save & load the values of the objects & properties ( also known as "to serialize" or "to persist" ) ?
Does your application requires to have several instances of the same class ?
If the answer to this questions is true, seems you need to store your data in a D.B., as #larsmans suggest.
Suggestion 2
Another thing. You didn't mention what programming language are you using. In programming languages like C++, Delphi (Object Pascal), D, an object inside another object can be handled in 2 ways: as part of the object, or as a pointer to the subobject.
I suggest use pointers to objects approach, for your scenario.
In programming languages like Java, PHP, C#, VB.NET, there is this concept called references, which in practical terms, its the same as pointer to objects, so you don't need to do anything else.
Non pointer example:
class SubClass
{
public:
int X;
int Y;
}; // class SubClass
class MainClass
{
public:
int Color;
SubClass SubObject;
public:
/* constructor */ MainClass()
{
this.Color = 7;
this.SubObject();
} // /* constructor */ MainClass(...)
/* destructor */ ~MainClass()
{
this.~SubObject();
this.Color = 0;
} // /* destructor */ MainClass(...)
}; // class MainClass
void main()
{
MainClass* MainObject = new MainClass();
MainObject->Color = 5;
MainObject->SubObject.X = 19;
MainObject->SubObject.Y = 32;
delete MainObject();
} // void main(...)
Pointer to objects example:
class SubClass
{
public:
int X;
int Y;
}; // class SubClass
class MainClass
{
public:
int Color;
SubClass* SubObject;
public:
/* constructor */ MainClass()
{
this.Color = 7;
this.SubObject = new SubClass();
} // /* constructor */ MainClass(...)
/* destructor */ ~MainClass()
{
delete this.SubObject();
this.Color = 0;
} // /* destructor */ MainClass(...)
}; // class MainClass
void main()
{
MainClass* MainObject = new MainClass();
MainObject->Color = 5;
MainObject->SubObject->X = 19;
MainObject->SubObject->Y = 32;
delete MainObject();
} // void main(...)
Cheers.
In the general case, you will need some entities joining the entities from your domain. Say, you will have a StudentRegistry that will hold the correspondence between the students and their professors/lecturers. This indeed resembles an RDBMS schema design, so you can refer to the ER DB design method (obviously, you will have classes instead of tables.)
It sounds like you are describing lazy loading.

What are good examples to get a feeling of a languages OO features and constructs?

I have been searching for short and good examples to demonstrate OO features of a language as an introduction to fellow programmers. By "good", I mean, they can be run and output something rather meaningful not foobar stuff.
For instance, you can demonstrate most control flow constructs by a mandelbrot set example or functional aspects by a mergesort example. But I have yet to find a good example for OO constructs.
One "real world" example that's pretty straightforward to understand is the java.io.InputStream class and it's children. This is a decent example of polymorphism: if you write your code to understand how to use InputStream, it doesn't matter how the underlying class works, as long as it conforms to the contract imposed by InputStream. So, you can have a method in some class
public void dump(InputStream in) throws IOException {
int b;
while((b = in.read()) >= 0) {
System.out.println(b);
}
}
This method doesn't care where the data comes from.
Now, if you want to use the dump method with data from a file, you can call
dump(new FileInputStream("file"));
or, if you want to use dump with data from a socket,
dump(socket.getInputStream());
or, if you have a byte array, you can call
dump(new ByteArrayInputStream(theArray));
There are implementations if InputStream that wrap other InputStreams. For example, SequenceInputStream lets you glom multiple InputStreams into one:
dump(new SequenceInputStream(new FileInputStream("file1"),
new FileInputStream("file2"));
If you want to create your own, custom InputStream, you can extend the InputStream class, and override the int read() method:
public class ZerosInputStream extends InputStream {
protected int howManyZeros;
protected int index = 0;
public ZerosInputStream(int howManyZeros) {
this.howManyZeros = howManyZeros;
}
#Override
public int read() throws IOException {
if(index < howManyZeros) {
index++;
return 0;
} else {
return -1;
}
}
Then you can use that in your dump call:
dump(new ZerosInputStream(500));