Java: everything in a class is static - is this reasonable? - java

I 'm just wondering if what I'm doing is somehow poor design.
I have a ArrayList of things. I need this list to always exist. I only need to have one of these lists. I also have some methods to interact with this list. Thusly, I made everything static.
The thing is that since all of these things are tucked away into a single class, literally everything in that class is declared as static. Which seems a bit odd, because it's like I want to have the entire class be static.
The facts that Java doesn't allow me to make an entire class static and that I was taught to minimize static methods in my code are setting off a few alarm bells in my head, but I honestly can't see any rational reason why what I'm doing won't work well.
EDIT: A bit more about the program and why I decided to do what I did, because I guess that would help (and it was asked, of course).
The center of the program are two databases, one for items and another for characters.
Characters need to have temporary posession of items, but all items must be able to be listed at all times.
I decided I would have an arraylist of items, each item having a boolean marking it available or not available (making it easy to display both all items and available items). Each character would have their own, smaller arraylist of items, to which I would add duplicates of the item from the database.
To be able to access the database from other classes (this is where I started with the idea), I considered my easiest option to simply make the large arraylist static because there is no situation where I need it to not exist and there is no situation where I need more than one. Of course, as I made the list static, I needed to make all of the basic methods of interacting with it static as well.
I'm pretty sure there are better ways of doing what I'm trying to do, but I'm just a beginner practising.
EDIT2: Oh, and the list of items will be added to, removed from, and it's items modified while the program runs. Another effect of the characters receiving copies of items is that their own items will remain the same as long as they have them.

If you need exactly one list of Things in your system, you need to ask yourself what these things are. Are they items that can be configured before each run? Are they things that will change as the user executes the program? Perhaps these things should be stored as records in a database, even a lightweight in-memory one like Apache Derby or a NoSQL database.
Even if you genuinely have a fixed set of items, you should consider using a dependency injection system and vending the list in singleton scope instead of using a hardwired singleton. This way you can replace the list in your test classes by changing the configuration.
If you find that last confusing, consider this instead. Suppose you had a class that handles Things, say by keeping a static list of them inside it. Something like:
public class ThingCatalog {
private static final List<Thing> things = new ArrayList<>();
public ThingCatalog() {
// initialize list of things.
}
public List<Thing> getThings() {
return things;
}
public Thing getThingWithId(int id) {
// ...
}
}
Now, you could make ThingCatalog a singleton class; you've seen how to do it. Make the constructor private, and create a static getInstance method. You'd be tempted to write
public class TreasureGenerator {
private ThingCatalog things = ThingCatalog.getInstance();
// ...
}
What happens if you want write unit test for method in this class that don't use things? You don't need the things, so you don't really need ThingCatalog at all. Unforunately, you're stuck with it.
You can start to fix this by giving TreasureGenerator a setThingCatalog method:
public void setThingCatalog(ThingCatalog things) {
this.things = things;
}
Of course, you only have one ThingCatalog, so that doesn't help much. But if you had an interface that ThingCatalog could implement:
public interface ThingVendor {
List<Thing> getThings();
Thing getThingById(int id);
}
and all your classes used ThingVendor instead of ThingCatalog, you could replace it in your tests.
Here's a more business-like example. You are writing a financial program, and you need have it print today's date on checks. Typical is to write code like:
String recipient = ...;
String accountOwner = ...;
BigDecimal amount = ...;
String accountNumber = ...;
Date today = new Date();
printCheck(...);
Now, somebody asks you "Can your program handle leap days correctly?" Fourteen years ago, the question might have been about Y2K. How would you test this? You're stuck with today in this method.
Instead, you write an interface called DateGenerator:
public interface DateGenerator {
Date today();
}
public class TodayGenerator implements DateGenerator {
public Date today() { return new Date(); }
}
public class LeapDayGenerator implements DateGenerator {
public Date today() {
Calendar cal = Calendar.getInstance();
cal.set(2016, FEBRUARY, 29); // assume static imports;
return cal.getTime();
}
}
Your class would have a setDateGenerator method, and you'd use TodayGenerator normally. In your leap day test, you'd use the LeapDayGenerator.
A dependency injection system automates these processes. What you will learn with experience if you stay with computing is that objects should not know how to configure themselves. Other parts of the project should glue objects together.

Based on your update, you've arrived at the classic "It's a singleton!" moment, after which someone should point out to you that "It's (almost) never a singleton!". Instead, this should be a normal, non-static, non-singleton class, and the rest of the application should be written to always use a single instance of it. The fact that your application only needs a single instance of a thing doesn't make that thing a singleton. You'd benefit from reading several of the articles that turn up from Google searches for "why is singleton evil" and "singleton antipattern".
It's also sounding like you might be talking about shared mutable state, which is a whole other (giant) can of worms that you don't want to get into without some careful consideration.

