I've been reading the book Clean Code: A Handbook of Agile Software Craftsmanship and in chapter six pages 95-98 it clarifies about the differences between objects and data structures:
Objects hide their data behind abstractions and expose functions that operate on that data. Data structures expose their data and have no meaningful functions.
Object expose behavior and hide data. This makes it easy to add new kinds of objects without changing existing behaviors. It also makes it hard to add new behaviors to existing objects.
Data structures expose data and have no significant behavior. This makes it easy to add new behaviors to existing data structures but makes it hard to add new data structures to existing functions.
I'm a tad bit confused whether some classes are objects or data structures. Say for example HashMaps in java.util, are they objects? (because of its methods like put(), get(), we dont know their inner workings) or are they data structures? (I've always thought of it as data structures because its a Map).
Strings as well, are they data structures or objects?
So far majority of the code I've been writing have been the so called "hybrid classes" which try to act as an object and a data structure as well. Any tips on how to avoid them as well?
The distinction between data structures and classes/objects is a harder to explain in Java than in C++. In C, there are no classes, only data structures, that are nothing more than "containers" of typed and named fields. C++ inherited these "structs", so you can have both "classic" data structures and "real objects".
In Java, you can "emulate" C-style data structures using classes that have no methods and only public fields:
public class VehicleStruct
{
public Engine engine;
public Wheel[] wheels;
}
A user of VehicleStruct knows about the parts a vehicle is made of, and can directly interact with these parts. Behavior, i.e. functions, have to be defined outside of the class. That's why it is easy to change behavior: Adding new functions won't require existing code to change. Changing data, on the other hand, requires changes in virtually every function interacting with VehicleStruct. It violates encapsulation!
The idea behind OOP is to hide the data and expose behavior instead. It focuses on what you can do with a vehicle without having to know if it has engine or how many wheels are installed:
public class Vehicle
{
private Details hidden;
public void startEngine() { ... }
public void shiftInto(int gear) { ... }
public void accelerate(double amount) { ... }
public void brake(double amount) { ... }
}
Notice how the Vehicle could be a motorcycle, a car, a truck, or a tank -- you don't need to know the details. Changing data is easy -- nobody outside the class knows about data so no user of the class needs to be changed. Changing behavior is difficult: All subclasses must be adjusted when a new (abstract) function is added to the class.
Now, following the "rules of encapsulation", you could understand hiding the data as simply making the fields private and adding accessor methods to VehicleStruct:
public class VehicleStruct
{
private Engine engine;
private Wheel[] wheels;
public Engine getEngine() { return engine; }
public Wheel[] getWheels() { return wheels; }
}
In his book, Uncle Bob argues that by doing this, you still have a data structure and not an object. You are still just modeling the vehicle as the sum of its parts, and expose these parts using methods. It is essentially the same as the version with public fields and a plain old C struct -- hence a data structure. Hiding data and exposing methods is not enough to create an object, you have to consider if the methods actually expose behavior or just the data!
When you mix the two approaches, e.g. exposing getEngine() along with startEngine(), you end up with a "hybrid". I don't have Martin's Book at hand, but I remember that he did not recommend hybrids at all, as you end up with the worst of both worlds: Objects where both data and behavior is hard to change.
Your questions concerning HashMaps and Strings are a bit tricky, as these are pretty low level and don't fit quite well in the kinds of classes you will be writing for your applications. Nevertheless, using the definitions given above, you should be able to answer them.
A HashMap is an object. It exposes its behavior to you and hides all the nasty hashing details. You tell it to put and get data, and don't care which hash function is used, how many "buckets" there are, and how collisions are handled. Actually, you are using HashMap solely through its Map interface, which is quite a good indication of abstraction and "real" objects.
Don't get confused that you can use instances of a Map as a replacement for a data structure!
// A data structure
public class Point {
public int x;
public int y;
}
// A Map _instance_ used instead of a data structure!
Map<String, Integer> data = new HashMap<>();
data.put("x", 1);
data.put("y", 2);
A String, on the other hand, is pretty much an array of characters, and does not try to hide this very much. I guess one could call it a data structure, but to be honest I am not sure if much is to be gained one way or the other.
This is what, I believe, Robert. C. Martin was trying to convey:
Data Structures are classes that simply act as containers of structured data. For example:
public class Point {
public double x;
public double y;
}
Objects, on the other hand, are used to create abstractions. An abstraction is understood as:
a simplification of something much more complicated that is going on under the covers The Law of Leaky Abstractions, Joel on Software
So, objects hide all their underpinnings and only let you manipulate the essence of their data in a simplified way. For instance:
public interface Point {
double getX();
double getY();
void setCartesian(double x, double y);
double getR();
double getTheta();
void setPolar(double r, double theta);
}
Where we don't know how the Point is implemented, but we do know how to consume it.
As I see it , what Robert Martin tries to convey, is that objects should not expose their data via getters and setters unless their sole purpose is to act as simple data containers. Good examples of such containers might be java beans, entity objects (from object mapping of DB entities), etc.
The Java Collection Framework classes, however, are not a good example of what he's referring to, since they don't really expose their internal data (which is in a lot of cases basic arrays). It provides abstraction that lets you retrieve objects that they contain. Thus (in my POV) they fit in the "Objects" category.
The reasons are stated by the quotes you added from the book, but there are more good reasons for refraining from exposing the internals. Classes that provide getters and setters invite breaches of the Law of Demeter, for instance. On top of that, knowing the structure of the state of some class (knowing which getters/setters it has) reduces the ability to abstract the implementation of that class. There are many more reasons of that sort.
An object is an instance of a class.
A class can model various things from the real world. It's an abstraction of something (car, socket, map, connection, student, teacher, you name it).
A data structure is a structure which organizes certain data in a certain way.
You can implement structures in ways different that by using classes (that's what you do in languages which don't support OOP e.g.; you can still implement a data structure in C let's say).
HashMap in java is a class which models a map data structure using hash-based implementation, that's why it's called HashMap.
Socket in java is a class which doesn't model a data structure but something else (a socket).
A data structure is only an abstraction, a special way of representing data. They are just human-made constructs, which help in reducing complexity at the high-level, i.e. to not work in the low-level. An object may seem to mean the same thing, but the major difference between objects and data structures is that an object might abstract anything. It also offers behaviour. A data structure does not have any behaviour because it is just data-holding memory.
The libraries classes such as Map, List,etc. are classes, which represent data structures. They implement and setup a data structure so that you can easily work with them in your programs by creating instances of them (i.e. objects).
Data structures(DS) are an abstract way of saying that a structure holds some data'. HashMap with some key value pairs is a data structure in Java. Associated arrays are similarly in PHP etc. Objects is a little lower than the DS level. Your hashmap is a data structure. now to use a hashmap you create an 'object' of it and add data to that object using put method. I can have my own class Employee which has data and is thus a DS for me. But to use this DS to do some operations like o see if the employee is a male or a female colleague i need an instance of an Employee and test its gender property.
Don't confuse objects with data structures.
An object is an instance of a class. A class can define a set of properties/fields that every instance/object of that class inherits. A data structure is a way to organize and store data. Technically a data structure is an object, but it's an object with the specific use for holding other objects (everything in Java is an object, even primitive types).
To answer your question a String is an object and a data structure. Every String object you create is an instance of the String class. A String, as Java represents it internally, is essentially a character array, and an array is a data structure.
Not all classes are blueprints for data structures, however all data structures are technically objects AKA instances of a class (that is specifically designed to store data), if that makes any sense.
Your question is tagged as Java, so I will reference only Java here.
Objects are the Eve class in Java; that is to say everything in Java extends Object and object is a class.
Therefor, all data structures are Objects, but not all Objects are data structures.
The key to the difference is the term Encapsulation.
When you make an object in Java, it is considered best practice to make all of your data members private. You do this to protect them from anyone using the class.
However, you want people to be able to access the data, sometimes change it. So, you provide public methods called accessors and mutators to allow them to do so, also called getters and setters. Additionally, you may want them to view the object as a whole in a format of your choosing, so you can define a toString method; this returns a string representing the object's data.
A structure is slightly different.
It is a class.
It is an Object.
But it is usually private within another class; As a Node is private within a tree and should not be directly accessible to the user of the tree. However, inside the tree object the nodes data members are publicly visible. The node itself does not need accessors and mutators, because these functions are trusted to and protected by the tree object.
Keywords to research: Encapsulation, Visibility Modifiers
Related
I have lot of static/constant data which I want to store, this data is also related with each other. I can use lot enums referencing each other forming a tree or a graph. Or simply use tables or database enums and store values in them and create corresponding classes and respective relationships. The data I have is constant and is certainly not going to change. I might have to also consider internationalization in near future. I will be using this constant data as filter to various other data.
I am tempted to use enums as it gives me immutability by default, but seeing the complexity of relationship between data, like I might have to sacrifice with inheritance, I am also little apprehensive of enums. And populating these enum classes from database and internationalization might be little more tricky. And at later stage hoping that it will scale and embrace the complexity with ease are the areas of concern as I would not like to revert from the mid way.!
---Update---
I have not seen examples of enums related(associations) with each other, containing fields of complex types referencing other enums. Can in this type of cases enums replace classes when data is constant.
Is there any objective way to look at this problem.
To understand better, I have similar classification like below.
Animal Kingdom having tree hierarchy
While this Question is likely too broad for Stack Overflow, a few thoughts.
Enums
You may not fully understand the enum facility in Java. See the Oracle Tutorial, and see the Enum class doc.
An enum is a class, a regular Java class, a subclass of Enum. The only thing special is that syntactic sugar that automatically instantiates the static instances you define and name. Otherwise, they are normal classe:
Your enums can carry member variables.
Your enums can have constructors, and you can pass arguments to those constructors.
Your enums can offer other methods, and you can pass arguments to those methods.
You can even pass instances of one enum as arguments to methods of another enum’s instances – just as you might pass instances of an enum to instances of other non-enum classes. Each enum instance is just an object, plain and simple, saved as a static reference on the enum-defining class.
Example:
public enum Food { HERBIVORE, OMNIVORE, CARNIVORE ; } // Syntactic sugar for automatically instantiating these named static instances of this class type.
…and…
public enum Animal {
RABBIT( Food.HERBIVORE ) ,
DOG( Food.OMNIVORE ) ,
CAT( Food.CARNIVORE ) ;
// Member variables.
public Food eats ;
// Constructor
Animal( Food foodType ) {
this.eats = foodType ; // Assign an instance of another enum to this instance of this enum.
}
}
Limitations of enums
While more powerful and useful than in other languages, there are limitations.
Compile-time
Firstly, enums are defined at compile-time. If your values change at runtime, perhaps you want to add or delete items, then enums are not appropriate.
Permanently in memory
Also, enums are static. This means when first used, all the objects of that enum class are instantiated immediately and held in memory throughout the execution of your app. So they are never retired from memory until program ends. So having an enormous number of them might be a burden on memory.
Understand that your can collect enum instances. See the EnumSet and EnumMap classes for fast-to-execute and low-memory usage collections of enum instances. Search Stack Overflow for much coverage on this topic. And be aware that every enum carries a values() method that returns an array of its values, yet this method is mysteriously not listed in the JavaDoc.
As for your mention inheritance, your enums by definition are subclasses of Enum class. So they cannot inherit from any other class you may have in mind, as Java does not support multiple-inheritance. Your enums can implement one or more interfaces. In later version of Java, an inheritance can carry implementation code by way of new default methods, so you can pass along some code that way.
Internationalization
Internationalization and localization seems to be an orthogonal issue. You can add a method on your enum to generate localized String representation of their value. As an example, see DayOfWeek::getDisplayName and Month::getDisplayName enum methods.
Database
If you want to dynamically define your values at runtime, or you have zillions of them, then a database is the way to go. A serious database such as Postgres is designed to manage memory, handle concurrency, and execute efficiently.
You can even combine enums with the database. For example, localization. You might have enum values defined at compile-time, but their getDisplayName method does a lookup into a database to find the French or Arabic translation. That translation value in the database can be updated during runtime by running SQL INSERT or UPDATE commands via JDBC.
Recursive hierarchical relationships
If you are trying to represent relationships of a hierarchy of arbitrary depth, that is a whole other topic I'll not address here other than to say that is often implemented with recursion. Search Stack Overflow and other sources to learn more.
As a rule of thumb, I only involve a database when the values are likely to change faster than code release cycles, and when it's possible or likely that someone who is not me is going to change them. Making the code depend on a running (and available) database means that when some DBA takes the database down for maintenance then your application can't be started.
What is the difference between following two class in terms of data hiding(encapsulation).
In below example , I can access the value of member by making it public.
Eg: 1
public class App {
public int b = 10;
public static void main(String[] args) {
System.out.println(new App().b);
}
}
In below example, I can access the value of member by using getter method.
Eg : 2
class DataHiding
{
private int b;
public DataHiding() {
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
In both the above examples, I can access the value of member. Why Eg : 2, is called data hiding (encapsulation) ? If its not hiding the data.
Why Eg : 1 is not called encapsulated ?
What is it about
As you tagged this question with both java and object oriented programming oop, I suppose you are implicitly thinking about Java Beans. Nevertheless this is a question quite common across languages, take the wikipedia page on this matter :
In programming languages, encapsulation is used to refer to one of two
related but distinct notions, and sometimes to the combination1
thereof:
A language mechanism for restricting access to some of the object's
components.
A language construct that facilitates the bundling
of data with the methods (or other functions) operating on that
data.
Some programming language researchers and academics use the first
meaning alone or in combination with the second as a distinguishing
feature of object-oriented programming, while other programming
languages which provide lexical closures view encapsulation as a
feature of the language orthogonal to object orientation.
The second definition is motivated by the fact that in many OOP
languages hiding of components is not automatic or can be overridden;
thus, information hiding is defined as a separate notion by those who
prefer the second definition.
So encapsulation is not really about hiding data or information it about enclosing pieces of data in a language component (a class in Java). A Java Beans encapsulate data.
That being said, while encapsulation is one of the main feature of object oriented programming paradigm, at some point in the history of language design it was seen as not enough to help design better software.
History
One key practice to achieve better software design is decoupling, and encapsulation helps on that matter. Yet a cluster of data was not enough to help achieve this goal, other efforts in OOP pioneering were made in different language at that time, I believe SIMULA is the earliest language to introduce some kind of visibility keywords among other concepts like a class. Yet the idea of information hiding really appears later in 1972 with data that is only relevant to the component that uses it to achieve greater decoupling.
But back to the topic.
Answers to your questions
In this case data is encapsulated and public
This is commonly known as a global variable and it is usually regarded as a bad programming practice, because this may lead to coupling and other kind of bugs
Data is encapsulated and public (through method accessors)
This class is usually referred to as a Java Bean, these are an abomination if used in any other than what they were designed for.
These object were designed to fulfill a single role and that is quite specific is according to the specification
2.1 What is a Bean?
Let's start with an initial definition and then refine it:
“A Java Bean is a reusable software component that can be manipulated visually in a builder tool.”
Why is it an abomination nowadays ? Because people, framework vendors usually misuse them. The specification is not enough clear about that, yet there's some statement in this regard :
So for example it makes sense to provide the JDBC database access API as a class library rather than as a bean, because JDBC is essentially a programmatic API and not something that can be directly presented for visual manipulation.
I'd rather quote Joshua Bloch (more in this question and answer) :
"The JavaBeans pattern has serious disadvantages." - Joshua Bloch, Effective Java
Related points
As explained above one key practice to achieve better software is decoupling. Coupling has been one of the oldest battlefront of software engineers. Encapsulation, information hiding have a lot to do with the following practices to help decoupling for numerous reasons:
the Law of Demeter, breaking this law means the code has coupling. If one has to traverse a whole data graph by hand then, there's no information hiding, knowledge of the graph is outside of the component, which means the software is therefore less maintainable, less adaptable. In short : refactoring is a painful process. Anemic domain model suffer from that, and they are recognized as an anti-pattern.
A somehow modern practice that allows one to not break the Law of Demeter is Tell, Don't Ask.
That is, you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.
immutability, if data has to be public it should be immutable. In some degree if data is not needed, one module can introduce side effects in another ; if this was true for single threaded programs, it's even more painful with multi-threaded softwares. Today softwares and hardware are getting more and more multi-threaded, threads have to communicate, if an information has to be public it should be immutable. Immutability guarantee thread-safety, one less thing to worry about. Also immutability has to be guaranteed on the whole object graph.
class IsItImmutable {
// skipping method accessors for brevity
// OK <= String is immutable
private final String str;
// NOK <= java.util.Date is mutable, even if reference is final a date can be modified
private final Date date;
// NOK <= Set operations are still possible, so this set is mutable
private final Set<String> strs;
// NOK <= Set is immutable, set operations are not permitted, however Dates in the set are mutable
private final Set<Date> udates = Collections.unmodifiableSet(...);
// OK <= Set is immutable, set operations are not permitted, String is immutable
private final Set<String> ustrs = Collections.unmodifiableSet(...);
}
Using mutators and accessors hides the logic, not the name of the methods. It prevents users from directly modifying the class members.
In your second example, the user has no idea about the class member b, whereas in the first example, the user is directly exposed to that variable, having the ability to change it.
Imagine a situation where you want to do some validation before setting the value of b, or using a helper variable and methods that you don't want to expose. You'll encapsulate the logic in your setter and by doing that, you ensure that users cannot modify the variable without your supervision.
Encapsulation is not data hiding it is information hiding. You are hiding internal structure and data implementation, as well as data access logic.
For instance you can store your integer internally as String, if you like. In first case changing that internal implementation would mean that you have to also change all code that depends on b being an int. In second case accessor methods will protect internal structure and give you int, and you don't have to change the rest of the code if internals have changed.
Accessor methods also give you opportunity to restrict access to the data making it read-only or write-only in addition to plain read-write access. Not to mention other logic that can verify integrity of data going into the object as well as changing object state accordingly.
What happens if you want to retrieve the state of B without being able to change its value? you would create the getter but not the setter, you can't accomplish that by accessing B as a public int.
Also, in both methods get and set, if we had a more complex object, maybe we want to set or get some property or state of the object.
Example.
private MyObject a;
public setMyObjectName(String name){
MyObject.name = name;
}
public getMyObjectName(){
return MyObject.name;
}
This way we keep the object encapsulated, by restricting access to its state.
In java, all methods are virtual. This means, that if you extend some class, you can override the result of a method. Imagine for example the next class (continuing on your example):
class DataHidingDouble extends DataHiding{
public int getB(){
return b*2;
}
}
this means that you maintain control over what b is to the outer world in your subclass.
imagine also some subclass where the value of b comes from something that is not a variable, eg. a database. How are you then going to make b return the value if it is a variable.
It hides the data, not the value. Because the class is responsible for maintaining the data, and returning the correct value to the outside world.
Is it possible to retrieve a map stored in a different class?
For eg:
I have Class A in which I have the below map:
Map<String,List<Names>> map=new HashMap<String,List<Names>>();
map.put("Details", Names);
Is it possible to retrieve the map in Class B?
Is it possible to retrieve [or retrieve from] the map in Class B?
Yes it is. And there are a variety of ways to do it. For example:
You could make the Map variable public (almost certainly a bad idea!)
You could implement a public getter that returns the Map (probably not a good idea ...)
You could implement a public getter that returned a read-only wrapper for the (private) Map.
You could implement a public method that looks up an entry in the (private) Map.
But it is not necessarily a good thing to do these things. One of the principles of Object Oriented Programming is that a class should encapsulate its state. If your class B can access a map that is (for the sake of argument) internal to your class A, then the encapsulation is weakened or broken in the process. (Now, it might be appropriate to have loose encapsulation ... but you need to understand the issues and think through the consequence for your particular circumstances.)
What I'm saying is that you most likely need to find / read a tutorial (or text book) on OO programming to help you understand whether what you are trying to do is the right thing to do.
I am struggling to explain oop concepts in java.
A major tenet in oop is that objects have methods; so Object.method(); works.
I am contrasting this with procedural programming in which one must do method(Object).
Is this called encapsulation?
What are the advantages of the oop way?
That's a big question with an answer that fills multiple books, but in short, class members have access modifiers (public, private, protected). Private members can be accessed by other class members, such as a method, but not from external functions.
In the scenario Object.doSomething(), the object will have complete control over its properties which are used in the method.
But in the other call, doSomething(Object), you have to make all the properties of the object public so that they are available in the method. Which is not a safer operation.
2 more advantages of OOP are re-use and polymorphism.
ReUse:
If you use doSomething(Object) in one file or one program, it may work fine for that program. Now, imagine that you need to use your Object in another program. You will need to duplicate the doSomething() method in your new program (probably copy and paste it). This may work, but is bad practice and makes maintaining that logic a nightmare. If the doSomething() logic is a function inside Object then that logic "lives" with the object.
Polymorphism:
Imagine another case where Object is just one of many similar types. If you take advantage of Interfaces, many objects can implement the doSomething() function to suit their specific needs.
Example:
interface ICar
{
void doSomething();
void getFuel();
}
class GasCar : ICar
{
public void doSomething()
{
//do something a gas car would do
}
public void getFuel()
{
//logic to pull gas out of a tank
}
}
class ElectricCar : ICar
{
public void doSomething()
{
//do something an electric car would do
}
public void getFuel()
{
//logic to pull fuel out of a battery
}
}
One other answer to keep in mind. When you do method(object) and method is implemented like this:
method(obj)
{
return obj.getA()+obj.getB()
}
This is bad because later when you want to do the same thing again, where is your code? I mean, it uses A and B, so the first place you'd go to look is obj, but it's not there!?! Now you have to go search.
OO is as much about organizing code to find and reuse it as anything else.
tl;dr rant
You see a LOT of code like this with the bean pattern--I've come to see beans as one of the more insidious evils in OO programming because of this. In theory most beans these days are called "Pojos" because you CAN implement actual methods in them, but people still stick with beans full of nothing but setters and getters which is in no way OO, in fact they encourage code that is specifically NOT OO (beans are more akin to data structures in a non-oo language like C than anything OO has).
OOP evangelizes encapsulation; as a result, state and behavior is encapsulated in the class representing the object. Depending on what level you the encapsulation to happen, employ either static (class level) or instance (object level) based encapsulation.
method(Object) is a paradigm that works with data structures. Data Structures are about grouping fields of information that are semantically consistent and related (i.e. struct Person {FirstName, LastName, DateOfBirth}).
Object oriented programing is one step above data structures. In OOP, we not only group data fields that are related, but we also include functions (methods, member functions) that are related to the data (and that act on the data the correct way).
Encapsulation is about keeping part of the members private to objects. The goal is to "hide" the inner-working from the external world, and protect the object's state from "corruption", or from being assigned incorrect values. OOP languages provide several "access modifiers" that are used to specify whether a given member can be accessed by a specific category of objects (instances of child classes, classes in the same "package/namespace/library", any other class, etc.).
object.method() is usually about asking an object to perform something that may involve accessing a field that is not accessible outside of the class.
The above was to define, and explain how the concept of member function (method), and the concept of encapsulation go hand in hand.
Referrences:
http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29
http://en.wikipedia.org/wiki/Object-oriented_programming
Out of curiosity, I'd like to know if any class exists in Java with a method that returns a copy of its data structure. I ask because in class the teacher said a method like this breaks privacy, but I think that getting a copy of the structure is useful if you want to rearrange the structure. I'd like an example. Thanks.
I'm not entirely sure what you mean by the "data structure" of a class, but assuming you mean the members it contains, what you're looking for is reflection.
Try this tutorial.
Maybe you are missing the point: If you build a class which encapsulates some kind of internal data then you should NOT add a method which returns the internal data structure, but only the data that is encapsulated.
(Which is kind of the idea of encapsulation)
There should not be any need to "rearrange" your internal representation from the outside - because it is supposed to be internal and thus transparent in its use. (Meaning: You should not even be able to say what kind of data structure is used)
If you serialize it, any object (that is serializable) will happily prints its internal structure to a binary stream. And yes, this breaks encapsulation.
And yes, no one stops you from going to change the binary output and read it in again to create an altered object.
NB: there are more strange issues regarding serialization. For example, when deserializing objects new objects are created without their constructor ever being called. Et cetera. Serialization of objects is the maybe least object-oriented thing one can do with objects.
You're mixing up some concepts here.
Classes really are "data structures + methods", so in general you'd need a class to represent your class. Hey, a nice custom-built one would be the class your data is already in. You may be thinking of a class as a collection of simple fields, but this is not always the case.
As others have mentioned, you can extract the data via reflection, e.g.
public Map<String,Object> fields() {
Map output=new hashMap<String,Object>();
for (Field f:getClass().getFields())
{
try{
output.put(f.getName(), f.get(this));
}
catch(... //IllegalArgument, IllegalAccess.. {... }
}
return output;
}
You can get into encapsulation issues here, in general the class should provide the data that you need to see from it, I tend to use things like this only for debugging.
I'm not sure what you mean by "rearrange the structure". The class generally represents the structure of the data. If there's a transformation you want to accomplish, it probably belongs in a class method, e.g. are you thinking of something like a co-ordinates class that can provide a transformed version of itself into polar co-ordinates?
A simple way to see the internal representation of an object is to serialise it using XStream. This will generate an XML representation of the class and its components (and so on).
Does this break encapsulation ? Yes - in the sense that you're able to inspect the internal structure of the class. You can take that XML, change it, and provided that it matches the .class structure that it came from, deserialise it back into a .class instance.