4

I have this two parts of code which do the same thing.

But for you what is the best ? Using namespace or static class ?

    namespace MyMath {  
      const PI: number = 3.14;

      export function calculateCircumference(diameter: number): number {
        return diameter * PI;     
      }
      export function calculateRectangle(width: number, length: number): number {
        return width * length;     
      } 
    }

or

    class MyMathClass {  
      PI: number = 3.14;

      static calculateCircumference(diameter: number): number {  
        return diameter * PI;     
      }

      static calculateRectangle(width: number, length: number): number {
        return width * length;     
      } 
    }

Let me know what the best at your eyes ! Thank's

1

1 Answer 1

7

well, as you can read here Difference between classes and namespaces in typescript they are fairly similar in what they can achieve.

For me personally I mostly use classes. Even if they only contain static methods, which is kind of rare. You have the freedom to add new logic and now it maybe makes sense to have an instance of said class.

Namespaces in my opinion are just for grouping stuff. So grouping multiple classes, interfaces, etc. in one namespace. Especially important if you plan that other dev use your stuff. Then namespaces are really handy for them, to differentiate between own code and imported code.

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.