Sorry to say but I fear that yours may be a bad plan, and that you may need to re-design your program. Your class has a state, and this suggests to me that it shouldn't be static.
Things that should be static:
Constants
Utility methods
Fields that belong to the class and not the instance.
Consider giving us more information about your program structure so that we can give a more precise answer.

I'm inclined to agree that your design sounds suboptimal. Many of your goals appear to be those which are typical of procedural, rather than object-oriented, programming.
If you find that your project has a strong reliance upon static mutable data, then you should ask yourself why you need so much global data.

Related

Java: What's the difference between system property and class variable in singleton class?

I have a singleton class that looks like this
public class Data {
private static Data data;
private List<String> list;
private Data() {
list = new ArrayList<>();
}
public static Data getInstance() {
if (data == null) {
data = new Data();
}
return data;
}
public void process() {
//check timestamp value
//process values from list
}
}
I want to maintain a timestamp for when the list was last processed. However I'm trying to decide whether to use a private class variable to record it or create a system variable like System.setProperty("timestamp", System.currentTimeMillis()); and access it. My requirements are that I want to access this value only within the Data class but I am running multiple instances of another class (say DataAccessor) that uses Data.process. I want to get the latest value of timestamp irrespective of which DataAccessor instance calls Data.process but I am not sure if there are any differences between storing variables through system property vs local variables in a singleton class.
It doesn't matter, and this is, as far as code style is concerned, deplorable already, so it seems a bit silly to worry about it.
That's not how you make a singleton
It won't actually be a singleton if you call getInstance() from multiple threads. Just write:
public class Data {
private static final Data data = new Data();
public static Data getInstance() {
return data;
}
}
What you're doing ('lazily' make the singleton instance) is double useless:
It's only useful in the first place if your code 'touches' the type (Data), but doesn't call getInstance(). This is rare for all singletons.
It's only useful if the cost of creating the instance is high. It clearly is not, here.
That's not how you name classes
Data is not very descriptive. It's almost clichéd in how non-descriptive it is. More generally a class represents an actor of sorts - it's supposed to be a noun. It should be LogStorage for example, if the point of this thing is to store logs, or even better AtmLogStorage if it's specifically representing the printroll of an ATM that logs cash it emitted. Be specific.
This isn't a good use of a singleton
It's feasible to imagine a system that is running 2 separated concepts that both need the same logging functionality.
Stateless singletons (example: java's Collections or Files classes - they don't have fields or otherwise any state that you can modify) are always fine. Stateful singletons, like this one, usually aren't. Use injection frameworks if you must.
Singletons are hard to test
When writing tests you tend to want to set up dummy versions or otherwise configure some object differently than you would at normal runtime, and you usually want to be able to repeatedly create things (to isolate tests) that, during normal runtime, is only created once. Singletons and 'I wrote a unit test' do not like each other.
So, what do you do?
Make the field - and fix everything else if you can. At least with the field you can later refactor your code and make it possible to have more than one Data (hopefully you renamed it), even if just for testing purposes. system properties:
Cannot be controlled (any code can read and write them - you have no control over it).
Are invisible state, in that most java apps do not use the sysproperty store to write data. Hence most tools aren't written to deal with it; debug tools can be set to breakpoint if someone changes a field, it's much harder to breakpoint them upon some code changing a sysproperty - requires having the java core sourcecode and setting a conditional breakpoint on the setProperty method which comes in various flavours, oof.
Are 'singleton' and cannot be refactored away from it, whereas a field is on its own not singleton in the slightest (the fact that there's only ever one instance of the class with this field makes it a singleton, but change that aspect and your field ceases to be one. That's good).

JUnit testing static counter of objects

