Monday, February 2, 2009

Weekly Source Code: Default Controlling Access - Be Careful!

I've a general rule where I never assume defaults in a language, I always assign an initial value to a variable for example... assuming defaults caused alot of problems for me in the past expecially in languages like C or C++ where defaults can actually "hurt" you. Each language also has a diffirent default behaviour that you will see below with Java vs C#.

One of the rules is to always provide the control access level modifier in OOP languages like Java and C# (the 2x languages that I use alot).

For example:

According to the Java tutorial on Controlling Access to Members of a Class when you don't provide an access level modifier it assumes the class and package level access only. Class access is fine since you do want a member variable to be avialable in its containing class but package level access is where it can hurt you, for example:

package com.echosystem.core;

public class SystemCall
int status = 0;
// rest of the class continue

here if you've other classes in the com.echosystem.core package those classes can directly access the status member variable above so you're not following OOP rules where encaptulation is important - not to go into too much detail but encaptulation is good! Also if you've another class in another package location you will notice that you can't access this status member variable.

Its important in this case to write the above code as:

public class SystemCall
private int status = 0;

public int getStatus()
return status;

public void setStatus(int inStatus)
status = inStatus;

// rest of the class continue

Here you see that the status member variable is private (make it encaptulated into the class) and you control access to it using a getter and setter methods.

C# will continue in the next weekly source code - I do need to give you time to think about this hey! :-)


fugufoo said...

I understand all PHP variables have global scope, and one cannot have two variables of the same name in one project?

Not that it's good practice anyway - but still pretty scary.

Lennie De Villiers said...

Well it make sense not to have two variables with the same name since a) you will end up not knowing the type of the variable since PHP get the type from the value assigned to it e.g. $name = "Lennie"... then later on you might say again: $name = 5; oops!

Also global scope yes but that is bad, if you look at the C programming language - all variables are also global scope and you can access then from another source file/header BAD!!

I would say the rules in this case is:

1) always have unique names
2) never change variable types, only stick to a type
3) don't have globals but use local scope