Why don't oop languages have a 'read only' access modifier? - oop

Every time I write trivial getters (get functions that just return the value of the member) I wonder why don't oop languages simply have a 'read only' access modifier that would allow reading the value of the members of the object but does not allow you to set them just like const things in c++.
The private,protected,public access modifiers gives you either full (read/write) access or no access.
Writing a getter and calling it every time is slow, because function calling is slower than just accessing a member. A good optimizer can optimize these getter calls out but this is 'magic'. And I don't think it is good idea learning how an optimizer of a certain compiler works and write code to exploit it.
So why do we need to write accessors, read only interfaces everywhere in practice when just a new access modifier would do the trick?
ps1: please don't tell things like 'It would break the encapsulation'. A public foo.getX() and a public but read only foo.x would do the same thing.
EDIT: I didn't composed my post clear. Sorry. I mean you can read the member's value outside but you can't set it. You can only set its value inside the class scope.

You're incorrectly generalizing from one or some OOP language(s) you know to OOP languages in general. Some examples of languages that implement read-only attributes:
C# (thanks, Darin and tonio)
Delphi (= Object Pascal)
Ruby
Scala
Objective-C (thanks, Rano)
... more?
Personally, I'm annoyed that Java doesn't have this (yet?). Having seen the feature in other languages makes boilerplate writing in Java seem tiresome.

Well some OOP languages do have such modifier.

In C#, you can define an automatic property with different access qualifiers on the set and get:
public int Foo { get; private set; }
This way, the class implementation can tinker with the property to its heart's content, while client code can only read it.

C# has readonly, Java and some others have final. You can use these to make your member variables read-only.
In C#, you can just specify a getter for your property so it can only be read, not changed.
private int _foo;
public int Foo
{
get { return _foo; }
}

Actually, no they aren't the same. Public foo.getX() would still allow the internal class code to write to the variable. A read-only foo.x would be read-only for the internal class code as well.
And there are some languages that do have such modifier.

C# properties allow to define read only properties easily. See this article.

Not to mention Objective-C 2.0 property read-only accessors
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html

In Delphi:
strict private
FAnswer: integer;
public
property Answer: integer read FAnswer;
Declares a read-only property Answer that accesses private field FAnswer.

The question largely boils down to: why does not every language have a const property like C++?
This is why it's not in C#:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, although they don't come
out and say it that way.
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
See: http://www.artima.com/intv/choicesP.html
So, the reason wy const works in C++ is because you can work around it. Which is sensible for C++, which has its roots in C.
For managed languages like Java and C#, users would expect that const would be just as secure as, say, the garbage collector. That also implies you can't work around it, and it won't be useful if you can't work around it.

Related

Is there any difference in Kotlin between a private property with just a getter and a private function?

I've seen the following Kotlin code, which to me seems just like a more verbose way to do what a function can do. Why would anyone choose to do:
private val foo: Rect
get() = memberField
instead of doing this:
private fun foo(): Rect = memberField
It seems like the fun version is more straightforward to read, but maybe I'm missing something?
When I see the Kotlin byte code and decompile it, I see no difference between the two, so I'm mostly sure there is no difference between them. It might come down to readability, but you should be thinking in terms of state and behaviour. If you think any candidate should describe the state of the class, you should go for the getter, and if you think it should be describing a functionality or behaviour, you should go for functions.
private static final Rect getFoo() {
return memberField;
}
private static final Rect foo() {
return memberField;
}
Using a function instead of a property to simply return something is unconventional code in Kotlin. So, the downside of the function is that the code is a little less readable and easy to follow (more so at call sites than at the declaration site). Maybe not for you specifically if that’s your own style of writing code, but people might not like having to collaborate with you. :)
If the value is unchanging, you don’t need a custom getter. You can just write
private val foo: Rect = memberField
Though I’m not sure what the point of this property is if it just passes through the value of another property.
In practice you don’t frequently need to write custom getters and setters except when implementing interfaces that have properties.
I’m assuming memberField is actually a property. Fields in Kotlin are only accessible via field and it wouldn’t be possible to use it in your getter if you don’t provide an initial value for the property.
It's good to think of this from the user's perspective. Properties make sense when describing the state of an object, for example city.population rather then city.population().
This is not a hard rule, more of a heuristic.

Is there a C# equivalent of VB.NET's "Static"?

The VB.NET Static declaration:
http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
The only reference I can find to this question is from 2008:
http://forums.asp.net/t/951620.aspx?what+is+the+equivalent+of+static+from+vb+net+in+c+
Is there an equivalent in recent versions of C#, or still not present? Is there anything particularly wrong about using Static in VB.NET?
C# does not support it and probably won't be because it somehow violates object programming idea of state being part of object, not a method.
Of course one can say that it is only syntactic sugar, and he/she will be event quite right. But still, looking through class code, we expected description of its state variables as a fields of class. Otherwise we should find for it in each and every method.
So this can be simply seen about some high-level decision and your millage may vary here.
Personally, I like the VB procedure-level Static, even if it's not "pure" enough for some folk.
You can set it in declaration and forget it:
Static oClient As HttpClient = New HttpClient()
There's no checking whether a module-level variable needs to be instantiated or not:
If moClient Is Nothing Then moClient = New HttpClient()
And, silly me, I always expect that there is equivalency between C#.NET and VB.NET but I've learned that clinging to that concept is folly, unfortunately.

Does an isolate / sandbox access modifier exist in any language?

Is there a language which has a feature that can prevent a class accessing any other class, unless an instance or reference is contained?
isolated class Example {
public Integer i;
public void doSomething()
{
i = 5; // This is ok because i belongs to this class
/*
* This is forbidden because this class can only
* access anything contained within, nothing outside
*/
System.out.println("This does not work.");
}
}
[edit]An example use case might be a plugin system. I could define a plugin object with references to certain objects that class can manipulate, but nothing else is permissible. It could potentially make security concerns much easier.[/edit]
I'm not aware of any class-based access modifiers with such intent, but I believe access modifiers to be misguided anyway.
Capability-based security or, more specifically, the object-capability model seems to be what you want.
http://en.wikipedia.org/wiki/Object-capability_model
The basic idea is that in order to do anything with an object, you need to hold a reference to it. Withhold the reference and no access is possible.
Global things (such as System.out.println) and a few other things are problematic features of a language, because anyone can access them without a reference.
Languages such as E, or tools like google caja (for Javascript) allow proper object-capability models. Here an example in JS:
function Example(someObj) {
this.someObj = someObj;
this.doStuff() = function() {
this.someObj.foo(); //allowed, we have been given a reference to it
alert("foobar"); //caja may deny/proxy access to global "alert"
}
}
Any language where you must include headers would probably count: Just don't include any headers.
However, I would wager that there's no language that explicitly forbids external access. What's the point? You can't do anything if you can't access the outside world. And, why would the reference to Integer be okay, but System.out.println not be?
If you clarify the potential use-case, we can probably help you better...
Edit for your Edit:
I thought you might be going there.
If this is for security, it's flawed from the start. Let's examine:
class EvilCode {
void DoNiceThings() {
HardDrive.Format();
}
}
What incentive do I have to voluntarily place a keyword on my class? I'm certainly not going to because I'm nice, since I'm not!
One thing to consider is that any time you're loading native code that's not your own (native, in this case, means not scripted), you're potentially allowing a bad guy to run his code. No language features are going to protect you from that.
The proper answer depends on your target language. Java has Security descriptors, .NET lets you create AppDomains with restricted permissions, etc. Unfortunately, I'm not an expert in these fields.

Use of Constructors - Odd Doubt