I am quite a beginner at unit testing and I got some failures that I do not know how to solve. I was trying to test my simple class Employee where I have static counter of created objects, so new employees can get consecutive numbers and default names like "Name1", "Name2" etc. Here is my default initiaiton block:
{
currentNr = ++count;
setName("Name"+currentNr);
setSurname("Surname"+currentNr);
}
I wrote one JUnit class with few methods. They are working fine but methods concerning counter are working only when I run them separately (they were also working when I saved them as separate tests, but it seemed messy having so many files).
When I run the class with all the testing methods, counter is adding more object and I do not know why/when/where as test are independent. In testing methods I am creating an object and checking the counter with assertEqual. Looking for solutions I tried to work with #Before, #After, etc. but it was the same or maybe I do not know how to use it properly.
My question is what could I do to have all the test methods working or what should I write in #Before method (I tried adding and deleting objects to ArrayList and/or setting to null). I guess it is not acceptable to have test working only when run separately.
Any help will be appreciated. Thanks!
Don't use static field as counter of employees. Use instance field instead:
public class Manager {
private int employeesCount;
public Employee addEmployee() {
employeesCount++;
Employee employee = new Employee();
employee.setName("John " + employeesCount);
employee.setLastName("Smith " + employeesCount);
return employee;
}
}
There are lots of good reasons not to use static fields (read: why static variables are bad) to maintain state and one of them is that this makes your code not-testable. If you maintain your state within object (in instance fields), then there is no problem to instantiate your object and just test it as is.
Instead, make sure that there is just one instance of Manager in your program and everyone works with it (this is called singleton). Well, there is singleton pattern. And many good reasons not to use it (read: why singletons are bad). So it ends up with the fact that when you write real app, you typically use some dependency injection framework (like spring or guice) and they have ability to instantiate singleton for you when you want it.
Well, it was a bit of humor here but I'm sure you get idea that global state is considered poor practice and difficulty to test it is one of ways how it manifests itself.
The answer frenzykryger is giving a lot of valuable insight, but there is a bit more to it.
You should always look at your work with SOLID in mind. In your example, the "Single responsibility principle" can guide to a better solution. You see, good OO programming is about creating helpful abstractions. And some of the abstractions that you put into Employee simply don't belong there.
For example, one can create a class Employee to model a human being working for some company. So, employees are human beings, so probably they have names; and as they are part of an organization, yes, they might have an ID.
But: an employee gets an ID assigned! When you start at a new company, people don't come up and ask you: "please tell us your new numeric ID". Instead, somebody comes to you and tells you "this is your numeric ID, don't forget it".
So, having that in mind, some advise:
An employee does not have setters for core attributes. So, properties like "ID" or "name" that are not meant to be changed should be passed as arguments to the constructor. You simply do not create an employee object and allow later on to change the name or the id of that entity!
So, as the other answer correctly pointed out: some external class, like a "Manager" has to keep track of all "known" employees; and if a new one is added, that Manager somehow computes a new, unique ID.
Finally: is is really true: static is an abnormality in good OO design. One should have really good reasons to turn to static fields (except maybe constants) and methods. static always leads to tightly coupled code - and that something to avoid!

Member variables, get and set methods, public and private (Java) [duplicate]

What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:
public String foo;
is any worse than:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Whereas the former takes a lot less boilerplate code.
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are the some of the reasons I am aware of:
Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
Hiding the internal representation of the property while exposing a property using an alternative representation.
Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
Allowing the getter/setter to be passed around as lambda expressions rather than values.
Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.
Because 2 weeks (months, years) from now when you realize that your setter needs to do more than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)
A public field is not worse than a getter/setter pair that does nothing except returning the field and assigning to it. First, it's clear that (in most languages) there is no functional difference. Any difference must be in other factors, like maintainability or readability.
An oft-mentioned advantage of getter/setter pairs, isn't. There's this claim that you can change the implementation and your clients don't have to be recompiled. Supposedly, setters let you add functionality like validation later on and your clients don't even need to know about it. However, adding validation to a setter is a change to its preconditions, a violation of the previous contract, which was, quite simply, "you can put anything in here, and you can get that same thing later from the getter".
So, now that you broke the contract, changing every file in the codebase is something you should want to do, not avoid. If you avoid it you're making the assumption that all the code assumed the contract for those methods was different.
If that should not have been the contract, then the interface was allowing clients to put the object in invalid states. That's the exact opposite of encapsulation If that field could not really be set to anything from the start, why wasn't the validation there from the start?
This same argument applies to other supposed advantages of these pass-through getter/setter pairs: if you later decide to change the value being set, you're breaking the contract. If you override the default functionality in a derived class, in a way beyond a few harmless modifications (like logging or other non-observable behaviour), you're breaking the contract of the base class. That is a violation of the Liskov Substitutability Principle, which is seen as one of the tenets of OO.
If a class has these dumb getters and setters for every field, then it is a class that has no invariants whatsoever, no contract. Is that really object-oriented design? If all the class has is those getters and setters, it's just a dumb data holder, and dumb data holders should look like dumb data holders:
class Foo {
public:
int DaysLeft;
int ContestantNumber;
};
Adding pass-through getter/setter pairs to such a class adds no value. Other classes should provide meaningful operations, not just operations that fields already provide. That's how you can define and maintain useful invariants.
Client: "What can I do with an object of this class?"
Designer: "You can read and write several variables."
Client: "Oh... cool, I guess?"
There are reasons to use getters and setters, but if those reasons don't exist, making getter/setter pairs in the name of false encapsulation gods is not a good thing. Valid reasons to make getters or setters include the things often mentioned as the potential changes you can make later, like validation or different internal representations. Or maybe the value should be readable by clients but not writable (for example, reading the size of a dictionary), so a simple getter is a nice choice. But those reasons should be there when you make the choice, and not just as a potential thing you may want later. This is an instance of YAGNI (You Ain't Gonna Need It).
Lots of people talk about the advantages of getters and setters but I want to play devil's advocate. Right now I'm debugging a very large program where the programmers decided to make everything getters and setters. That might seem nice, but its a reverse-engineering nightmare.
Say you're looking through hundreds of lines of code and you come across this:
person.name = "Joe";
It's a beautifully simply piece of code until you realize its a setter. Now, you follow that setter and find that it also sets person.firstName, person.lastName, person.isHuman, person.hasReallyCommonFirstName, and calls person.update(), which sends a query out to the database, etc. Oh, that's where your memory leak was occurring.
Understanding a local piece of code at first glance is an important property of good readability that getters and setters tend to break. That is why I try to avoid them when I can, and minimize what they do when I use them.
In a pure object-oriented world getters and setters is a terrible anti-pattern. Read this article: Getters/Setters. Evil. Period. In a nutshell, they encourage programmers to think about objects as of data structures, and this type of thinking is pure procedural (like in COBOL or C). In an object-oriented language there are no data structures, but only objects that expose behavior (not attributes/properties!)
You may find more about them in Section 3.5 of Elegant Objects (my book about object-oriented programming).
There are many reasons. My favorite one is when you need to change the behavior or regulate what you can set on a variable. For instance, lets say you had a setSpeed(int speed) method. But you want that you can only set a maximum speed of 100. You would do something like:
public void setSpeed(int speed) {
if ( speed > 100 ) {
this.speed = 100;
} else {
this.speed = speed;
}
}
Now what if EVERYWHERE in your code you were using the public field and then you realized you need the above requirement? Have fun hunting down every usage of the public field instead of just modifying your setter.
My 2 cents :)
One advantage of accessors and mutators is that you can perform validation.
For example, if foo was public, I could easily set it to null and then someone else could try to call a method on the object. But it's not there anymore! With a setFoo method, I could ensure that foo was never set to null.
Accessors and mutators also allow for encapsulation - if you aren't supposed to see the value once its set (perhaps it's set in the constructor and then used by methods, but never supposed to be changed), it will never been seen by anyone. But if you can allow other classes to see or change it, you can provide the proper accessor and/or mutator.
Thanks, that really clarified my thinking. Now here is (almost) 10 (almost) good reasons NOT to use getters and setters:
When you realize you need to do more than just set and get the value, you can just make the field private, which will instantly tell you where you've directly accessed it.
Any validation you perform in there can only be context free, which validation rarely is in practice.
You can change the value being set - this is an absolute nightmare when the caller passes you a value that they [shock horror] want you to store AS IS.
You can hide the internal representation - fantastic, so you're making sure that all these operations are symmetrical right?
You've insulated your public interface from changes under the sheets - if you were designing an interface and weren't sure whether direct access to something was OK, then you should have kept designing.
Some libraries expect this, but not many - reflection, serialization, mock objects all work just fine with public fields.
Inheriting this class, you can override default functionality - in other words you can REALLY confuse callers by not only hiding the implementation but making it inconsistent.
The last three I'm just leaving (N/A or D/C)...
Depends on your language. You've tagged this "object-oriented" rather than "Java", so I'd like to point out that ChssPly76's answer is language-dependent. In Python, for instance, there is no reason to use getters and setters. If you need to change the behavior, you can use a property, which wraps a getter and setter around basic attribute access. Something like this:
class Simple(object):
def _get_value(self):
return self._value -1
def _set_value(self, new_value):
self._value = new_value + 1
def _del_value(self):
self.old_values.append(self._value)
del self._value
value = property(_get_value, _set_value, _del_value)
Well i just want to add that even if sometimes they are necessary for the encapsulation and security of your variables/objects, if we want to code a real Object Oriented Program, then we need to STOP OVERUSING THE ACCESSORS, cause sometimes we depend a lot on them when is not really necessary and that makes almost the same as if we put the variables public.
EDIT: I answered this question because there are a bunch of people learning programming asking this, and most of the answers are very technically competent, but they're not as easy to understand if you're a newbie. We were all newbies, so I thought I'd try my hand at a more newbie friendly answer.
The two main ones are polymorphism, and validation. Even if it's just a stupid data structure.
Let's say we have this simple class:
public class Bottle {
public int amountOfWaterMl;
public int capacityMl;
}
A very simple class that holds how much liquid is in it, and what its capacity is (in milliliters).
What happens when I do:
Bottle bot = new Bottle();
bot.amountOfWaterMl = 1500;
bot.capacityMl = 1000;
Well, you wouldn't expect that to work, right?
You want there to be some kind of sanity check. And worse, what if I never specified the maximum capacity? Oh dear, we have a problem.
But there's another problem too. What if bottles were just one type of container? What if we had several containers, all with capacities and amounts of liquid filled? If we could just make an interface, we could let the rest of our program accept that interface, and bottles, jerrycans and all sorts of stuff would just work interchangably. Wouldn't that be better? Since interfaces demand methods, this is also a good thing.
We'd end up with something like:
public interface LiquidContainer {
public int getAmountMl();
public void setAmountMl(int amountMl);
public int getCapacityMl();
}
Great! And now we just change Bottle to this:
public class Bottle implements LiquidContainer {
private int capacityMl;
private int amountFilledMl;
public Bottle(int capacityMl, int amountFilledMl) {
this.capacityMl = capacityMl;
this.amountFilledMl = amountFilledMl;
checkNotOverFlow();
}
public int getAmountMl() {
return amountFilledMl;
}
public void setAmountMl(int amountMl) {
this.amountFilled = amountMl;
checkNotOverFlow();
}
public int getCapacityMl() {
return capacityMl;
}
private void checkNotOverFlow() {
if(amountOfWaterMl > capacityMl) {
throw new BottleOverflowException();
}
}
I'll leave the definition of the BottleOverflowException as an exercise to the reader.
Now notice how much more robust this is. We can deal with any type of container in our code now by accepting LiquidContainer instead of Bottle. And how these bottles deal with this sort of stuff can all differ. You can have bottles that write their state to disk when it changes, or bottles that save on SQL databases or GNU knows what else.
And all these can have different ways to handle various whoopsies. The Bottle just checks and if it's overflowing it throws a RuntimeException. But that might be the wrong thing to do.
(There is a useful discussion to be had about error handling, but I'm keeping it very simple here on purpose. People in comments will likely point out the flaws of this simplistic approach. ;) )
And yes, it seems like we go from a very simple idea to getting much better answers quickly.
Please note also that you can't change the capacity of a bottle. It's now set in stone. You could do this with an int by declaring it final. But if this was a list, you could empty it, add new things to it, and so on. You can't limit the access to touching the innards.
There's also the third thing that not everyone has addressed: getters and setters use method calls. That means that they look like normal methods everywhere else does. Instead of having weird specific syntax for DTOs and stuff, you have the same thing everywhere.
I know it's a bit late, but I think there are some people who are interested in performance.
I've done a little performance test. I wrote a class "NumberHolder" which, well, holds an Integer. You can either read that Integer by using the getter method
anInstance.getNumber() or by directly accessing the number by using anInstance.number. My programm reads the number 1,000,000,000 times, via both ways. That process is repeated five times and the time is printed. I've got the following result:
Time 1: 953ms, Time 2: 741ms
Time 1: 655ms, Time 2: 743ms
Time 1: 656ms, Time 2: 634ms
Time 1: 637ms, Time 2: 629ms
Time 1: 633ms, Time 2: 625ms
(Time 1 is the direct way, Time 2 is the getter)
You see, the getter is (almost) always a bit faster. Then I tried with different numbers of cycles. Instead of 1 million, I used 10 million and 0.1 million.
The results:
10 million cycles:
Time 1: 6382ms, Time 2: 6351ms
Time 1: 6363ms, Time 2: 6351ms
Time 1: 6350ms, Time 2: 6363ms
Time 1: 6353ms, Time 2: 6357ms
Time 1: 6348ms, Time 2: 6354ms
With 10 million cycles, the times are almost the same.
Here are 100 thousand (0.1 million) cycles:
Time 1: 77ms, Time 2: 73ms
Time 1: 94ms, Time 2: 65ms
Time 1: 67ms, Time 2: 63ms
Time 1: 65ms, Time 2: 65ms
Time 1: 66ms, Time 2: 63ms
Also with different amounts of cycles, the getter is a little bit faster than the regular way. I hope this helped you.
Don't use getters setters unless needed for your current delivery I.e. Don't think too much about what would happen in the future, if any thing to be changed its a change request in most of the production applications, systems.
Think simple, easy, add complexity when needed.
I would not take advantage of ignorance of business owners of deep technical know how just because I think it's correct or I like the approach.
I have massive system written without getters setters only with access modifiers and some methods to validate n perform biz logic. If you absolutely needed the. Use anything.
We use getters and setters:
for reusability
to perform validation in later stages of programming
Getter and setter methods are public interfaces to access private class members.
Encapsulation mantra
The encapsulation mantra is to make fields private and methods public.
Getter Methods: We can get access to private variables.
Setter Methods: We can modify private fields.
Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method
better;
safer; and
faster.
Anywhere a value can be used, a method that returns that value can be added. Instead of:
int x = 1000 - 500
use
int x = 1000 - class_name.getValue();
In layman's terms
Suppose we need to store the details of this Person. This Person has the fields name, age and sex. Doing this involves creating methods for name, age and sex. Now if we need create another person, it becomes necessary to create the methods for name, age, sex all over again.
Instead of doing this, we can create a bean class(Person) with getter and setter methods. So tomorrow we can just create objects of this Bean class(Person class) whenever we need to add a new person (see the figure). Thus we are reusing the fields and methods of bean class, which is much better.
I spent quite a while thinking this over for the Java case, and I believe the real reasons are:
Code to the interface, not the implementation
Interfaces only specify methods, not fields
In other words, the only way you can specify a field in an interface is by providing a method for writing a new value and a method for reading the current value.
Those methods are the infamous getter and setter....
It can be useful for lazy-loading. Say the object in question is stored in a database, and you don't want to go get it unless you need it. If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.
I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages. Web services, for all of the benefits, pioneer new definitions of "slow", so you don't want to make a web service call if you don't have to.
I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service. So with a little wrapping, a lot of web service calls were prevented.
So the getter saves me from trying to figure out, on each child page, what I will need. If I need it, I call the getter, and it goes to find it for me if I don't already have it.
protected YourType _yourName = null;
public YourType YourName{
get
{
if (_yourName == null)
{
_yourName = new YourType();
return _yourName;
}
}
}
One aspect I missed in the answers so far, the access specification:
for members you have only one access specification for both setting and getting
for setters and getters you can fine tune it and define it separately
In languages which don't support "properties" (C++, Java) or require recompilation of clients when changing fields to properties (C#), using get/set methods is easier to modify. For example, adding validation logic to a setFoo method will not require changing the public interface of a class.
In languages which support "real" properties (Python, Ruby, maybe Smalltalk?) there is no point to get/set methods.
One of the basic principals of OO design: Encapsulation!
It gives you many benefits, one of which being that you can change the implementation of the getter/setter behind the scenes but any consumer of that value will continue to work as long as the data type remains the same.
You should use getters and setters when:
You're dealing with something that is conceptually an attribute, but:
Your language doesn't have properties (or some similar mechanism, like Tcl's variable traces), or
Your language's property support isn't sufficient for this use case, or
Your language's (or sometimes your framework's) idiomatic conventions encourage getters or setters for this use case.
So this is very rarely a general OO question; it's a language-specific question, with different answers for different languages (and different use cases).
From an OO theory point of view, getters and setters are useless. The interface of your class is what it does, not what its state is. (If not, you've written the wrong class.) In very simple cases, where what a class does is just, e.g., represent a point in rectangular coordinates,* the attributes are part of the interface; getters and setters just cloud that. But in anything but very simple cases, neither the attributes nor getters and setters are part of the interface.
Put another way: If you believe that consumers of your class shouldn't even know that you have a spam attribute, much less be able to change it willy-nilly, then giving them a set_spam method is the last thing you want to do.
* Even for that simple class, you may not necessarily want to allow setting the x and y values. If this is really a class, shouldn't it have methods like translate, rotate, etc.? If it's only a class because your language doesn't have records/structs/named tuples, then this isn't really a question of OO…
But nobody is ever doing general OO design. They're doing design, and implementation, in a specific language. And in some languages, getters and setters are far from useless.
If your language doesn't have properties, then the only way to represent something that's conceptually an attribute, but is actually computed, or validated, etc., is through getters and setters.
Even if your language does have properties, there may be cases where they're insufficient or inappropriate. For example, if you want to allow subclasses to control the semantics of an attribute, in languages without dynamic access, a subclass can't substitute a computed property for an attribute.
As for the "what if I want to change my implementation later?" question (which is repeated multiple times in different wording in both the OP's question and the accepted answer): If it really is a pure implementation change, and you started with an attribute, you can change it to a property without affecting the interface. Unless, of course, your language doesn't support that. So this is really just the same case again.
Also, it's important to follow the idioms of the language (or framework) you're using. If you write beautiful Ruby-style code in C#, any experienced C# developer other than you is going to have trouble reading it, and that's bad. Some languages have stronger cultures around their conventions than others.—and it may not be a coincidence that Java and Python, which are on opposite ends of the spectrum for how idiomatic getters are, happen to have two of the strongest cultures.
Beyond human readers, there will be libraries and tools that expect you to follow the conventions, and make your life harder if you don't. Hooking Interface Builder widgets to anything but ObjC properties, or using certain Java mocking libraries without getters, is just making your life more difficult. If the tools are important to you, don't fight them.
From a object orientation design standpoint both alternatives can be damaging to the maintenance of the code by weakening the encapsulation of the classes. For a discussion you can look into this excellent article: http://typicalprogrammer.com/?p=23
Code evolves. private is great for when you need data member protection. Eventually all classes should be sort of "miniprograms" that have a well-defined interface that you can't just screw with the internals of.
That said, software development isn't about setting down that final version of the class as if you're pressing some cast iron statue on the first try. While you're working with it, code is more like clay. It evolves as you develop it and learn more about the problem domain you are solving. During development classes may interact with each other than they should (dependency you plan to factor out), merge together, or split apart. So I think the debate boils down to people not wanting to religiously write
int getVar() const { return var ; }
So you have:
doSomething( obj->getVar() ) ;
Instead of
doSomething( obj->var ) ;
Not only is getVar() visually noisy, it gives this illusion that gettingVar() is somehow a more complex process than it really is. How you (as the class writer) regard the sanctity of var is particularly confusing to a user of your class if it has a passthru setter -- then it looks like you're putting up these gates to "protect" something you insist is valuable, (the sanctity of var) but yet even you concede var's protection isn't worth much by the ability for anyone to just come in and set var to whatever value they want, without you even peeking at what they are doing.
So I program as follows (assuming an "agile" type approach -- ie when I write code not knowing exactly what it will be doing/don't have time or experience to plan an elaborate waterfall style interface set):
1) Start with all public members for basic objects with data and behavior. This is why in all my C++ "example" code you'll notice me using struct instead of class everywhere.
2) When an object's internal behavior for a data member becomes complex enough, (for example, it likes to keep an internal std::list in some kind of order), accessor type functions are written. Because I'm programming by myself, I don't always set the member private right away, but somewhere down the evolution of the class the member will be "promoted" to either protected or private.
3) Classes that are fully fleshed out and have strict rules about their internals (ie they know exactly what they are doing, and you are not to "fuck" (technical term) with its internals) are given the class designation, default private members, and only a select few members are allowed to be public.
I find this approach allows me to avoid sitting there and religiously writing getter/setters when a lot of data members get migrated out, shifted around, etc. during the early stages of a class's evolution.
There is a good reason to consider using accessors is there is no property inheritance. See next example:
public class TestPropertyOverride {
public static class A {
public int i = 0;
public void add() {
i++;
}
public int getI() {
return i;
}
}
public static class B extends A {
public int i = 2;
#Override
public void add() {
i = i + 2;
}
#Override
public int getI() {
return i;
}
}
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
a.add();
System.out.println(a.i);
System.out.println(a.getI());
}
}
Output:
0
0
4
Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are:
Abstraction
Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
Here the implementation details of Full Name is hidden from the user and is not accessible directly to the user, unlike a public attribute.
There is a difference between DataStructure and Object.
Datastructure should expose its innards and not behavior.
An Object should not expose its innards but it should expose its behavior, which is also known as the Law of Demeter
Mostly DTOs are considered more of a datastructure and not Object. They should only expose their data and not behavior. Having Setter/Getter in DataStructure will expose behavior instead of data inside it. This further increases the chance of violation of Law of Demeter.
Uncle Bob in his book Clean code explained the Law of Demeter.
There is a well-known heuristic called the Law of Demeter that says a
module should not know about the innards of the objects it
manipulates. As we saw in the last section, objects hide their data
and expose operations. This means that an object should not expose its
internal structure through accessors because to do so is to expose,
rather than to hide, its internal structure.
More precisely, the Law of Demeter says that a method f of a class C
should only call the methods of these:
C
An object created by f
An object passed as an argument to f
An object held in an instance variable of C
The method should not invoke methods on objects that are returned by any of the allowed functions.
In other words, talk to friends, not to strangers.
So according this, example of LoD violation is:
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
Here, the function should call the method of its immediate friend which is ctxt here, It should not call the method of its immediate friend's friend. but this rule doesn't apply to data structure. so here if ctxt, option, scratchDir are datastructure then why to wrap their internal data with some behavior and doing a violation of LoD.
Instead, we can do something like this.
final String outputDir = ctxt.options.scratchDir.absolutePath;
This fulfills our needs and doesn't even violate LoD.
Inspired by Clean Code by Robert C. Martin(Uncle Bob)
If you don't require any validations and not even need to maintain state i.e. one property depends on another so we need to maintain the state when one is change. You can keep it simple by making field public and not using getter and setters.
I think OOPs complicates things as the program grows it becomes nightmare for developer to scale.
A simple example; we generate c++ headers from xml. The header contains simple field which does not require any validations. But still as in OOPS accessor are fashion we generates them as following.
const Filed& getfield() const
Field& getField()
void setfield(const Field& field){...}
which is very verbose and is not required. a simple
struct
{
Field field;
};
is enough and readable.
Functional programming don't have the concept of data hiding they even don't require it as they do not mutate the data.
Additionally, this is to "future-proof" your class. In particular, changing from a field to a property is an ABI break, so if you do later decide that you need more logic than just "set/get the field", then you need to break ABI, which of course creates problems for anything else already compiled against your class.
One other use (in languages that support properties) is that setters and getters can imply that an operation is non-trivial. Typically, you want to avoid doing anything that's computationally expensive in a property.
One relatively modern advantage of getters/setters is that is makes it easier to browse code in tagged (indexed) code editors. E.g. If you want to see who sets a member, you can open the call hierarchy of the setter.
On the other hand, if the member is public, the tools don't make it possible to filter read/write access to the member. So you have to trudge though all uses of the member.
Getters and setters coming from data hiding. Data Hiding means We
are hiding data from outsiders or outside person/thing cannot access
our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public and private are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
Advantage:
When anyone want to access or change/set value to balance variable, he/she must have permision.
//assume we have person1 object
//to give permission to check balance
person1.getName()
//to give permission to set balance
person1.setName()
You can set value in constructor also but when later on when you want
to update/change value, you have to implement setter method.

