简体   繁体   中英

Java static predicate naming convention

Let's say I want to write isSubdirectory static function in my FileUtils helper class. This function would look like:

class FileUtils {
  public static boolean isSubdirectory(File child, File parent) {
    // ...
  }
}

Or I could flip parent and child parameters:

class FileUtils {
  public static boolean isSubdirectory(File parent, File child) {
    // ...
  }
}

And I cannot choose which order is right...

In Kotlin there would not be any doubts: just declare extension function:

fun File.isSubdirectory(parent: File) {
  // ...
}

With an eye on kotlin I have invented mnemonic rule: first parameter in static function should be considered as this (I'm not the first who invented this rule. I saw many people also using it). So in this example I'd prefer placing child as first parameter.

But the question is: is this rule is already formalized and has well known name? I've tired to repeat this rule to people who don't know it and I wish I could simply refer to this rule by it's name.

I'm not sure that there's a name or any real formalization. At best, it's just a common convention to have the first parameter look like the this . Although rarest, the "this last" convention also exists, more in C and early C++ (Example: stdio with fread/fwrite)

There also exist conventions based on the argument type; for example promoting the following order:

  • Collection and other objects with generic parameters
  • Arrays of objects
  • Objects without generics
  • String
  • Arrays of primitive types, eg byte[]
  • double, float
  • long, int, short, byte
  • boolean

There also exist the more or less exact opposite order. Other conventions also tend to group arguments by their type, prefering method(String, String, int, int) rather than method(String, int, String, int) .

As you can see, there are a lot of conventions that exist. I'm not sure that any of them has a name, and that any is really much more used than any other. It isn't as clear as camelCase vs. snake_case for example, which almost no one contradict.

What you can keep from all that is the following: put the arguments in the order that looks the most logical and straightforward to you. The most important is to stay consist in the entire project, ie don't write isFileX(a,b) and then isFileY(b,a) for example, a fortiori if the two methods are in the same class. IN case of doubt, don't hesitate to ask other people working on your project what they think is the best.

For your particular case, it's reasonnable to put child first because of the "this first" rule, but it's as reasonnable to put the parent first, as it's also a common convention for example in GUI frameworks. It's up to you to decide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM