Java best practice: Class with only static methods -


i have application have class called plausibilitychecker. class has static methods, checkzipcodeformat or checkmailformat. use them in gui classes check input before sending lower layer.

is practice? thought i'd go static methods don't have care passing instance gui classes or having instance field in each gui class doesn't reference gui object.

i noticed files class of java nio has static methods assume can't horribly wrong.

i you're doing right. apart of that, advices utility class:

  • make sure doesn't have state. is, there's no field in class unless it's declared static final. also, make sure field immutable e.g. strings.
  • make sure cannot super class of other classes. make class final other programmers cannot extend it.
  • this 1 debatable, may declare no-arg constructor private, no other class create instance of utility class (using reflection or similar do, there's no need go protective class). why may not this? well, strange case want/need inject instance of utility class e.g. through interface rather directly using along class. here's example of this. design odd may happen (as shown in link above), if not run in such case, best advice keep constructor private.

there lot of libraries provide utility classes in order programmers our work. 1 of known apache common set of libraries. it's open source , can check code see how design these utility classes in order create yours. (disclaimer: not work or support these libraries, i'm happy user of them)

important note: avoid using singleton utility class.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -