All else equal, how should files be ordered within a typical class/file?
For further actions, you may consider blocking this person and/or reporting abuse
All else equal, how should files be ordered within a typical class/file?
For further actions, you may consider blocking this person and/or reporting abuse
Scofield Idehen -
babar ali -
T.H. Jacobs -
Argho Dev -
Top comments (6)
Except for the following rough layout:
I stopped worrying about rearranging and ordering by visibility, member name or getter / setter types, for the following reasons:
Moving a method to its "correct" place can increase the likelihood for merge conflicts (when several people happen to work on the same file at the same time)
IDEs can present the structure of a class or file in any way you like. You can sort by name, filter out private methods, just show fields etc.
IDE code generators usually generate new method stubs right under the method you're working on. Even when those methods are private, I stopped moving them to the bottom of the class. I actually prefer them now being right under the public method that uses them. It makes the code much clearer and easier to follow to me.
Mistakes happen. I want to worry less. I've been almost OCD for most of my life, and letting go of those things makes me happier π
I typically avoid classes in JS.
I do put all functions in separate files unless they are really small and make sense together.
I group these files in folders that make sense for the category of work.
I always add a index file that exports the other methods.
There is 2 ways I do this: if the file performs one task I will call the primary function main and have supporting functions private and with logical names, if the file performs several task in the same general category I will give it a logical name and again, make supporting functions private with good name. in most cases I will try to do one class per file it just is better organized that way. as for variable I will just give a short name based on what they do and leave it at that, in java and similar languages I try to declare the variable at the top of the function or class, in Kotlin and languages that use a var/val like system they are declared as needed.
Class {
static variables;
private variables;
protected variables;
public variables; // although real world apps should not expose public variables, keep them encapculated
ctor() {}
public method() {}
protected _method() {}
private _method() {}
}
Personally, I tend to write classes of 40 lines or less so I usually just define the public methods up top and then define everything else as close to where it is used as possible.
If I need to write a bigger class I will probably switch to a standard ordering.
I use:
-->Const, private variables, dependency's, Global variables
-->Constructor
-->Public Methods
-->Private Methods