Class Methods: Passing private data fields in private methods - oop

I was wondering if which of the following patterns are considered to be more "correct".
The first example sets the value of private data member length by calling a void member function that implicitly takes arguments.
The second example sets the value of length by assigning it to the return value of the member function that explicitly takes an argument.
It seems that the second method makes the code clearer, since you know when and how the private member is getting set,
where the first requires a trace of the code to verify what and how a value is being assigned. The second method
also seems like it would allow for better reuse down the road because it could operate in any class/context (since the
arguments and return type are explicit).
The first method is quicker, and if used throughout the entire class (for private member functions) can save some coding, however I'm
not sure if this will bite me down the road ?
Thank you for the insight and clearing this up for me.
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
calculateLength();
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private void calculateLength()
{
int i = 0;
while(content[i++] != NULL) {} // i know, buffer overflow...
length = i;
}
}
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
length = calculateLength(content);
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private int calculateLength(string s)
{
int i = 0;
while(s[i++] != NULL) {}
return i;
}
}

In terms of readability and flexibility the second example wins out.
The advantage to using the second example is that you are essentially just delegating some work in the constructor to a method. This is easy to read and won't easily break in the future if, for instance, someone calls the private calculateLength() method without expecting the instance variables to change.
In the first example the calculateLength() method is operating on the member variables in a non-transparent way to the constructor which makes it less readable and more prone to be brittle in the way described above.

I would say the second is more appropriate, but the first works.
Usually getters are public, anywhere within a class you can access a private variable, doesn't make sense to have a getter that gets a private or protected variable in the same class. If it were protected and you could pass functionality to subclasses of your class.
It depends on what you want to do with the variable. If the value isn't going to change, I would just move the private calculateLength() method to the constructor. If you have to recalculate it then I guess I can see either the void or private doing pretty much the same thing. I feel that the second is clearer because you know exactly where the calculateLength() method is returning, but in the first it it is ambiguous to whether it is doing anything at all. It's better style to do the second.

Why not embed the getLength() function content into the constructor, and do the copying simultaneously? You will save yourself another loop.
Other than that, I am pretty sure it does not matter much. Just go with the flow, start with a method, and then modify in the future if you see fit.

Related

How to change the value of a global variable in a function while there is a local variable of same name in C#

I want to change the global variable in a function where a local variable of same is already present.
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int x)
{
x=7; //here i want that this statement assigns the value 7 to the global x
}
Just qualify it with this. It's a pretty common pattern, particularly for constructors:
public class Player
{
private readonly string name;
public Player(string name)
{
this.name = name;
}
}
While I view it as acceptable if your parameter really is meant to be a new value for the field (potentially in a method which creates a new instance based on the current one and the new value for the single field, for example), I would try to avoid it in general, just from a readability perspective. Of course, the names of your private fields are an implementation detail, but when reading the code for the method, it's confusing to have two different concepts represented by the same variable name.
Rename the local parameter value.
Like Yuriy Vikulov said.
this.x for non-static variables
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int lx)
{
x=7; //if you want 7
x=lx; //if you want the paramValue
}
this.x for non-static classes
NameClass.x for static variables

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

code in the middle is different, everything else the same

