110 likes | 196 Views
Classes & Interfaces. Minimizing Accessibility and Security Holes. Introduction. Classes and Interfaces are the backbone of Java Good design = usable, robust, and flexible 1. Minimize accessibility 2. Use private data members w/ accessors. Minimize Accessibility of Classes and Members.
E N D
Classes & Interfaces Minimizing Accessibility and Security Holes
Introduction • Classes and Interfaces are the backbone of Java • Good design = usable, robust, and flexible • 1. Minimize accessibility • 2. Use private data members w/ accessors
Minimize Accessibility of Classes and Members • Information hiding – degree to which the module hides internal data • Use multiple modules and keep them hidden!
Advantages of multi-hidden modules • Allows modules to be developed, tested, optimized, and modified individually -> SPEED. • Eases maintenance -> will not harm other modules.
Access Control Mechanisms • Private • Protected • Public
Rules of Accessibility • Make each class or member as inaccessible as possible. • Top-Level classes and interfaces = package private or public • If a method overrides supermethod, it cannot have lower level accessibility (compiler will catch this) • Public classes should rarely have public fields. Except for public static finals.
Example • Nearly always wrong to have public static final array field //potential security hole Public static final Type[] VALUES = {…}; Better Version: Private static final Type[] PRIVATE_VALUES = {…}; Public static final List VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));
Use Private data w/ Accessor methods • Use synchronized methods to protect data from corruption. • Multi threads may result in altering members concurrently.
Example Class Test { public int[] intArray = new int[10]; . . . } . . . Test tst = new Test(); Thread t = new Thread(tst); t.start(); Tst.intArray = null;
JUST ADD PRIVATE! Class Test { private int[] intArray = new int[10]; . . . } . . . Test tst = new Test(); Thread t = new Thread (tst); t.start(); int [] temp = tst.integerArray(); temp[5] = 1;