Java Class That Has 90% Static Members. Good Practice Or What?

I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.
The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?
I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.
As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.
In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.
ADDED
I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.
There is no perfect fix, YMMV, but I'd consider a single static method, something like
World World.getWorld(String name)
and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".
Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)
It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.
Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.
Well, what you are doing is definitely an option. Or you could use a singleton pattern:
public class World {
private static World instance = new World();
private World() {
}
public static World getInstance() {
return instance;
}
}
Now just use World.getInstance() everywhere to have a unique object of this type per application.
I would say it's definitely not a good practice.
I've not seen your code, but having several static variables in a class that other classes access freely seems to indicate that you're not really using object orientation/classes but more just writing procedural code in Java. Classes should generally encapsulate/hide all their variables - static or not - from access from other classes so that other classes don't depend on how the class is implemented.
The static part also causes problems with making threads work (global variables are hard to lock in a good way so that nothing deadlocks) and with unit testing (mocking is all but impossible)
I also agree with the other posters, if you need "global variables", at least make them singletons. That allows you to change strategy easier later and does not lock you to one world.
Edit: I'm definitely not advocating singletons as a good pattern here if someone read it like that, but it does solve some problems with static variables, esp. regarding testing/mocking compared to just statics so I'd say it's a ever so slightly lighter shade of gray :) It is also a pattern that is easier to gradually replace with better patterns by for example using a IoC container.
I think it is fine as long as you don't need anything more sophisticated, in other words, static fields are OK as long as different objects (including subclasses if there will be any) do not need different values.
You code by yourself, refactoring is easy with modern tools, me says don't fix it until it is broken, and focus on the algorithmic aspects of your project.
Perhaps you may think to encapsulate all those static fields within a different static class, as it is a good principle to "keep what changes seperate from what does not". Chances are one day you will want to initiate that static class with different values, for example want to read the initial values from an XML file and/or registry, add behaviour, etc. so instead of a static class you will implement it with a Singleton pattern.
But clearly that is not the concern of today. Till then, enjoy!
You may wish to look into implementing this class as a singleton, while there is nothing particularly wrong with your approach it may lead to some inflexibility further down the road.
Also you should take in to consideration the purpose of static members which is to be a member of the class and 'act' on/with the class not an instance of it. For example the static method in a singleton returns either a new instance of the class if one doesn't already exist or returns the instance, and because the method is static you do not instantiate a new one. This is probably worth a read because it can be somewhat confusing when determining the appropriate use of static members
I'm not sure what you are really talking about from your short description, so I'll try this:
public class Level {
static List<Mushroom> mushrooms;
static List<Coin> coins;
...
}
Is that you were describing?
You asked if this is "good practice" and I can tell you that this looks very odd, so, no, it's not.
You gain absolutely nothing by doing this. You make it impossible to have more than one Level, which brings no advantage, but it could cause trouble in the future.
I didn't understand your last paragraph where you say you made most things static to save memory. You would usually create one Level and it would be passed around (without cloning) to the various classes/methods that read from it or modify it.