I often have a situation where I need to do:
function a1() {
a = getA;
b = getB;
b.doStuff();
.... // do some things
b.send()
return a - b;
}
function a2() {
a = getA;
b = getB;
b.doStuff();
.... // do some things, but different to above
b.send()
return a - b;
}
I feel like I am repeating myself, yet where I have ...., the methods are different, have different signatures, etc..
What do people normally do? Add an if (this type) do this stuff, else do the other stuff that is different? It doesn't seem like a very good solution either.
Polymorphism and possibly abstraction and encapsulation are your friends here.
You should specify better what kind of instructions you have on the .... // do some things part. If you're always using the same information, but doing different things with it, the solution is fairly easy using simple polymorphism. See my first revision of this answer. I'll assume you need different information to do the specific tasks in each case.
You also didn't specify if those functions are in the same class/module or not. If they are not, you can use inheritance to share the common parts and polymorphism to introduce different behavior in the specific part. If they are in the same class you don't need inheritance nor polymorphism.
In different classes
Taking into account you're stating in the question that you might need to make calls to functions with different signature depending on the implementation subclass (for instance, passing a or b as parameter depending on the case), and assuming you need to do something with the intermediate local variables (i.e. a and b) in the specific implementations:
Short version: Polymorphism+Encapsulation: Pass all the possible in & out parameters that every subclass might need to the abstract function. Might be less painful if you encapsulate them in an object.
Long Version
I'd store intermediate state in generic class' member, and pass it to the implementation methods. Alternatively you could grab the State from the implementation methods instead of passing it as an argument. Then, you can make two subclasses of it implementing the doSpecificStuff(State) method, and grabbing the needed parameters from the intermediate state in the superclass. If needed by the superclass, subclasses might also modify state.
(Java specifics next, sorry)
public abstract class Generic {
private State state = new State();
public void a() {
preProcess();
prepareState();
doSpecificStuf(state);
clearState();
return postProcess();
}
protected void preProcess(){
a = getA;
b = getB;
b.doStuff();
}
protected Object postProcess(){
b.send()
return a - b;
}
protected void prepareState(){
state.prepareState(a,b);
}
private void clearState() {
state.clear();
}
protected abstract doSpecificStuf(State state);
}
public class Specific extends Generic {
protected doSpecificStuf(State state) {
state.getA().doThings();
state.setB(someCalculation);
}
}
public class Specific2 extends Generic {
protected doSpecificStuf(State state) {
state.getB().doThings();
}
}
In the same class
Another possibility would be making the preProcess() method return a State variable, and use it inthe implementations of a1() and a2().
public class MyClass {
protected State preProcess(){
a = getA;
b = getB;
b.doStuff();
return new State(a,b);
}
protected Object postProcess(){
b.send()
return a - b;
}
public void a1(){
State st = preProcess();
st.getA().doThings();
State.clear(st);
return postProcess();
}
public void a2(){
State st = preProcess();
st.getB().doThings();
State.clear(st);
return postProcess();
}
}
Well, don't repeat yourself. My golden rule (which admittedly I break from time on time) is based on the ZOI rule: all code must live exactly zero, one or infinite times. If you see code repeated, you should refactor that into a common ancestor.
That said, it is not possible to give you a definite answer how to refactor your code; there are infinite ways to do this. For example, if a1() and a2() reside in different classes then you can use polymorphism. If they live in the same class, you can create a function that receives an anonymous function as parameter and then a1() and a2() are just wrappers to that function. Using a (shudder) parameter to change the function behavior can be used, too.
You can solve this in one of 2 ways. Both a1 and a2 will call a3. a3 will do the shared code, and:
1. call a function that it receives as a parameter, which does either the middle part of a1 or the middle part of a2 (and they will pass the correct parameter),
- or -
2. receive a flag (e.g. boolean), which will tell it which part it needs to do, and using an if statement will execute the correct code.
This screams out loud for the design pattern "Template Method"
The general part is in the super class:
package patterns.templatemethod;
public abstract class AbstractSuper {
public Integer doTheStuff(Integer a, Integer b) {
Integer x = b.intValue() + a.intValue();
Integer y = doSpecificStuff(x);
return b.intValue() * y;
}
protected abstract Integer doSpecificStuff(Integer x);
}
The spezific part is in the subclass:
package patterns.templatemethod;
public class ConcreteA extends AbstractSuper {
#Override
protected Integer doSpecificStuff(Integer x) {
return x.intValue() * x.intValue();
}
}
For every spezific solution you implement a subclass, with the specific behavior.
If you put them all in an Collection, you can iterate over them and call always the common method and evry class does it's magic. ;)
hope this helps

c++/cli reference to property

Well, I haven't yet found something that says this is impossible, though I'm starting to think it might be. Can you make this work?
using namespace System;
template <typename T>
void unset(Nullable<T>& var) { var = Nullable<T>(); }
void unset(String^% var) { var=nullptr; }
//this is really a C# class in my situation, so I can't change its types
public ref class Foo
{
public:
property Nullable<Decimal> Dec;
property Nullable<int> Num;
property String^ Str;
};
int main()
{
Foo^ foo = gcnew Foo;
foo->Dec = Decimal(1.2);
foo->Num = 3;
foo->Str = "hi";
unset(foo->Dec);
unset(foo->Num);
unset(foo->Str);
Console::WriteLine(foo->Dec);
Console::WriteLine(foo->Num);
Console::WriteLine(foo->Str);
}
Update: unset is called from a code-generating macro which is called on about 50 params. I'd prefer not to have to go make varieties of the macro for each type.
It isn't possible. Setting a property requires calling the property setter function. There is no way to guess for the called method that it needs to call a function vs can assign the passed variable pointer. If you really want to do this then pass a delegate.
There is actually one .NET language that supports it, VB.NET generates code like this:
T temp = obj->prop;
func(temp)
obj->prop = temp;
There is however a dreadful aliasing problem with that, quite undebuggable. This goes belly up in the (rare) case where func() also uses the property. This is otherwise the way you'd work around the limitation, explicitly in your own code.
Beware that your code is wrong, possibly intentional, you are passing a C++ & reference, not a managed % interior pointer. The compiler is going to bitch about that, you can't create references or pointers to managed objects. They move. Unless the reference is to a variable on the stack. It doesn't otherwise change the answer.
For those who may end up here wondering how I got on with this, I ended up being lucky that the class I was working with was an LLBLGen Entity, so I was able to replace
unset(re->var);
with
{ SD::LLBLGen::Pro::ORMSupportClasses::IEntityField2^ f = re->Fields[#var]; \
if (f->IsNullable) \
f->CurrentValue = nullptr; }

Declaration of variables?

Case:1
class A
{
private int i=0;
public void display()
{
this.getValue();
}
private int getValue()
{
return i+2;
}
}
Case:2
class B
{
public void display()
{
int i=0;
this. getValue(i);
}
private int getValue(int i)
{
return i+2;
}
}
Does the declaration of "i" in both cases have any great
difference (other than the global access) whenever I call
display() ?
In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.
Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.
Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.
In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.
But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)
In first case i exists outside of any method
In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.