JUnit testing static counter of objects - java

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!

Related

Unit testing a method that update only some properties

I want to unit test a method that set the property active of the class Person to True.
The class Person have many other properties :
public class Person{
private int id;
private Boolean active;
private Boolean adult;
... more properties
... getters and setters
}
The method to test will look something like :
public void updatePersonStatus(int personId){
Person person = getPersonById(personId);
person.setActive(true);
repository.save(person);
}
Is it sufficent to test only that the method save is called with an object person that have the property active true (Example using mockito):
#Test
public void activateTest() {
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
Person testPerson = new Person();
testPerson.setActif(true);
responsableExamenService.updatePersonStatus(1);
verify(theClass, times(1)).save(argument.capture()); //verify that the method save is called one time with a class Person as a parameter
assertTrue(argument.getValue().getActive()); //and that the Object person have a property active to true.
}
Or do I also need to test that every other property of Person have not bean altered ?
So in other words, does a unit test need to validate "what a method should do",
or does does it need to validate only what a method should do without verifying possible side effects ? Here an example of side effect would be besides of setting active to true, a developper can also set the property adult to true.
PS : The example is in Java, but the question is valid for nearly every programming language
Unfortunately, the set of things a function shall not do is infinite. Not setting other than the desired attributes is only one possibility. And, when it comes to specifications, they are mostly only explicit with respect to what the function shall do. There is always an implicit "and nothing else", and only rarely some selected behaviours are explicitly excluded.
On the other hand, when you apply unit-testing to check that the code you have written behaves as you intend it to behave, then the problem gets manageable: There is a set of 'likely' bugs, and your tests should be designed to catch those. For example, you know if your code does I/O or not, and if not, there is no value in writing unit-tests to verify it does not do I/O. On the other hand, if you have good reason believe that it is a likely bug that the code does more than intended of a specific operation, then it is worth a test to ensure it does not.
The same applies, mostly, to code written by some other person, for example if you take over the maintenance of some code. In any case, unit-testing is a white-box testing technique, and the assumption is that you have access to the code, typically even the possibility to change it (to improve testability, for example).
Simple answer - there is no strict rule.
Unit testing stands for testing one "unit" of functionality.
In your case functionality is "updating person status".
It should be defined by specification - what is expected in this case.
And, in perfect world, your tests should verify only things specified.
Also it's a good idea to unit test one action at a time.
E.g. first test could verify base functionality, while second check for a side effects.
The rule that I personally follow is to test what the method is supposed to do at first. I'll test something like "side-effect free" when and only when it either makes sense from the method implementation standpoint to apply such an effect (but it shouldn't) or (sticking to one of the TDD rules) when I am proving that the code works (addressing your example - I wouldn't verify the absence of such a side effect at first, but if some developer had set an another property to true - I'll prove the mistake by writing a unit-test that verifies this side effect, and then I'll apply the fix).

Encapsulation - why do we need it when setters are already public? [duplicate]

This question already has answers here:
Why are getter and setter method important in java? [duplicate]
(6 answers)
Closed 7 years ago.
Encapsulation is hiding the data. I would like to hear some really interesting answers here.
What is the point behind keeping variables as private when we already declare public setter methods for variables?
I understand the usage of encapsulation but when we are making the setters as public what is the point behind keeping the variables as private, we can directly use public access modifiers.
Is it because we do not want others to know the exact way we are storing data or managing data on the back-end?
Is it because we do not want others to know the exact way we are
storing data or managing data on the back-end?
Yes, that's the point. It is related to the concepts of abstraction and information hiding too.
You provide a public setter that when invoked by the class client will have the effect that you have documented. It is none of the client's business how this effect is actually achieved. Are you modifying one of the class attributes? Ok, let the client know that, but not the fact that you are actually modifying a variable. In the future, you could want to modify your class so that instead of a simple backup variable it uses something completely different (a dictionary of attributes? An external service? Whatever!) and the client will not break.
So your setter is an abstraction that you provide to the client for "modify this class attribute". At the same time you are hiding the fact that you are using an internal variable because the client doesn't need to know that fact.
(Note: here I'm using the word "attribute" as a generic concept, not related to any concrete programming language)
I fully agree with Konamiman's answer, but I'd like to add one thing:
There are cases where you really don't want that abstraction. And that's fine.
A simple example I like to use here is a class for a 3-dimensional float vector:
class Vector3f {
public:
float x;
float y;
float z;
};
Could you make those fields private and provide setters instead? Sure, you could. But here you might argue that the class is really just supposed to provide a tuple of floats and you don't want any additional functionality. Thus adding setters would only complicate the class and you'd rather leave the fields public.
Now, you can easily construct scenarios where that might bite you later on. For instance, you might one day get a requirement that Vector3fs are not allowed to store NaNs and should throw an exception if anyone tries to do so. But such a hypothetical future problem should not be enough to justify introducing additional abstractions.
It's your call as a programmer to decide which abstractions make sense for the problem at hand and which ones would only get in your way of getting the job done. Unnecessary abstractions are over-engineering and will hurt your productivity just as much as not abstracting enough.
Bottom line: Don't blindly use setters everywhere just because someone claimed that's good practice. Instead, think about the problem at hand and consider the tradeoffs.
Because by encapsulation we provide single point of access. Suppose you define a variable and its setter as follows
String username;
public void setUsername(String username){
this.username = username;
}
Later you like to add some validation before setting username property. If you are setting the username at 10 places by directly accessing the property then you don't have single point of access and you need to make this change at 10 places. But if you have one setter method then by making a change at one place you can easily achieve the result.
Think about this : I'm representing a real life object, a Lion through a class. I'd do something like this.
class Lion {
public int legs;
}
Now my class is needed by some other developer to create an object and set its legs field. He'd do something like this
Lion jungleKing = new Lion();
jungleKing.legs = 15;
Now the question is, Java won't restrict him to setting any number more than 4 as the number of legs for that object. It's not an error, and it'll run just fine. But it's a logical blunder, and the compiler won't help you there. This way a Lion may have any number of legs.
But if we write the code this way
class Lion {
private int legs;
public void setLegs(int legs){
if(legs > 4){
this.legs = 4;
}
else this.legs = legs;
}
}
Now you won't have any Lion with more than 4 legs because the policy of updating the fields of the class has been defined by the class itself and there's no way anyone not knowing the policy is going to update the legs field because the only way to update the legs field is through the setLegs() method and that method knows the policy of the class.
Although Konamiman's answer is spot on, I'd like to add that, in the particular case of public setters versus directly exposing public fields you are asking, there is another very important distinction to keep in mind apart from information hiding and decoupling implementation from the public surface, or API, of a class; validation.
In a public field scenario, there is no way to validate the field's value when it's modified. In case of a public setter (be it a Foo {get; set;} property or a SetFoo(Foo value)) method you have the possibility to add validation code and launch required side-effects and this way ensure that your class is always in a valid or predictable state.
What if you do want to a range check before assignment? That's one of the cases I use setters and getters
More or less simple and realistic example I encountered in practice is an Options class, which has a lot of setters and getters. At some point you might want to add new option which depends on others or has side effects. Or even replace group of options with Enum. In this case setA function will not just modify a field, but will hide some additional configuration logic. Similarly getA will not just return value of a, but something like config == cStuffSupportingA.
Wikipedia has a good overview of [mutator methods(https://en.wikipedia.org/wiki/Mutator_method), which is what setter methods are and how they work in different languages.
The short version: if you want to introduce validation or other logic that gets executed on object modification it is nice to have a setter to put that logic in. Also you may want to hide how you store things. So, those are reasons for having getters/setters. Similarly, for getters, you might have logic that provides default values or values that are dependent on e.g. configuration for things like Locale, character encoding, etc. There are lots of valid reasons to want to have logic other than getting or setting the instance variable.
Obviously, if you have getters and setteres, you don't want people bypassing them by manipulating the object state directly, which is why you should keep instance variables private.
Other things to consider include whether you actually want your objects to be mutable at all (if not, make fields final), whether you want to make modifying the object state threadsafe with e.g. locks, synchronized, etc.
Setting fields as private documents a powerful fact: these private fields are only directly used within the current class. This helps maintainers by not having to track down field usage. They can reason better on the code by looking at the class and determining that the effects on and from these fields with the class' environment go through public and protected method calls. It limits the exposure surface on the class.
In turn, defining a "setter" for a private field is not about giving it publicity again. It is about declaring another powerful fact: an object belonging to this class has a property that can be modified from the outside. (The terms object and property are used in the sense of a bounded part of the whole and an observable fact about this part, not in the OOP sense)
Why then declare a "setter" on a field when making the field public would suffice? Because declaring a field not only binds a name to a property of the objects of the class, but also commits to use memory storage for this property.
Therefore, if you declare a "private field with a setter", you declare three things:
You declare that the name you gave to the field/setter cluster represents a property of the object which is of interest when the object is seen as a black box.
You declare that the value of this property is modifiable by the environment of the object.
You declare that in this particular concrete class, the property of the object is realized by committing some memory storage to it.
I advocate that you never make your fields private with getters and setters indiscriminately. Fields are for describing storage. Methods are for interactions with the environment. (And the particular case of "getters" and "setters" are for describing properties of interest)

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

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.

Is declaring a method static when possible good practice?

That's pretty self-explanatory. In Java, (and all OO languages I suppose) should I declare instance method when it's the only choice or generally we don't care about it?
Methods are static when you dont need them to know about class state to process something. Helper methods are good examples of this scenario.
DateUtils.getDateNowInGMT()
The method above does not need any state to give you an answer. The one below does.
Withdrawer w = new Withdrawer.Builder().account(12545).build();
w.withdraw(100);
You cannot withdraw() money without knowing the account number, which is state associated with the Withdrawer. You could argue of course that this could be a static method and passing account information to the method would solve the problem, but it would make it inconvenient since all other methods need the same account information.
Generally speaking it will be more difficult for you to unit test your code if you use a lot of static methods (people consider it easier to mock an object using something like Mockito than mock a static method using something like Powermock).
However, if you do not care about that, and the method uses no instance data of the class it's in, you may as well make it static.
Yes.
That's the correct approach and at least I follow that.
For example, the utility methods should be made static.
But, mostly there are many future requirments and changes required, and we can't forsee all of them today. so instance should be preferred over static. until unless you are following some design pattern.
as such you can go with any kind of implementation. But rather than possibility, the criteria should be the requirement.
if you have some operations to be performed class-wide u should opt for static methods. say for example, if you have to generate some uniqueID per instance, or you have to initialize any thing that the instances would use like display or db-driver.
in other cases, instance methods are preferred where operations are instance specific.
Methods should be made static only when it makes sense for them to be static. Static methods belong to the class and not to the specific instances of it. Static methods can only use other static features of the class. A static method could not call an instance method or access instance variables for example. If this makes sense for the method you are designing, then it is a good idea to use static.
Also static elements, be it variables or methods, are loaded into memory at class loading time and stay there until the end of execution or when the class-loader unloads/reloads the class it belongs to.
I use Static methods when they are meant to do computations that do not fit in the general object oriented modeling of my application. Usually utility methods such as methods to validate input data or to hold information specific to the entire application execution, or to access points to external databases are good candidates for this.
As best of my knowledge,
If you have such a code or logic that utilize or yield something that is related to particular object state, or in simple words if your logic in side method treats different objects with some different sets of inputs and produces some different set of output, you need to take this method as instance method.
On the other side if your method has such a logic that is common for each object and the input and output doesn't depends upon object's state you should declare it as static but not instance.
Explaination with examples:
Suppose you are organizing a college party and you have to provide a common coupon to the students of all departments,you just need to appoint a person for distributing a common coupon to students(without knowing about his/her department and roll no.) as he/she(person) approaches to the coupon counter.
Now think if you want to give the coupons with different serial numbers according to the departments and roll number of students, the person appointed by you need to get the department name and roll number of student(as input from each and every student)
and according to his/her department and roll number he will create a separate coupon with unique serial number.
First case is an example where we need static method, if we take it as instance method unnecessary it will increase the burden.
Second case is an example of instance method, where you need to treat each student(in sense of object) separately.
This example may looks silly, but I hope it will help you to understand the difference clearly.

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.

Categories

Resources