1

I am new to Typescript, but with my JAVA Knowledge, I believe exporting functions breaks Encapsulation principles.

for example:

hello.ts
** Below method will be called from outside ***
 export const abcd=async()=>{
// some code
  dcb()

}
** 
1. Below method (dcb) is not used outside this file, do I need to export?
2. is it a best practise to export the method only for TDD development?
**
export const dcb=async()=>{
// some code
}

Questions:

  1. Does best practices say when to export a function and when not to?
  2. For TDD development, can we export any function to test it? isn't it a violation of Encapsulation Principle(I believe it's not a good Practice).

NOTE: In Typescript, we can have functions without classes; question is not related with Typescript classes.

1 Answer 1

1

Maybe someone can give a researched answer but I'm answering based on gut feel.

TDD doesn't make a difference to my answer.

  1. You should not export everything from a module; only functions that are used by consumers should be exported.

  2. Functions that are not exported from a module can still be covered in thorough unit tests through the methods that are exposed publicly.

  3. If you want to prioritise granular unit testing over a clean API then an option might be using a strict convention and adding a prefix underscore to those exported members that are not part of the public API. This would allow consumers to see at a glance which methods are for designed for consumption and those that are internal.

  4. If you have to regularly use conventions to help expose functions for unit testing then you could focus more on SOLID priniciples where you separate concerns and you might find it allows you to expose a wider conceptual model / public API which is accessible in tests. The message here is, perhaps components in the design have more than one responsibility and can be separated further and tested independently.

  5. Using JSDocs for exported functions to educate consumers of a module API. I would expect all functions that are designed for consumers to have a JSDoc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.