Why programming languages don't have an 'allow specific classes' access modifier - programming-languages

Today, programming languages have these well-known access modifiers: private, public, internal, and protected. But sometimes when I write a program in OOP manner, I think I require a 'special' modifier that can manually specify what class I want to allow access for.
Now I want to know the reason why language designers don't add such modifier to programming languages, maybe the conflict with OOP concept, or about the difficulty?
Thanks for the answer :)
p.s. Sorry if the same question has been already asked.

C# and VB.Net both have the concept of friend assemblies, where specified assemblies can access the internal members of the specified assembly. This allows you to give provisional access to specific callers, the checking for this is done at compile time.
Only assemblies that you explicitly specify as friends can access Friend (Visual Basic) or internal (C#) types and members. For example, if assembly B is a friend of assembly A and assembly C references assembly B, C does not have access to Friend (Visual Basic) or internal (C#) types in A.
The reality is that there are limited legitimate uses for this feature (in these languages at least), unless you are into developing smelly code.
But having said that, the idea of a class defining who can call it is borderline violating the encapsulation and abstraction rules of OOP. By allowing a class to nominate who it's caller can be you are allowing the class to have a knowledge beyond its realm and you are throwing good design out the window. A class can dictate how a caller should call, but not who should call.
I hope that helps somewhat - personally I'm looking forward to the answers from the more academic language oriented people.

Well, Scala allows you to restrict access to specific packages or just to an instance of a class you're referring to as 'this'

This is exactly what the friend modifier in C++ does.

Related

What's an example of an object that is NOT a POCO, and why isn't it a POCO?

I've seen the question, "what does POCO mean?" asked all over the net, and seen plenty of explanations, but it's still not clear to me. I know it stands for "Plain Old CLR Object", but this isn't really helping me to understand.
Can someone please give me a few examples of something that is NOT a POCO and explain why it is NOT a POCO?
Thanks.
edit: I'm beginning to come to the conclusion that a POCO object is any object that can be easily converted to an identical object in any other CLR-supported language because it does not rely on any platform-specific or language specific library that is not universally available.
POCO just means: nothing but a pure class. No inheritance from any base class (other than eventually your own), no decoration with any attributes, no interface implementation of any kind (other than eventually your own), nothing else that would tie the code in any way to a certain technology.
Mostly the term is used in situations where a framework provides you with some services (like persistence in case of an ORM) wihout you having to change anything on your business objects. Other frameworks might demand from you that your objects be derived from some base class, or implement some interface. In case of a POCO, it just your plain object, no changes needed.

Which frameworks (and associated languages) support class replacement?

I'm writing my master thesis, which deals with AOP in .NET, among other things, and I mention the lack of support for replacing classes at load time as an important factor in the fact that there are currently no .NET AOP frameworks that perform true dynamic weaving -- not without imposing the requirement that woven classes must extend ContextBoundObject or MarshalByRefObject or expose all their semantics on an interface.
You can however do this with Java in the JVM thanks to ClassFileTransformer:
You extend ClassFileTransformer.
You subscribe to the class load event.
On class load, you rewrite the class and replace it.
All this is very well, but my project director has asked me, quite in the last minute, to give him a list of frameworks (and associated languages) that do / do not support class replacement. I really have no time to look for this now: I wouldn't feel comfortable just doing a superficial research and potentially putting erroneous information in my thesis.
So I ask you, oh almighty programming community, can you help out? Of course, I'm not asking you to research this yourselves. Simply, if you know for sure that a particular framework supports / doesn't support this, leave it as an answer. If you're not sure please don't forget to point it out.
Thanks so much!
EDIT: #ewernli
I'm asking about (2).
In C# you can indeed emit code at run-time and create new classes dynamically, but they are new classes, they do not replace an existing class. What I'd like to do is to transform the class at load-time, like you can do in Java with the ClassFileTransformer.
About modifying a method's signature: yes, you're right. I should have mentioned that in my case I don't want to modify the class' interface, but rather the content of its methods.
Your answer was really helpful. Thank you :)
Are you asking about (1) true class replacement at run-time, or (2) facilities to transform the class when it's loaded or (3) languages which support dynamic class loading ?
Java support dynamic class loading with ClassLoader, transformation with ClassFileTransformer, but no true class replacement.
I'm not sure for C#, but I think you can emit code at run-time and create new class dynamically, so you can achieve (3) and probably (2).
True class replacement is mostly supported only by dynamic language, e.g. Smalltalk, Ruby, I guess Python and a few others. This requires the transformation of the instances of the class to match the new shape. They usually initialize the new fields to nil if the class changes.
AFAIK, dynamic languages ported to the JVM make extensive hacking of ClassLoader to support class replacement at run-time. For JRuby, see A first taste of invoke dynamic to get more pointers how they do it now, what's problematic and how the upcoming invokedynamic might help.
This is not offered in statically typed languages because of the complication with the type system. If a method signature change in a class, other existing classes already loaded might not necessary comply with the new method signature which is not safe. In java you can however change a method as long as the signature is the same using the Java Platform Debugger Architecture.
There have been some attempt to add this feature to Java, and/or statically typed languages:
Runtime support for type-safe dynamic Java classes
Supporting Unanticipated Dynamic Adaptation of Application Behaviour
A Technique for Dynamic Updating of Java Software
This paper provide a general overview of related problems
Influence of type systems on dynamic software evolution
Not sure exactly if that address you initial question, but these pointers might be interesting for your thesis anyway.
The Java language doesn't support class file replacement. The JVM exposes the feature via the classes you mention. Therefore all languages which have been ported to the JVM can take advantage of it.
Erlang supports hot code swapping, and if you are looking also for theoretical frameworks that model dynamic class updates, you can take a look at the Creol language (interpreted).
Objective-C's runtime library supports dynamic construction and registration of classes, lazy method registration and "method swizzling" by which method implementations can be switched at runtime. Previous versions supported "Class swizzling" by which a class could be substituted for another at runtime, but now method swizzling is used instead. Here's the reference doc.

