Why some java methods in core libraries end with numbers? - naming-conventions

It's common in a lot of classes in JDK, just a few examples:
java.util.Properties
load0
store0
java.lang.Thread
start0
stop0
setPriority0
Usually they are private native methods (like in Thread class), but sometimes they are just private (Properties class)
I'm just curious if anybody know if there is any history behind that.

I believe they are named like that because equivalent functions with same names exist in the code and just to distinguish between native helper functions and public functions they decided to suffix them with 0.
in java.util.Properties both load, store and load0, store0 exist.

The 0 after the method name is done so to distinguish between public and private methods having same name .
Start function will call the start0 function.
Those functions which ends with 0 is private method.
And those which are not ending with number is public.
You can check in any of the library.

The use of zero suffixes on method names is just a convention to deal with cases where you have a public API method and a corresponding private method. In the Java SE libraries, this is commonly used for the native methods that provide the underlying functionality implemented by the classes. (You can see what is going on by looking at the OpenJDK source code.)
But your questions are:
Why some java methods in core libraries end with numbers?
Because someone thought it would be a good idea. It is not strictly necessary since they typically could have overloaded the public methods instead. And since the zero suffix matters are private, the naming of methods should not be relevant beyond the class and its native implementation.
I'm just curious if anybody know if there is any history behind that.
There is no mention of this convention in the original Java Style Guide. In fact, I think it predates Java. I vaguely recall seeing it in C libraries in 4.x BSD Unix. That was the mid 1980's. And I wouldn't be surprised if they adopted it from somewhere else.

Related

Kotlin: Idiomatic usage of extension functions - putting extension functions next to the class it extends

I see some usages of Extension functions in Kotlin I don't personally think that makes sense, but it seems that there are some guidelines that "apparently" support it (a matter of interpretation).
Specifically: defining an extension function outside a class (but in the same file):
data class AddressDTO(val state: State,
val zipCode: String,
val city: String,
val streetAddress: String
)
fun AddressDTO.asXyzFormat() = "${streetAddress}\n${city}\n${state.name} $zipCode"
Where the asXyzFormat() is widely used, and cannot be defined as private/internal (but also for the cases it may be).
In my common sense, if you own the code (AddressDTO) and the usage is not local to some class / module (hence behing private/internal) - there is no reason to define an extension function - just define it as a member function of that class.
Edge case: if you want to avoid serialization of the function starting with get - annotate the class to get the desired behavior (e.g. #JsonIgnore on the function). This IMHO still doesn't justify an extension function.
The counter-response I got to this is that the approach of having an extension function of this fashion is supported by the Official Kotlin Coding Conventions. Specifically:
Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an extension function accepting that object as a receiver.
Source
And:
In particular, when defining extension functions for a class which are relevant for all clients of this class, put them in the same file where the class itself is defined. When defining extension functions that make sense only for a specific client, put them next to the code of that client. Do not create files just to hold "all extensions of Foo".
Source
I'll appreciate any commonly accepted source/reference explaining why it makes more sense to move the function to be a member of the class and/or pragmatic arguments support this separation.
That quote about using extension functions liberally, I'm pretty sure means use them liberally as opposed to top level non-extension functions (not as opposed to making it a member function). It's saying that if a top-level function conceptually works on a target object, prefer the extension function form.
I've searched before for the answer to why you might choose to make a function an extension function instead of a member function when working on a class you own the source code for, and have never found a canonical answer from JetBrains. Here are some reasons I think you might, but some are highly subject to opinion.
Sometimes you want a function that operates on a class with a specific generic type. Think of List<Int>.sum(), which is only available to a subset of Lists, but not a subtype of List.
Interfaces can be thought of as contracts. Functions that do something to an interface may make more sense conceptually since they are not part of the contract. I think this is the rationale for most of the standard library extension functions for Iterable and Sequence. A similar rationale might apply to a data class, if you think of a data class almost like a passive struct.
Extension functions afford the possibility of allowing users to pseudo-override them, but forcing them to do it in an independent way. Suppose your asXyzFormat() were an open member function. In some other module, you receive AddressDTO instances and want to get the XYZ format of them, exactly in the format you expect. But the AddressDTO you receive might have overridden asXyzFormat() and provide you something unexpected, so now you can't trust the function. If you use an extension function, than you allow users to replace asXyzFormat() in their own packages with something applicable to that space, but you can always trust the function asXyzFormat() in the source package.
Similarly for interfaces, a member function with default implementation invites users to override it. As the author of the interface, you may want a reliable function you can use on that interface with expected behavior. Although the end-user can hide your extension in their own module by overloading it, that will have no effect on your own uses of the function.
For what it's worth, I think it would be very rare to choose to make an extension function for a class (not an interface) when you own the source code for it. And I can't think of any examples of that in the standard library. Which leads me to believe that the Coding Conventions document is using the word "class" in a liberal sense that includes interfaces.
Here's a reverse argument…
One of the main reasons for adding extension functions to the language is being able to add functionality to classes from the standard library, and from third-party libraries and other dependencies where you don't control the code and can't add member functions (AKA methods).  I suspect it's mainly those cases that that section of the coding conventions is talking about.
In Java, the only option in this cases is utility methods: static methods, usually in a utility class gathering together lots of such methods, each taking the relevant object as its first parameter:
public static String[] splitOnChar(String str, char separator)
public static boolean isAllDigits(String str)
…and so on, interminably.
The main problem there is that such methods are hard to find (no help from the IDE unless you already know about all the various utility classes).  Also, calling them is long-winded (though it improved a bit once static imports were available).
Kotlin's extension methods are implemented exactly the same way down at the bytecode level, but their syntax is much simpler and exactly like member functions: they're written the same way (with this &c), calling them looks just like calling a member function, and your IDE will suggest them.
(Of course, they have drawbacks, too: no dynamic dispatch, no inheritance or overriding, scoping/import issues, name clashes, references to them are awkward, accessing them from Java or reflection is awkward, and so on.)
So: if the main purpose of extension functions is to substitute for member functions when member functions aren't possible, why would you use them when member functions are possible?!
(To be fair, there are a few reasons why you might want them.  For example, you can make the receiver nullable, which isn't possible with member functions.  But in most cases, they're greatly outweighed by the benefits of a proper member function.)
This means that the vast majority of extension functions are likely to be written for classes that you don't control the source code for, and so you don't have the option of putting them next to the class.

Private and protected methods in Objective-C

What is the recommended way to define private and protected methods in Objective-C? One website suggested using categories in the implementation file for private methods, another suggested trailing underscores, or XX_ where XX is some project-specific code. What does Apple itself use?
And what about protected methods? One solution I read was to use categories in separate files, for example CLASS_protected.h and CLASS_protected.m but this seems like it could get very bloated. What should I do?
There are three issues:
Hiding from compiler.
That is, making it impossible for someone else to #import something and see your method declarations. For that, put your private API into a separate header file, mark that header's role as "Private" in Xcode, and then import it in your project where you need access to said private API.
Use a category or class extension to declare the additional methods.
Preventing collisions
If you are implementing lots of internal goop, do so with a common prefix or something that makes a collision with Apple provided (or third party) provided methods exceedingly unlikely. This is especially critical for categories and not nearly as critical for your leaf node subclasses of existing classes.
Post the link for the site suggesting leading underscores, as they are wrong, wrong, wrong. Leading underscores are used by the system to mark private API and you can run into collisions easily enough.
Hiding from the runtime.
Don't bother. It just makes debugging / crash analysis harder and anyone determined enough to muck around at the runtime will be able to hack your app anyway.
There are no "real" private methods in Objective C, as the run-time will allow, via documented public APIs, access any method in any class by using their string names.
I never do separate interface files for "private" methods, and let the compiler complain if I try to use these any of these methods outside of file scope.
The XX_ seems to be the ad hoc means to create a pseudo namespace. The idea is to read Apple's docs and the docs of any frameworks you might use at any time in the future, and pick an XX prefix that none of these others is ever likely to use.

When is it a good idea to use a vb.net Module

Some of my co-workers make extensive use of the VB.net concept of Modules. Unfortunately, I just don't 'get it'. I see no benefit in using modules over shared classes. Am I missing something? When would it be preferable to use a module? Or am I (as I do quite often in this language) 'just not getting it'?
In VB.net a module is a shared class. When they are compiled they are given a private constructor and methods set to shared.
There are some times when you are forced to use modules by the compiler (in the same way static classes are in C#) such as for extension methods which can not be created in side a VB.Net class.
By using modules for your helper methods you will make it easier to convert them over to extension methods later and restrict others from adding any instance methods or constructors.
That said they are a hang over from VB6 that did not support full OO programming and beyond standalone helper methods they would not widely be used.
A module is essentially the same as a shared class. The major difference is that in a module, there's no need for all the extra "shared"s, cause everything's implicitly shared. If you have no instance data and are just using the class as a kind of namespace for functions, then it's a better idea (IMO) to use a module instead and make that clear.

Are Modules still commonly used in program structures?

I am not a program designer by any means but I would really like to start getting a better grasp of how to do it and a better understanding of the .NET languages in general (VB, C#). I was reading a book by Wrox - Professional Visual Basic 2008. In it I believed it mentioned that Modules are slowly going out of existence. I can see why most coding would go into a class object but I would assume modules would always be necessary to at least keep the code clean.
Could anybody clarify this up for me? Also, I have been searching for a good source on software design but I can't seem to find any recent books published. I might be searching in the wrong places but I would really like to get my hands on one.
Thank you.
While in general they don't quite fit with OOP, they are still used and are required in some cases.
In VB.Net, if you wish to write extension methods, you are going to have to use a Module - The compiler will only allow Extension Methods to be defined in one.
You could of course get round not using Modules - an Non Inheritable Class with a private constructor and nothing but Shared Methods will achieved the same thing as a Module.
Like everything in programming (and many other things), they have their uses, and as long as they are not miss-used there is no problem with them. Right tool for the job!
The Module keyword in VB.NET primarily exists for compatibility with VB6 and earlier. Back then, most VB code was procedural with free-standing non-class Subs and Functions. The language acquired the Class keyword somewhere around VB4. Not true classes in the OOP sense, it didn't support inheritance. A feature missing from the underlying COM architecture.
It doesn't fit very well with the execution model provided by the CLR. There is no support for free functions, every method must be a member of a class. The VB.NET compiler emulates modules by declaring a class, the module procedures become Shared methods of that class. You can see this with Ildasm.exe:
.class private auto ansi sealed ConsoleApplication1.Module1
extends [mscorlib]System.Object
{
.custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 )
} // end of class ConsoleApplication1.Module1
Note how it is private, so that code can't get a reference to it, and sealed, so that no code can derive a class from a module.
The C# compiler does the exact same thing with a "static class", the CLR doesn't have a notion of static classes either. There are plenty of good reasons for static classes, the idea of "Module" isn't obsolete. You could accomplish the same by declaring a NotInheritable Class in VB.NET code, having only Shared methods. The VB.NET compiler however doesn't enforce methods to be Shared like the C# compiler does and doesn't allow you to declare the class private. As such, a Module is just fine.
Modules are the closest thing VB has to static classes, which can be very useful, even when programming in an object-oriented environment.
And since VB has no static classes, modules are as far as I know the only way to create extension methods.
You need modules in order to define your own Extension methods

Is it good practice to call module functions directly in VB.NET?

I have a Util module in my VB.NET program that has project-wide methods such as logging and property parsing. The general practice where I work seems to be to call these methods directly without prefixing them with Util. When I was new to VB, it took me a while to figure out where these methods/functions were coming from. As I use my own Util methods now, I can't help thinking that it's a lot clearer and more understandable to add Util. before each method call (you know immediately that it's user-defined but not within the current class, and where to find it), and is hardly even longer. What's the general practice when calling procedures/functions of VB modules? Should we prefix them with the module name or not?
Intellisense (and "Goto Definition") should make it trivial to find where things are located, but I always preface the calls with a better namespace, just for clarity of reading. Then it's clear that it's a custom function, and not something built in or local to the class you're working with.
Maybe there's a subtle difference I'm missing, but I tend to use shared classes instead of modules for any code that's common and self-contained - it just seems easier to keep track of for me, and it would also enforce your rule of prefacing it, since you can't just call it from everywhere without giving a namespace to call it from.
I usually put the complete namespace for a shared function, for readibility.
Call MyNameSpace.Utils.MySharedFunction()
Util is such a generic name.
Example from the .Net framework. You have System.Web.HttpUtility.UrlEncode(...). Usually you refer to this as HttpUtility.UrlEncode since you have an import statement at the top.
The name of the class which has the static utility methods should be readable and explainable. That is good practice. If you have good class names they might just as well reside in a Utils namespace, but the class name should not be Utils.
Put all your logging in a Logger class. All your string handing in a StringUtils class etc. And try to keep the class names as specific as possible, and I'd rather have more classes with fewer functions than the other way around.