Guidelines for when to use Static class over instance class?

15,467

Solution 1

if it should be a collection of functions, then you'd use static classes. like :

int result = calculation.add(int p1,int p2);
float result = calculation.divide(int p1,int p2);

you can't say this on static classes:

Calculation mycalculator = new Calculation();

because they can not be instantiated. They can only contain static members.

Taken from here.

but if it'd be a member of a code, like apple in a tree, you'd use instance classes. each apple would have its own characteristics but it doesn't change the fact that it is an apple. and it's a part of the tree which contains multiple instances of the apple.

Apple apple1 = new Apple();
apple1.color = green;
apple1.age = newborn;
apple1.fallfromtree(speed);

Apple apple2 = new Apple();
apple2.color = red;

etc.

You can look here.

Solution 2

Static Classes are best used to create libraries of functions that will be called. Regular Classes are used to create objects that can be manipulated. It allows you to encapsulate the relations of a single bunch of code. Take, for instance, a point in Euclidian space. You could declare two floats and keep track of them individually, or you could use the following contract to declare how a point works.

class Point{
    float x;
    float y;

    Point(float x, float y);

    Point halfway(Point other);

    Line lineThrough(Point other);

    float distanceFrom(Point other);

    ...
}

This is a bit redundant, but it allows you to to write more readable code in the future - better keeping all your data encapsulated and well designed, making you a better programmer, because the equation of a line through two points goes from

float slope = (xone-xtwo)/(yone-ytwo);
float yintercept = yone-slope*xone;

to

Point p1 = new Point(xone, yone);
Point p2 = new Point(xtwo, ytwo);
Line linethrough = p1.lineThrough(p2);

Sorry the pseudocode is a bit Java informed. I have Java on the brain.

Share:
15,467
Dhananjay
Author by

Dhananjay

I am a software application programmer. I am interested in reading/writing analogy between software programming and real world.

Updated on July 08, 2022

Comments

  • Dhananjay
    Dhananjay almost 2 years

    Possible Duplicate:
    When to Use Static Classes in C#

    Can someone please provide guidelines , standard checkpoints on when to create static class and when to create instance class.

    Basically many a times I see while writing a code that the same thing could have been done using static class and methods and i get confused with many things.

    So far i know below check points :

    1. If object under the consideration can exists only once in entire application then it would come under "static"

    2. If a method does not use any field variable inside it then it can be static method.