Effective Java-Use tagged class with caution

Source: Internet
Author: User

The original title of the author is <Prefer class hierarchies to tagged classes, that is, the class hierarchy is better than the tagged class.


I don't know if tagged class says that, in fact, the author refers to tagged class is a class that describes a variety of abstractions, depending on a field to determine the different instances.
Here is an example of a book that uses shape and part of a field to represent the length of a shape and calculates the area, and the brain complements what is tagged class:

  class Figure {enum Shape {RECTANGLE, CIRCLE};    Tag field-the shape of this figure final shape shape;    These fields was used only if shape is RECTANGLE double length;    Double width;    This field was used only if the shape is CIRCLE double radius;        Constructor for Circle figure (double radius) {shape = shape.circle;    This.radius = radius;        }//Constructor for Rectangle figure (double length, double width) {shape = Shape.rectangle;        this.length = length;    This.width = width;        } double area () {switch (shape) {Case Rectangle:return length * width;        Case Circle:return Math.PI * (RADIUS * radius);        Default:throw new Assertionerror (); }    }}


It is not difficult to see what information this class wants to convey, nor is it difficult to see that there are many flaws in such a way.
Although it is possible to understand what it means, it is not very readable because various implementations are squeezed into a class.
Different implementations are described in a class that uses different field depending on the implementation, that is, field cannot be declared final. (Do you want to handle the unused field in the constructor?)
Although insignificant, memory does exist in meaningless use.
Not OO.


Although the previous article on the class level is useless, in fact, the class level is used to solve this problem, and the above tagged class is a non-OO way to imitate the class hierarchy.
The tagged class is transformed into a class hierarchy, first to abstract the behavior in the tagged class and provide it with an abstract class.
Take the figure above for example, we need a method--area.
Next you need to define a specific subclass for each tag, i.e. circle and rectangle in the example.
Then provide the corresponding field for the subclass, which is the width, length of radius and rectangle in circle.
Finally, the corresponding implementation of the abstract method is provided for the subclass.
In fact, it is not necessary to explain the conversion steps, because OO itself is a very natural thing.


The conversion results are as follows:

abstract class Figure {    abstract double area();}class Circle extends Figure {    final double radius;    Circle(double radius) {        this.radius = radius;    }    double area() {        return Math.PI * (radius * radius);    }}class Rectangle extends Figure {    final double length;    final double width;    Rectangle(double length, double width) {        this.length = length;        this.width = width;    }    double area() {        return length * width;    }}class Square extends Rectangle {    Square(double side) {        super(side, side);    }}


The benefits of doing so are obvious,
The code is simple and clear, no boilerplate code;
Types are independent of each other and are not affected by irrelevant field, and field can be declared final.
Subclass rows can be extended independently of each other.


Back to the original tagged class, is it really useless?
If I use this class, I just need to use the corresponding arguments when invoking the constructor to get the desired instance.
Just like the strategy pattern.
Of course, the tagged class may be considered a strategy pattern (it should be a characteristic of a behavior rather than an instance feature), but the policy pattern is not used in Java.


Typically, a policy is to specify specific behavior by passing a function through the caller.
But Java does not have a function pointer, so we use object reference to implement the policy pattern, that is, the method that invokes the object.
For this "vector", which is merely a method, that is, an instance of an object equivalent to a method pointer, the author calls it a function object.


For example, we have such a specific strategy (concrete strategy):

class StringLengthComparator {    private StringLengthComparator() {    }    public static final StringLengthComparator INSTANCE = new StringLengthComparator();    public int compare(String s1, String s2) {        return s1.length() - s2.length();    }}


A reference to a specific policy can be said to be a function pointer.
The abstraction of a specific strategy becomes a policy interface (strategy interface).
For the example above, there is a comparator in java.util:

public interface Comparable<T> {    int compare(T o1, T o2);    boolean equals(Object obj);}


As a result, we may use anonymous classes to pass a specific policy when we are using it:

Arrays.sort(stringArray, new Comparator<String>() {    public int compare(String s1, String s2) {        return s1.length() - s2.length();    }});


The code description seems to be the case, I just pass a specific strategy where I want to use it.
The disadvantage is obvious--you need to create an instance each time you call.
But what can be done? After implementing the policy interface in a host class for each of the specific strategies that might be used, make field and final declaration?
It feels silly, but you can really think about it because there are other benefits to doing so.
For example, specific policies can be more visually named than anonymous classes, and specific policies can implement other interfaces.


The code is as follows:

// Exporting a concrete strategyclass Host {    private static class StrLenCmp        implements Comparator<String>, Serializable {            public int compare(String s1, String s2) {                return s1.length() - s2.length();            }    }    // Returned comparator is serializable    public static final Comparator<String> STRING_LENGTH_COMPARATOR = new StrLenCmp();    ... // Bulk of class omitted}

Effective Java-Use tagged class with caution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.