File naming conventions for Kotlin - naming-conventions

Kotlin removes the Java "one top-level public class per file" restriction, which I've learned to love. I wonder if there are reasons for this discussed somewhere and whether there are some guidelines how to deal with this new freedom?

You can still use that Java rule as a convention and name your files after your classes. Or you can start putting more classes into a single Kotlin file, in which situation I'd recommend naming the files after their purpose. Each file will usually contain classes or other top-level elements that are related to each other (if they are not, maybe they don't belong to the same file in the first place?). There should be single word or a small number of words that express the purpose of all the classes in a single file, which is then a natural candidate for the file name.

On Kotling.org you can find the Coding Conventions document that answers to all your doubts.
If I may, I think these sections taken from the aforementioned page may be useful to you:
Source file names
If a Kotlin file contains a single class (potentially with related top-level declarations), its name should be the same as the name of the class, with the .kt extension appended. If a file contains multiple classes, or only top-level declarations, choose a name describing what the file contains, and name the file accordingly. Use camel humps with an uppercase first letter (e.g. ProcessDeclarations.kt).
The name of the file should describe what the code in the file does. Therefore, you should avoid using meaningless words such as "Util" in file names.
and...
Source file organization
Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged as long as these declarations are closely related to each other semantically and the file size remains reasonable (not exceeding a few hundred lines).
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".
Refer to the document for any other concern you may have.
I think that the main point is chosing a coding convention that works for your team. That said, I think this Kotlin.org convention could be considered as a sort of standard, that I would expect to be at least known, if not followed, by any Kotlin developer, and the default choice for any project unless there are compelling reasons to change.

Related

Why Xcode allows create duplicate Objective-C Category?

Xcode does not allow you to create duplicate class file. I'm curious why it allows you to create duplicate category file in different folders.
eg:
A folder
--- NSObject+Test
B folder
--- NSObject+Test
The project can run normally.
Xcode and Objective-C do allow you to create duplicate class files. What it doesn't allow you to do is create duplicate classes. In Objective-C, it is traditional to name the file with the same name as the class, but this is neither universal, nor enforced.
The question I think you're asking is why does Objective-C allow multiple categories with the same name (regardless of what file they're in). The reason is because Objective-C doesn't really care very much what the name of a category is. Originally categories were a way to organize large classes into multiple files (which is why they're called "categories" rather than "extensions"). Eventually they came to be used to add new methods to existing classes. At no point along the way has the compiler really bothered very much with the category names (the part in parentheses). They're generally treated as a comment.
I wouldn't assume there was a specific moment when the language designers decided "it should be legal to have multiple categories with the same name." There's just never been checked for or prevented.
The more interesting and important collision is that two categories can add the same method name. This isn't prevented by the compiler but is actually a serious problem. It's not defined which method will execute and the compiler won't tell you you've made this mistake. This is why it's important to prefix category method names to prevent collisions. It's a good idea to prefix category names, too, for consistency.
Why should the compiler care about the file name? Never heard that a compiler does such a thing.
And there might be reasons, i. e. if in Folder A resp. Folder B are different versions or configurations of the software.

Is defining all constants of a project in a single class acceptable?

There are some constants and enumerations in a project, and each one is used by some other classes.
As a design pattern, is it acceptable to create a class for constants and enumerations definition? Or is there a better way to define and use those constants?
It depends on the problem domain. Generally speaking it is rather standard practice to keep them in Java enumeration. The question is - how would you like to use those constants? I have such experience, that constants being hold in interfaces/enumerations are being duplicated and created over and over again due to lack of the knowledge of developers of past constants. In the result, there are many files as such Constants.java, BusinessLogic.java, AppConstants.java etc.. It causes big overwhelm over the purpose and then you don't know if the some constant, lets say APP_MODE should be used from Constants.java or AppConstants.java ?
One of the solutions is to keep those constants in one (or many?) properties files and inject thme using spring' #Value annotation.
You may group by using some prefixing, building groups separated by dot.
One of the advantages of the property files is that you keep one Java logic of using properties, but you still can provide property file (which may vary depending on application). A lot of flexibility, no redundancy.
Another solution is to create one Service to provide properties / constants from database. You can differentiate the values over diffrent environements, but that's another story.
If I were you I create a constant container class packege by package. Just span the logically coherent parts together. Otherwise you will increase the the coupling and dependency. And the most general constants (problem domain independent ones) take place in the utility package's constant container class.

Should my class have a method for each file format, or should I delegate I/O to other, file-format-specific classes?

In a given domain, there can be multiple file formats representing similar objects or structures. For example, an object of type Track (meaning a sequence of geographical points) can be saved in .GPX, .KML, GeoJSON, WKT, ShapeFile, etc.
So, my class Track is supposed to read and save its data from files, which can be in different formats.
Question is:
Should my class implement the methods to read from each file type (that is, "know about" them), or should it use other classes, where each class would contain logic to interact with implementation details of each file type? What is the standard practice?
The first option would be coded like this:
trackCollection.Add(Track.loadFromGPX(gpx_fname))
trackCollection.Add(Track.loadfromKML(kml_fname))
# ...and so on with other filetypes
while the second option would probably be:
trackCollection.Add(GpxReader.getTrack(gpx_fname))
trackCollection.Add(KmlReader.getTrack(kml_fname))
It seems to me that some characteristics involving Single Responsability Principle, Information Hiding, and interdependence between classes might make one approach better than the other, but I am not experienced enough to figure which one, if any.
Considering that each file type may need to be parsed with a completely different library and logic, I would certainly prefer the second method (separate classes).
I would only use a "loadFromXXX" method for supporting arguments with different datatypes or methods that will share a lot of code. For example, in C++, you might have loadFromFile(std::ifstream& input) and loadFromString(std::string& str). loadFromFile() may end up parsing the file into a string and call loadFromString or it may parse the file line by line and just share some of the parse functions used in loadFromString.
In any case, it appears that the file formats you listed have very little in common and some (such as KML vs GeoJSON) require completely different parsers. As a result, there should be a separate "reader" or "parser" class for each file type. Otherwise you are bloating class Track and it will have very low cohesion. Separation of concerns would also suggest you split the parsing into another class.

Defining a category in the same .h/.m files of another class

Is it a good practice to define a category within the same .h/.m files of another class? I know it will build with no error and be exactly the same as if it was defined separately.
The main reason I want to do this is because I'm working on an open source control and I want it to have a single .h/.m file.
In general, the biggest problem with combining multiple classes and categories into the same header/implementation is impaired searchability. When a class is in a file with another class, the file name will no longer reflect the fact that the header/implementation contains your other class, making it much harder for others to look for your class.
If your project is small and self-contained, however, the searchability is less of an issue. When there is only one file to search, there is no question of where each particular piece of code is: it's all in that one file. It sounds like your project is both small and self-contained, so I see no problem in placing all code in a single source file if you want it that way.
Another alternative could be placing each class and category in a separate header/implementation pair of files, and then defining a header that includes them all. This would let you keep an ideal project organization, and let your users include a single header to use your component.
If you need this category in just one place I’d say that it’s not that bad having the category within the .m file.
Obviously, if you need that category in multiple places, you should definitely move to its own file: the convention is to name it in this way:
BaseClass+categoryName.{h,m}
e.g.:
NSString+reverseString.h
NSString+reverseString.m

Naming convention and structure for utility classes and methods

Do you have any input on how to organize and name utility classes?
Whenever I run in to some code-duplication, could be just a couple of code lines, I move them to a utility class.
After a while, I tend to get a lot of small static classes, usually with only one method, which I usualy put in a utility namespace that gets bloated with classes.
Examples:
ParseCommaSeparatedIntegersFromString( string )
CreateCommaSeparatedStringFromIntegers( int[] )
CleanHtmlTags( string )
GetListOfIdsFromCollectionOfX( CollectionX )
CompressByteData( byte[] )
Usually, naming conventions tell you to name your class as a Noun. I often end up with a lot of classes like HtmlHelper, CompressHelper but they aren't very informative. I've also tried being really specific like HtmlTagCleaner, which usualy ends up with one class per utility method.
Have you any ideas on how to name and group these helper methods?
I believe there is a continuum of complexity, therefore corresponding organizations. Examples follow, choose depending of the complexity of your project and your utilities, and adapt to other constraints :
One class (called Helper), with a few methods
One package (called helper), with a few classes (called XXXHelper), each class with a few methods.
Alternatively, the classes may be split in several non-helper packages if they fit.
One project (called helper), with a few packages (called XXX), each package with ...
Alternatively, the packages can be split in several non-helper packages if they fit.
Several helper projects (split by tier, by library in use or otherwise)...
At each grouping level (package, class) :
the common part of the meaning is the name of the grouping name
inner codes don't need that meaning anymore (so their name is shorter, more focused, and doesn't need abbreviations, it uses full names).
For projects, I usually repeat the common meaning in a superpackage name. Although not my prefered choice in theory, I don't see in my IDE (Eclipse) from which project a class is imported, so I need the information repeated. The project is actually only used as :
a shipping unit : some deliverables or products will have the jar, those that don't need it won't),
to express dependencies : for example, a business project have no dependency on web tier helpers ; having expressed that in projects dependencies, we made an improvement in apparent complexity, good for us ; or finding such a dependency, we know something is wrong, and start to investigate... ; also, by reducing the dependencies, we may accelerate compilation and building ....
to categorize the code, to find it faster : only when it's huge, I'm talking about thousands of classes in the project
Please note that all the above applies to dynamic methods as well, not only static ones.
It's actually our good practices for all our code.
Now that I tried to answer your question (although in a broad way), let me add another thought
(I know you didn't ask for that).
Static methods (except those using static class members) work without context, all data have to be passed as parameters. We all know that, in OO code, this is not the preferred way. In theory, we should look for the object most relevant to the method, and move that method on that object. Remember that code sharing doesn't have to be static, it only has to be public (or otherwise visible).
Examples of where to move a static method :
If there is only one parameter, to that parameter.
If there are several parameters, choose between moving the method on :
the parameter that is used most : the one with several fields or methods used, or used by conditionals (ideally, some conditionnals would be removed by subclasses overriding) ...
one existing object that has already good access to several of the parameters.
build a new class for that need
Although this method moving may seem for OO-purist, we find this actually helps us in the long run (and it proves invaluable when we want to subclass it, to alter an algorithm). Eclipse moves a method in less than a minute (with all verifications), and we gain so much more than a minute when we look for some code, or when we don't code again a method that was coded already.
Limitations : some classes can't be extended, usually because they are out of control (JDK, libraries ...). I believe this is the real helper justification, when you need to put a method on a class that you can't change.
Our good practice then is to name the helper with the name of the class to extend, with Helper suffix. (StringHelper, DateHelper). This close matching between the class where we would like the code to be and the Helper helps us find those method in a few seconds, even without knowledge if someone else in our project wrote that method or not.
Helper suffix is a good convention, since it is used in other languages (at least in Java, IIRC rails use it).
The intent of your helper should be transported by the method name, and use the class only as placeholder. For example ParseCommaSeparatedIntegersFromString is a bad name for a couple of reasons:
too long, really
it is redundant, in a statically typed language you can remove FromString suffix since it is deduced from signature
What do you think about:
CSVHelper.parse(String)
CSVHelper.create(int[])
HTMLHelper.clean(String)
...