Does the 'dynamic' keyword and the DLR promote C# to a first class citizen as a dynamically typed language?

I understand that the new ‘dynamic’ keyword in C# 4.0 facilitates interaction with dynamic .NET languages, and can help to cut code by using it instead of reflection. So usage is for very specific situations.
However, what I would like to know is if it will give C# all the dynamic benefits that one would get in other dynamic languages such is the IronXXX languages? In other words, will it be possible to write a entire application in C# in a dynamic language style?
And if it is possible, would it be recommended or not. And why, or why not respectively?
Will I get all the benefits of a dynamic language without switching to another language?
I wouldn't say C# is a first class dynamic language, no.
Firstly, some of the static typing features really don't play well with dynamic typing. For example:
public void ShowListCount(IList foo)
{
dynamic d = foo;
Console.WriteLine(d.Count);
}
That looks like it should always work, because IList exposes Count, right? Try it with this:
ShowListCount(new int[10]);
Bang. Arrays implement IList.Count with explicit interface implementation, so when dynamic typing "sees" the object as an array, it doesn't look see the Count property. There are various gotchas like that.
Also, if you want to implement dynamic behaviour in C# (i.e. being called dynamically), there's no explicit language support. You can derive from DynamicObject or implement IDynamicMetaObjectProvider yourself, but nothing in the language is going to help you.
I regard dynamic typing in C# as something to be used primarily when you want to interoperate with an existing dynamic platform such as IronPython or a weakly-typed COM API. There are some places where it can be useful within pure C#, but they're relatively rare.
Basically C# is still very obviously a language designed with static typing in mind. Having the ability to use dynamic typing carefully where you want it is nice, but if you want to use dynamic typing extensively for one area of your codebase, I'd suggest writing that bit in IronPython and then calling into it from C#.
While the dynamic keyword will definitely bring C# closer to the dynamic world it won't make it a dynamic language and by so it won't have the benefits of dynamic languages such as adding methods to an existing type at runtime, ...

Most dynamic dynamic programming language [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
It seems I've got to agree with this post when it states that
[...] code in dynamically typed languages follows static-typing conventions
Much dynamic language code I encounter does indeed seem to be quite static (thinking of PHP) whereas dynamic approaches look somewhat clumsy or unnecessary instead.
Most of the time, it's just about omitting type signatures, which, in the context of type-inference/structural typing, doesn't even have to imply dynamic typing at all.
So my question (and it's not meant to be too subjective) is, in which dynamic languages or fields of application are all these more advanced dynamic language features (that couln't be replicated in static/compiled languages that easily) actually and idomatically used.
Examples:
Reflection
First-class continuations
Runtime object alteration/generation
Metaprogramming
Run-time code evaluation
Non-existent member behaviour
What are useful applications for such techniques?
Some examples of widespread application of the above techniques are:
Continuations make their appearance in web frameworks like Rails or Seaside. They can be used to allow an API to fake a local context. In Seaside or Rails this makes the API behave much more like a local GUI form handler than an HTTP request handler, which serves to simplify the task of coding the application's user interface elements. However, although many dynamic languages have strong support for continuations they are certainly not unique to this type of language.
Reflection is quite widely used for O/R mappers and serialisation, but many statically typed langages support reflection as well. On duck typed languages it can be used to find out at runtime if a facility is implemented by looking at the object's metadata. Some O/R mappers (and similar tools) work by implementing accesses to instance variables and redirecting the updates to a cached record in the data access layer. This helps to make the persistence relatively transparent to the developer as the field accesses look much like local variables.
Runtime object alteration is slightly useful (think monkey-patching) but mostly a gimmick. There aren't many really killer uses for it that come to mind immediately, but people certainly do use it. One possible use for it is fixing slightly broken behaviour when subclassing is not an option for some reason.
Metaprogramming is quite a fuzzy definition for a term, but arguably generics and C++ templates are an example of metaprogramming - taking place on statically typed languages. On languages with metaclass support, custom metaclasses can be used to implement particular behaviours such as singletons or object registries.Another metaprogramming example is Smalltalk's #notImplemented: method which is called on attempts to invoke nonexistent methods. The method name and parameters are supplied to the implementor of #notImplemented:, and can subsequently be used to construct a method invocation reflectively. Trapping this can be used (for example) to implement generic proxy mechanisms.
LISP programmers would argue that LISP is the most dynamic language of all due to its first class support for diddling directly with the parse trees of the code (known as 'macros'). This facility makes implementing DSLs trivial in LISP - and integrating them transparently into your code base.
All features you enumerate are also available in statically typed languages some with constraints.
Reflection: Present in Java, C# (not type safe).
First-class continuations: restricted support in Scala (maybe others)
Runtime object alteration: Changing the type of an object is supported in a restriced form in C# with extension methods (will be in Java 7) and implicit type conversions in Scala. Although open class is not supported most of the use cases are covered by type conversions.
Metaprogramming: I would say Metaprogramming is the heading for a lot of related features like reflection, type changes at runtime, AOP etc.
So there is not a lot left that is supported only by dynamic languages to discuss. Support for example for Reflection circumvents the type system but it is useful in certain situations where this kind of flexibility is needed. The same is true in dynamic languages.
The open class feature supported by Ruby is something that compiled languages will never support. It is the most flexible form of Metaprogramming possible (with all the implications: security, performance, maintainability.) You can change classes of the platform. It's used by Ruby on Rails to create methods of domain objects from metadata on the fly. In a statically typed language you have at least to create (or generate the code of) the interface of your domain object.
If you're looking for the "most dymanic languages" all homoiconic languages like LISP and Prolog are good candidates. Interestingly, C# is somewhat homoiconic with the expression trees in LINQ.
You should visit Douglas Crockford's Wrrrld Wide Web and see his wizardry over Javascript. Javascript is usually written in pretty straightforward and simple manner, like slightly simplified C. But it's only the surface. The unmutable keywords are a small percent of the language power. Most of it lies in objects and methods exported by the system, and these are fully mutable. You can replace/extend methods on the fly, you can replace pretty deeply rooted system methods, nest eval(), load generated <SCRIPT> on the fly, and so on. This is usable in writing all kinds of language extensions, frameworks, toolboxes and such. Instead of 200 lines of code of your program in straightforward Javascript, you write 50 lines that modify how Javascript work, and another 50 that use the new syntax to get the work done. You can generate whole pages on the fly, including JS embedded in them. You turn webpage structure into data storage. You replace frequently used methods of popular objects, and your own, to change their behavior on the fly, changing not only looks but also function of a webpage in one click.
It really feels like Javascript becomes a metalanguage to modify the Javascript engine, and make Javascript function like a different language, then you further modify it using the already modified, and your actual, final app takes a dozen of extremely intuitive lines getting the language do exactly what it needs. Oh, and patches the countless bugs and shortcomings of Javascript implementation on MSIE in the process.
I won't claim Lisp is the "most dynamic" (I'm not even sure what that means), but Lisp programmers frequently do things that are difficult-to-impossible in other languages:
create new control structures
create new syntax for existing constructs (I think every metaclass I've ever seen has its own defwhatever form)
extend the runtime (every .emacs is a runtime extension, e.g., what would it take to write calendar-mode for another editor?)
Yegge talks about it some here w.r.t. Emacs, e.g., parse XML by converting it to s-expressions, writing functions for the tags you want to process, and actually running it.
Ultimately it's not languages that write dynamic code, it's programmers; and there's going to be a learning curve to adjust your patterns to styles you're not used to. So what types of work can make best use of dynamic capabilities? The first that comes to my mind is middleware; interfaces among heterogeneous systems; especially those with imperfectly documented APIs or APIs that change a lot, and data serialization is dynamic.
I'd say anywhere you see REST and jason being applied, you're more likely to find dynamic code, for instance, where javascript, php, perl, ruby, ... are popular at least partially because they are capable of dynamic adaptation.
Also, there's a lot of javascript browser code that deals with browser version and brand incmpatiblities using dynamic techniques.
Yes i feel JavaScript as good one.
JavaScript is so flexible that people working on different languages have different variants of it for them. Like Microsoft has Ajax library which has typical .NET/C# type syntax. Also there are some JavaScript libraries which uses $ which looks similar like PHP syntaxes. Its all there because JavaScript is bueaty How many other languages one can tell which can facilitates something like this?
And one should know about the JavaScript closure feature which is state of art and help create amazing algorithms with great results.

What are the preferred conventions in naming attributes, methods and classes in different languages?

Are the naming conventions similar in different languages? If not, what are the differences?
Each language has a specific style. At least one.
Each project adopts a specific style. At least, they should. This can sometimes be a different style to the canonical style your language uses - probably based on the dev leaders preferences.
Which style to use?
If your language ships with a good standard library, try to adopt the conventions in that library.
If your language has a canonical book (The C Programming language, The Camel Book, Programming Ruby etc.) use that.
Sometimes the language designers (C#, Java spring to mind) actually write a bunch of guidelines. Use those, especially if the community adopts them too.
If you use multiple languages remember to stay flexible and adjust your preferred coding style to the language you are using - when coding in Python use a different style to coding in C# etc.
As others have said, things vary a lot, but here's a rough overview of the most commonly used naming conventions in various languages:
lowercase, lowercase_with_underscores:
Commonly used for local variables and function names (typical C syntax).
UPPERCASE, UPPERCASE_WITH_UNDERSCORES:
Commonly used for constants and variables that never change. Some (older) languages like BASIC also have a convention for using all upper case for all variable names.
CamelCase, javaCamelCase:
Typically used for function names and variable names. Some use it only for functions and combine it with lowercase or lowercase_with_underscores for variables. When javaCamelCase is used, it's typically used both for functions and variables.
This syntax is also quite common for external APIs, since this is how the Win32 and Java APIs do it. (Even if a library uses a different convention internally they typically export with the (java)CamelCase syntax for function names.)
prefix_CamelCase, prefix_lowercase, prefix_lowercase_with_underscores:
Commonly used in languages that don't support namespaces (i.e. C). The prefix will usually denote the library or module to which the function or variable belongs. Usually reserved to global variables and global functions. Prefix can also be in UPPERCASE. Some conventions use lowercase prefix for internal functions and variables and UPPERCASE prefix for exported ones.
There are of course many other ways to name things, but most conventions are based on one of the ones mentioned above or a variety on those.
BTW: I forgot to mention Hungarian notation on purpose.
G'day,
One of the best recommendations I can make is to read the relevant section(s) of Steve McConnell's Code Complete (Amazon Link). He has an excellent discussion on naming techniques.
HTH
cheers,
Rob
Of course there are some common guidelines but there are also differences due to difference in language syntax\design.
For .NET (C#, VB, etc) I would recommend following resource:
Framework Design Guidelines -
definitive book on .NET coding
guidelines including naming
conventions
Naming Guidelines - guidelines from Microsoft
General Naming Conventions - another set of MS guidelines (C#, C++, VB)
I think that most naming conventions will vary but the developer, for example I name variables like: mulitwordVarName, however some of the dev I have worked with used something like mulitword_var_name or multiwordvarname or aj5g54ag or... I think it really depends on your preference.
Years ago an wise old programmer taught me the evils of Hungarian notation, this was a real legacy system, Microsoft adopted it some what in the Windows SDK, and later in MFC. It was designed around loose typed languages like C, and not for strong typed languages like C++. At the time I was programming Windows 3.0 using Borland's Turbo Pascal 1.0 for Windows, which later became Delphi.
Anyway long story short at this time the team I was working on developed our own standards very simple and applicable to almost all languages, based on simple prefixes -
a - argument
l - local
m - member
g - global
The emphasis here is on scope, rely on the compiler to check type, all you need care about is scope, where the data lives. This has many advantages over nasty old Hungarian notation in that if you change the type of something via refactoring you don't have to search and replace all instances of it.
Nearly 16 years later I still promote the use of this practice, and have found it applicable to almost every language I have developed in.

Resources