Reducing complexity of a method

I have a method that does several tasks. It is part of the business logic of the application, but it is poorly readable because of the many if-then and try-catch blocks and the many log calls.
public class MyClass {
boolean createReport, sendReport, warnIfErrors;
public void archiveAll() {
if (createReport) {
//... ...
}
if (sendReport) {
//... ...
}
if (warnIfErrors) {
//... ...
}
}
The idea is to move the tasks into ad hoc methods and have an "archiveAll" method that may be understood at a glance:
public void archiveAll() {
doCreateReport();
doSendReport();
doWarnIfErrors();
}
But as doing this, two problems arise:
if all methods use a local variable, I'll move it as a class field, but this is not good design
I want to move the test if (createReport) into the method doCreateReport too, because part of the complexity derives from the tests that are done. This makes the sub methods poorly cohesive though.
If you have a lot of local variables that are shared between them it might make sense to make a private class to store them together, perhaps even do something like:
MyReport report = new MyReport(); // or MyReport.doCreateReport(); if it makes more sense
report.send();
report.warnIfErrors();
Again, it really depends on whether the function is currently big enough to warrant something like this.
If you can get away with just passing those common variables as parameters without having huge lists of parameters, do that.
You can also pass the required data as arguments to the methods.
I would do the check before calling a method. If a method is called doCreateReport it should actually do that.
Instead of making variables class fields, just parameterize the function and pass the values around. This has another big advantage that your code will now become more unit-testable. I always promote to have each method to be as independent as possible as it helps in UT.
If you had the name changed to checkAndCreateReport then, will you still think that way:)

Categories

Resources