I'm reading about constructors,
When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are
is a c'tor more like the main() in
C
Yes i understand the point that you
can set all the default values using
c'tor. I can also emulate the behavior
by writing a custom method. Then why a c'tor?
Example:
//The code below is written in C#.
public class Manipulate
{
public static int Main(string[] args) {
Provide provide = new Provide();
provide.Number(8);
provide.Square();
Console.ReadKey();
return 0;
}
}
public class Provide {
uint num;
public void Number(uint number)
{
num = number;
}
public void Square()
{
num *= num;
Console.WriteLine("{0}", num);
}
}
Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.
Head First OOA&D will be a good start.
Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.
With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.
Constructor and Destructor functionality may be emulated using regular methods. However, what makes those two type of methods unique is that the language treats them in a special way.
They are automatically called when an object is created or destroyed. This presents a uniform means to handle the most delicate operations that must take place during those two critical periods of an object's lifetime. It takes out the possibility of an end user of a class forgetting to call those at the appropriate times.
Furthermore, advanced OO features such as inheritance require that uniformity to even work.
First of all, most answers will depend at least a bit on the language you're using. Reasons that make great sense in one language don't necessarily have direct analogs in other languages. Just for example, in C++ there are quite a few situations where temporary objects are created automatically. The ctor is invoked as part of that process, but for most practical purposes it's impossible to explicitly invoke other member functions in the process. That doesn't necessarily apply to other OO languages though -- some won't create temporary objects implicitly at all.
Generally you should do all your initialization in the constructor. The constructor is the first thing called when an instance of your class is created, so you should setup any defaults here.
I think a good way to learn is comparing OOP between languages, it's like seeing the same picture from diferent angles.
Googling a while:
java (I prefer this, it's simple and full)- http://java.sun.com/docs/books/tutorial/java/concepts/
python - http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
c# - http://cplus.about.com/od/learnc/ss/csharpclasses.htm
Why constructors?
The main diference between a simple function (that also could have functions inside) and an Object, is the way that an Object can be hosted inside a "variable", with all it functions inside, and that also can react completly diferent to an other "variable" with the same kind of "object" inside. The way to make them have the same structure with diferent behaviours depends on the arguments you gave to the class.
So here's a lazy example:
car() is now a class.
c1 = car()
c2 = car()
¿c1 is exactly c2? Yes.
c1 = car(volkswagen)
c2 = car(lamborghini)
C1 has the same functionalities than C2, but they are completly diferent kinds of car()
Variables volkswagen and lamborghini were passed directly to the constructor.
Why a -constructor-? why not any other function? The answer is: order.
That's my best shot, man, for this late hours. I hope i've helped somehow.
You can't emulate the constructor in a custom method as the custom method is not called when the object is created. Only the constructor is called. Well, of course you can then call your custom method after you create the object, but this is not convention and other people using your object will not know to do this.
A constructor is just a convention that is agreed upon as a way to setup your object once it is created.
One of the reasons we need constructor is 'encapsulation',the code do something initialization must invisible
You also can't force the passing of variables without using a constructor. If you only want to instantiate an object if you have say an int to pass to it, you can set the default constructor as private, and make your constructor take an int. This way, it's impossible to create an object of that class without having it take an int.
Sub-objects will be initialized in the constructor. In languages like C++, where sub-objects exist within the containing object (instead of as separate objects connected via pointers or handles), the constructor is your only chance to pass parameters to sub-object constructors. Even in Java and C#, any base class is directly contained, so parameters to its constructor must be provided by your constructor.
Lastly, any constant (or in C#, readonly) member variables can only be set from the constructor. Even helper functions called from the constructor are unable to change them.

Why should member variables be initialized in constructors?

When I first started working with object-oriented programming languages, I was taught the following rule:
When declaring a field in a class, don't initialize it yet. Do that in the constructor.
An example in C#:
public class Test
{
private List<String> l;
public Test()
{
l = new List<String>();
}
}
But when someone recently asked me why to do that, I couldn't come up with a reason.
I'm not really familiar with the internal workings of C# (or other programming languages, for that matter, as I believe this can be done in all OO languages).
So why is this done? Is it security? Properties?
If you have multiple constructors, you might want to initialize a field to different values
When you initialize the field in the constructor, there can be no confusion over when exactly it is initialized in regard to the rest of the constructor. This may seem trivial with a single class, but not so much when you have an inheritance hierarchy with constructor code running at each level and accessing superclass fields.
The C# compiler will take any non-static member intialization that you do inline and move it into the constructor for you. In other words this:
class Test
{
Object o = new Object();
}
gets compiled to this:
class Test
{
Object o;
public Test()
{
this.o = new Object();
}
}
I am not sure how compilers for other languages handle this but as far as C# is concerned it is a matter of style and you are free to do whichever you wish. Please note that static fields are handled differently: read this article for more information on that.
One reason to do it is that it puts all of the initialization code in one place which is convenient for others reading your class. Having said this I don't really do it for two primary reasons. (1) I use TDD/Unit testing to define the behavior of my class. If you want to know what the parameterless constructor does, you should really read the tests I've built on the parameterless constructor. (2) With C# 3.0, I typically use automatic properties and inline initialization with a parameterless constructor to instantiate the object. This is much more flexible and it puts the definition of the properties right in line where the code is being used. This would override any initialization in the constructor so I rarely put any there. Of course, this only applies to C#.
Ex. (of 2)
var foo = new Foo { Bar = "baz" };
public class Foo
{
public string Bar { get; set; }
public Foo() { }
}
sometimes the constructor has parameters that are used for initializing internal variables. For example size of arrays
I haven't heard a compelling reason to not offer both options. I suspect that the real reason has to do with simplifying the language structure from a parsing perspective. This is especially true in C-derivative languages where parsing an assignment statement requires 75% of the language syntax rules. It seems to me that allowing it and defining how it would work precisely would be nice. I agree with Michael's comment about the complexity increase as you insert inheritance and multiple constructors but just because you add a feature doesn't mean that you have to use it. I would vote to support both even though my vote doesn't really add up to much.
I always like to think of the class as a factory for objects, and the constructor as the final stop on the production line. The fields declared in the class are blueprints descirbing the object, but the blueprint won't be realised into an object before such an object is ordered tthrough a call to the constructor... Also, as someone pointed out, doing all your initialisations in your constructor will improve readability, as well as it wil provide for dynamicity in initialisation (it might not be a parameterless constructor you're dealing with).
Also, in some languages the constructor may be used for resetting an object to an original state, which is why it will then be necessary to instatiate the object in the constructor.