Java developers always use private access level for methods which are not used outside of this class. There are known benefits of doing so but from other side we increase complexity of unit tests. In most of cases our code is not used by any other services/APIs and we actually don't care of 'private' benefits. But what I believe we do care is to create readable simple unit tests. Considering this, why do not create all methods in class as 'package-private' by default and make them 'private' only in case when we really need this?
Why private access for methods is more preferable than package-private?
370 views Asked by Aliaksei Yatsau At
1
There are 1 answers
Related Questions in JAVA
- I need the BIRT.war that is compatible with Java 17 and Tomcat 10
- Creating global Class holder
- No method found for class java.lang.String in Kafka
- Issue edit a jtable with a pictures
- getting error when trying to launch kotlin jar file that use supabase "java.lang.NoClassDefFoundError"
- Does the && (logical AND) operator have a higher precedence than || (logical OR) operator in Java?
- Mixed color rendering in a JTable
- HTTPS configuration in Spring Boot, server returning timeout
- How to use Layout to create textfields which dont increase in size?
- Function for making the code wait in javafx
- How to create beans of the same class for multiple template parameters in Spring
- How could you print a specific String from an array with the values of an array from a double array on the same line, using iteration to print all?
- org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty
- Accessing Secret Variables in Classic Pipelines through Java app in Azure DevOps
- Postgres && statement Error in Mybatis Mapper?
Related Questions in OOP
- How do I apply the interface concept with the base-class in design?
- Creating multiple instances of a class with different initializing values in Flutter
- System.InvalidCastException while inheriting a class
- How to add logging to an abstract class in php
- creating cutscenes using OOP and pygame
- What effect does the `virtual` modifier have on an interface member?
- How to pass the value of a function of one class to a function of another with the @property decorator
- Creating a C++ Class Instance for every server request?
- Dart OOP programming
- Containing Object Design
- Clean architecture/OOP and optimization: how to organize for classes with same logic
- How to get 5 LEVEL hierarchy users from database using PHP and MYSQL
- TypeError: unsupported operand type(s) for /: 'property' and 'complex'
- How can I refer to this metaclass inside a metaclass without specifying its name in the code?
- Why customed "-eq" do twice in Powershell?
Related Questions in PRIVATE
- Why this can't happen? properties {get; set;} x Structs
- Azure Databricks to Cognitive Search connection timing out
- Deploy Flask Microblog in private ec2 with private RDS
- What are the best ways to protect private keys in code developed for the .NET framework?
- Why is there no change in the value of instance attribute even if I wrote my code to perform it (python)
- To access private arrays, classes are double-wrapped
- how to return a std::expect<T, E> from a function where T's move/copy constructor are deleted and has a private constructor
- Is there a way to add a friend class that is itself but with different template arguments?
- WooCommerce - Add a private item to the cart via 'add_to_cart'
- Problem with a mirc script to open a popup message when a user open a private chat with me
- How can I create routes by roles with next-auth/authjs nextjs/13/14?
- Analyzer Option or Lint Option for Flutter private variables?
- Separating git commits for private and public
- Assign a value to a variable in private section of class in C++
- Github Private repo access
Related Questions in ACCESS-LEVELS
- How to verify user's access is still valid before accessing each page in next.js with nextauth?
- Can I customize the HTML, CSS, and JS for UI5 / Fiori?
- method must be declared internal because its parameter uses an internal type
- How to write the constructor instead of using Lombok to access public level?
- How to avoid having large files in Swift?
- Hide Interface from assembly
- ModelMapper mapping enum to same enum returns null
- Automatically change access level on a user in Azure DevOps
- Xcode Playgrounds: Source files are unable to be accessed by each other
- Open function in a non-open class
- Google AdWords account permissions via api
- Displaying levels of access for different types of accounts in a UML diagram
- What's the difference of `private` and `fileprivate` class in the same file in Swift?
- How to test private/internal extension methods?
- "Best" way to access IO.FileInfo Protected property (OriginalPath)?
Related Questions in PACKAGE-PRIVATE
- Why package-private classes are not accessible from nested packages?
- How to make relation between entities from different packages and keep encapsulation?
- howt to use mBagOfTags in ViewModel android?
- Javascript: Export things inside the module, internally
- How can I open class only to test class?
- Inheritance at package visibility in Java
- javadoc generate "extends Object" instead of the real class when the parent class is package private and comes from another module
- Lombok builder package scope
- Why JUnit 5 default access modifier changed to package-private
- Package-private member visibility in complex inheritance / package combinations - Qiuck General Rule to verify visibility
- Adding an external class with the same package name and breaking encapsulation
- Are packages (that share a name) combined during compliation?
- How to create mock object of a class which is package private
- Is it possible to extend a package private class defined in a 3rd party jar in Scala
- Why private access for methods is more preferable than package-private?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
I would not say that it is preferable.
Both practices are acceptable and don't shock me.
Now
privateshould be favored as much as possible as it prevents undesirable coupling whilepackage-privatethat creates a little more coupling should be used with relevancy.Even as you develop a library to be used by some clients, using the package modifier is not bad as the classes in the
package-privatedoesn't make part directly of the API.Reversely, unit testing and
privatemodifiers are not incompatible at all.I agree that using
package-privatemodifier instead ofprivateallows to test/mock/switch easily members of classes.In some cases, this practice is acceptable.
Now generalizing this is before all a design choice.
Personally I use the
package-privatemodifier only as really relevant (a real issue for testing or a internal processing to share among other classes of the same package) because beyond making unit testing easier (which is a good point), I think that this kind of practice may favor a design that couples the classes more strongly than required.For example, suppose in a
Bclass you may access a field/method of aAclass instance because these are in the same package.Suppose that conceptually this field make part of a very internal part of the
Aimplementation and that it have not be known by other classes to allows to change it later.But as this field/method is package-private, now nothing prevents you from making it as you can.
I don't like that.
To finish, I would say that you should not worry about unit testing of
privatemethods.Internals don't make part of the API. You don't need to test it.
Now if the private method is invoked multiple times or you really need to test this processing, nothing prevents you from extracting it in another class to make it testable and to have a way to mock the processing if required (to avoid test it multiple times).