Kotlin's naming conventions for private values - kotlin

Have read Kotlin's style guide https://kotlinlang.org/docs/coding-conventions.html#interface-implementation-layout.
This does not make it clear why IntelliJ IDEA underline "private val LOGGER =" with the suggestion that LOGGER is changed to logger.
This is particularly weird because IDEA doesn't have a problem if private is removed and we leave "val LOGGER =".
In my mind UPPER_CASE should be used if the object is not mutable at any level. Whether it is private or not is irrelevant.

As far as I can tell, these three inspections in IntelliJ are responsible for reporting "bad" property names:
From top to bottom, they are called:
Object property naming convention
Private property naming convention
Property naming convention
Each of them has a regex associated with it. It is as simple as "whatever doesn't match the regex gets reported". The regexes are, from top to bottom:
[A-Za-z][_A-Za-z\d]*
_?[a-z][A-Za-z\d]*
[a-z][A-Za-z\d]*
(You can edit or disable these if you don't like them.)
When combined, these sort of cover all the rules in this page, except perhaps the one about "Names of properties holding references to singleton objects can use the same naming style as object declarations" because static analysis can't reliably determine whether something is a "singleton object".
As you discovered, however, these also adds in other "recommendations" not mentioned in that page, such as private properties in classes should not start with a capital. That said, I don't think that page is supposed to be an exhaustive list of all the recommendations anyway. That page even recommends you to use these inspections to verify that the code follows the style guide:
Verify that your code follows the style guide
Go to Settings/Preferences | Editor | Inspections | General.
Switch on Incorrect formatting inspection. Additional inspections that verify other issues described in the style guide (such as naming
conventions) are enabled by default.

Related

How can I have a "private" Erlang module?

I prefer working with files that are less than 1000 lines long, so am thinking of breaking up some Erlang modules into more bite-sized pieces.
Is there a way of doing this without expanding the public API of my library?
What I mean is, any time there is a module, any user can do module:func_exported_from_the_module. The only way to really have something be private that I know of is to not export it from any module (and even then holes can be poked).
So if there is technically no way to accomplish what I'm looking for, is there a convention?
For example, there are no private methods in Python classes, but the convention is to use a leading _ in _my_private_method to mark it as private.
I accept that the answer may be, "no, you must have 4K LOC files."
The closest thing to a convention is to use edoc tags, like #private and #hidden.
From the docs:
#hidden
Marks the function so that it will not appear in the
documentation (even if "private" documentation is generated). Useful
for debug/test functions, etc. The content can be used as a comment;
it is ignored by EDoc.
#private
Marks the function as private (i.e., not part of the public
interface), so that it will not appear in the normal documentation.
(If "private" documentation is generated, the function will be
included.) Only useful for exported functions, e.g. entry points for
spawn. (Non-exported functions are always "private".) The content can
be used as a comment; it is ignored by EDoc.
Please note that this answer started as a comment to #legoscia's answer
Different visibilities for different methods is not currently supported.
The current convention, if you want to call it that way, is to have one (or several) 'facade' my_lib.erl module(s) that export the public API of your library/application. Calling any internal module of the library is playing with fire and should be avoided (call them at your own risk).
There are some very nice features in the BEAM VM that rely on being able to call exported functions from any module, such as
Callbacks (funs/anonymous funs), MFA, erlang:apply/3: The calling code does not need to know anything about the library, just that it's something that needs to be called
Behaviours such as gen_server need the previous point to work
Hot reloading: You can upgrade the bytecode of any module without stopping the VM. The code server inside the VM maintains at most two versions of the bytecode for any module, redirecting external calls (those with the Module:) to the most recent version and the internal calls to the current version. That's why you may see some ?MODULE: calls in long-running servers, to be able to upgrade the code
You'd be able to argue that these points'd be available with more fine-grained BEAM-oriented visibility levels, true. But I don't think it would solve anything that's not solved with the facade modules, and it'd complicate other parts of the VM/code a great deal.
Bonus
Something similar applies to records and opaque types, records only exist at compile time, and opaque types only at dialyzer time. Nothing stops you from accessing their internals anywhere, but you'll only find problems if you go that way:
You insert a new field in the record, suddenly, all your {record_name,...} = break
You use a library that returns an opaque_adt(), you know that it's a list and use like so. The library is upgraded to include the size of the list, so now opaque_adt() is a tuple() and chaos ensues
Only those functions that are specified in the -export attribute are visible to other modules i.e "public" functions. All other functions are private. If you have specified -compile(export_all) only then all functions in module are visible outside. It is not recommended to use -compile(export_all).
I don't know of any existing convention for Erlang, but why not adopt the Python convention? Let's say that "library-private" functions are prefixed with an underscore. You'll need to quote function names with single quotes for that to work:
-module(bar).
-export(['_my_private_function'/0]).
'_my_private_function'() ->
foo.
Then you can call it as:
> bar:'_my_private_function'().
foo
To me, that communicates clearly that I shouldn't be calling that function unless I know what I'm doing. (and probably not even then)

What's the standard naming convention for a property's backing field?

Background
I'm wanting to follow the most commonly-practised naming conventions for TypeScript. I've noticed that the official website shows code examples featuring Pascal-case for types and modules and camel-case for just about everything else.
Example
I'm currently implementing a property that encapsulates a backing value:
class SomeClass {
get status() {
return statusBackingField;
}
set status(newValue: Status) {
statusBackingField = newValue;
//Do other work here
}
statusBackingField: Status;
}
Problem
The name of the property is status. In C#, I would normally name the property Status and the backing value status. Since the convention is to use camel-case for properties, this doesn't work. I'm not sure which convention I should use for consistency with other TypeScript code in general.
Question
Other languages, such as C# and Java, seem to have official or de facto standard conventions. Is there any such authoritative or de facto standard convention for naming backing fields in TypeScript?
Notes
For the close-voters: please note that I'm not looking for opinions. I'm looking for objective information as requested in the summarised question above.
There is no code convention standard for TypeScript. Since it is a superset of JavaScript, following JavaScript code conventions would probably be the correct approach. In such a case you would use an underscore-prefixed property _status. Idiomatically, this also matches the compiler’s use of an underscore-prefixed _this for compiled arrow functions and underscored-prefixed _super for superclasses.
In C# as well as TypeScript we use private _status. In C# the property will be Status. In TypeScript as you mentioned it is status
I think it's safe to say at this stage that there is no standard.
If someone can point me to an authoritative standard or evidence of a de-facto standard, then I may consider accepting their answer instead.

Disable "not used" warning for public methods of a class

The new intellij upgrade (10.5) now shows a warning that some of the methods defined for a class are not being used. These methods are public and I plan on not using all of them as I have created them to support the API expected. I would like to disable this warning (not used for public methods in a class). Is there a way to do it?.
You can disable it for a single method like this
#SuppressWarnings("unused")
public void myMethod(){...}
IDEA 2016.3
In the upcoming version IDEA 2016.3 (preview version already available) it is now possible to adjust the inspection scope:
< IDEA 14.0
If you want to highlight unused public methods, please enable the "Settings|Inspections|Declaration redundancy|Unused declaration" global inspection.
If you want to highlight unused private methods, please enable the "Settings|Inspections|Declaration redundancy|Unused symbol" local inspection.
So, if you want to highlight unused private members, but do not highlight unused public members, turn off "Unused declaration" and turn on "Unused symbol".
Source
I've just tested it using IDEA 13.1.4, and it worked exactly as described.
IDEA 14.x
In IntelliJ IDEA 14.0.x the settings are under:
Settings | Editor | Inspections | Declaration redundancy | Unused symbol/declaration
In IntelliJ IDEA 14.1 the option appears to be gone..
Disable Settings | Inspections | Declaration redundancy | Unused Declaration code inspection. As an option you can create a custom scope for your API classes and disable this inspection only per API scope so that it still works in the rest parts of your project.
2018-2019
Here is the 2019 update for:
IntelliJ IDEA 2018.3.2 (Community Edition)
Build #IC-183.4886.37, built on December 17, 2018
Settings | Editor | Inspections | Declaration redundancy | Unused declaration
I think the best way to avoid the highlighting of that unused public methods is writing a couple of test for those methods in your API.
In the latest version, this options is under Settings>Inspections>Java>Declaration redundancy>Unused declaration>Methods uncheck options which are not required.
This is an old thread, but I ended up here faster than I could find a solution so I'm going to go ahead and share my findings.
First, I am not sure if we are working with the same language (JS here,) but fiddling with the GUI-based tools, here is what I ended up with.
The following code was giving me the infamous "not used" warning:
/**
* #class sample class
*/
var MyClass = function () {
return this;
};
/**
* Some public method
* #api public
*/
MyClass.prototype.myMethod = function () {
return null;
};
There goes the "Unused definition myMethod"
The inspector ended up suggesting to ignore this specific issue by adding
//noinspection JSUnusedGlobalSymbols
right on top of this specific method so that the following code no longer results in this warning:
//noinspection JSUnusedGlobalSymbols
/**
* Some public method
* #api public
*/
MyClass.prototype.myMethod = function () {
return null;
};
Other warnings (typoes etc..) still seem to show up, including unused local variables and parameters, so it seems to isolate this particular issue.
The downside is that it tends to pollute your code if you have lots of it...
I just clicked "suppress for statement" and webstorm prepended this:
//noinspection JSUnusedGlobalSymbols
When extending a library recently, I was also alerted by that "not used" inspection warning.
Think about why IntelliJ signals
Usually when doing refactoring all unused methods/parameters should be safe to be deleted (via Intellij's safe delete action).
This way the intend of IntelliJ (like Checkstyle and others) is to support our clean design. Since the unused methods are neither used internally (in src/java/main) nor externally tested (in src/java/test) they seem obsolete. So why not following the saying "When in doubt, throw it out".
When refactoring, that's mostly a true advice.
But if we are developing a library/API that is intended to be used by other codebases (modules/dependencies from the ouside), then we rather answer "When not used, get confused".
We are astonished about IntelliJ's warning. The methods should not be deleted, because they are actually intended to be used elsewhere. They are entry-points.
Then choose suitable solution
All of below solutions have one in commen:
Communicate through your code, so every IDE and developer can understood (e.g. add a test so it becomes used)
Tell your intent (e.g. to IntelliJ via reconfiguring Code Inspection)
Configure Inspection or Disable
As described in various earlier answers. With screenshots and navigation hints to IntelliJ's Code Inspection settings
Add a test
If you add a test for the unused (method, class etc.) you will benefit in 3 ways:
correctness: (previously) unused subject under test (SUT) is tested
communication: you clearly communicate to every reader, that and how your unused (method, class, etc.) should be used
clearance: now the unused finally got used. So IntelliJ's inspection would not find and warn anymore.
Add or mark as Entry Point
I saw the suggestion multiple times:
as optional dialog tab inside IntelliJ's Inspection Settings
as comment below top-ranked answer:
IMO better approach is to mark class as "entry point". – Tanya Jivvca Aug 18 at 8:46
in IntelliJ's forum: Code inspection: unused element - what is an entry point? (emphasis in below quote by me):
Add the element as an entry point. By default, all code in the global scope as well as tests is treated as reachable. If you know that a method or function is executed, you may add it as an entry point. The code inside the entry point is now executed and reachable, as well.
When you add an entry point, your source code files stay unaffected, and the element’s record is stored with the project under .idea\misc.xml.
Maybe the entry points funtion can work, where you can specify the code pattern that can disable the warning
Settings | Inspections | Declaration redundancy | Unused Declaration | entry point

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.

Naming convention for VB.NET private fields

Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines:
"Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields."
In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions?
I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently.
At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions.
It's personal preference, although there's widespread support for having some distinction. Even in C# I don't think there's one widely used convention.
Jeff Prosise says
As a matter of personal preference I typically prefix private fields with an underscore [in C#] ... This convention is used quite a lot in the .NET framework but it is not used throughout.
From the .NET Framework Design Guidelines 2nd Edition page 73.
Jeffrey Richter says
I make all my fields private and I prefix my instance fields with "m_" and my static fields with "s_" [in C#]
From the .NET Framework Design Guidelines 2nd Edition page 47. Anthony Moore (BCL team) also thinks using "m_" and "s_" is worth consideration, page 48.
Official guidelines are just that -- guidelines. You can always go around them. That being said we usually prefix fields with an underscore in both C# and VB.NET. This convention is quite common (and obviously, the Official Guidelines ignored).
Private fields can then be referenced without the "me" keyword (the "this" keyword is for C# :)
The design guidelines that you linked specifically state that they only apply to static public and protected fields. The design guidelines mostly focus on designing public APIs; what you do with your private members is up to you. I'm not positive but I'm relatively confident that private members are not considered when the compiler checks for CLS compliance, because only public/protected members come in to play there (the idea is, "What if someone who uses a language that doesn't allow the _ character tries to use your library?" If the members are private, the answer is "Nothing, the user doesn't have to use these members." but if the members are public you're in trouble.)
That said, I'm going to add to the echo chamber and point out that whatever you do, it's important to be consistent. My employer mandates that private fields in both C# and VB are prefixed with _, and because all of us follow this convention it is easy to use code written by someone else.
In VB.NET 4.0, most of you probably know you don't need to explicitly write getters and setters for your Property declarations as follows:
Public Property Foo As String
Public Property Foo2 As String
VB automatically creates private member variables called _Foo and _Foo2. It seems as though Microsoft and the VS team have adopted the _ convention, so I don't see an issue with it.
I don't think there is an official naming convention, but i've seen that Microsoft use m_ in the Microsoft.VisualBasic dll (via reflector).
I still use the _ prefix in VB for
private fields, so I'll have _foo as
the private field and Foo as the
property. I do this for c# as well and
pretty much any code I write.
Generally I wouldn't get too caught up
in "what is the right way to do it"
because there isn't really a "right"
way (altho there are some very bad
ways) but rather be concerned with
doing it consistently.
I haven't found anything better than the "_" for clarify and consistency. Cons include:
Not CLS compliant
Tends to get lost when VB draws horizontal lines across my IDE
I get around the lines by turning those off in the editor, and try not to think too much about the CLS compliance.
I agree with #lomaxx, it's more important to be consistent throughout the team than to have the right convention.
Still, here are several good places to get ideas and guidance for coding conventions:
Practical Guidelines and Best Practices for Microsoft Visual Basic and Visual C# Developers by Francesco Balena is a great book that addresses many of these issues.
IDesign Coding Standards (for C# and for WCF)
The .NET Framework Source Code (in VS2008)
I prefer to use the underscore prefix for private fields. I use lowercase first letter for the method parameters. I follow the guideline of having lowercase camelcase parameters for methods, which I regard as more important than the naming of private fields since it is part of the API for the class. . e.g.
Public Class Class1
Private _foo As String
Public Property Foo() As String
Get
Return _foo
End Get
Set(ByVal value As String)
_foo = value
End Set
End Property
Public Sub New(ByVal foo As String)
_foo = foo
End Sub
End Class
Using this pattern, you won't have any naming conflicts with the private field and your constructor parameter in C# or VB.NET.
I agree most important is not what style one uses but it being consistent.
With that said, the new MS/.NET styling for private fields tends to be _fooVar (underscore followed by a camelCased name)