Is it necessary for setter methods to have one argument? - java

Is it necessary for setter methods to have one argument? Usually setter methods accept one argument as the value of a certain property of an Object. What if I want to test first the validity which depends on another argument which is a boolean, if true, validate first, else just set the value.
I am getting the values from clients through ftp server. Sometimes those files contain garbage values. For instance, a phone number like #3432838#9. So before I set the value I need to remove those garbage characters. Can I do it in the setter methods? Is it a valid approach?
Thanks a bunch in advance!
EDIT:
Is this valid:
public void setSomething(String strValue){
if(checkValidity(strValue)){
// set the value
} else {
// set the value to an empty string
}
}

It is necessary specifically in the java bean framework model, but it s not mandatory in general.
You can have setter with no argument when they are meant to "swith" a value.
void setCheck()
could for instance be meant to set the "check" boolean attribute to true.
So even if it is not a "setter" in the java bean sense of the term, you can imagine setter used for other purposes.
Plus, according to section 7 of JavaBean specifications, a setter can have more than one argument, for instance for Indexed properties (An indexed property supports a range of values. Whenever the property is read or written you just specify an index to identify which value you want.)
void setter(int index, PropertyType value); // indexed setter
void setter(PropertyType values[]); // array setter
In your case, a valid approach would be to add a runtime exception to the signature of our function.
That way you do not put any unnecessary compilation-time exception checking for all of the other classes which are already calling your setter.
Or you could consider your property as a Constrained property and add a non-runtime exception.
Constrained property setter methods are required to support the PropertyVetoException.
This documents to the users of the constrained property that attempted updates may be
vetoed.
So a simple constrained property might look like:
PropertyType getFoo();
void setFoo(PropertyType value) throws PropertyVetoException;
which allows for VetoableChangeListener to be added if needed.
Regarding your snippet, it is "valid" but may not be optimal because (as said in this question):
Validation should be captured separately from getters or setters in a validation method. That way if the validation needs to be reused across multiple components, it is available.
It is better to fail fast (hence my proposition to add exception to the setter).

By Java Bean specification setter have one argument. If you add another one, for whatever reason, it is not considered setter anymore.
Setter is perfectly valid to "clean up" its argument, or throw exception if is invalid.

Why not. Verifying and validating the input is a good variant to include into the setter. The question here is, if you want to allow setting the member without validation.
Possibly you need the standard-form of the setter for some framework you use (usage as bean). But if you are not restricted in this way, you could try this.
You could also use asserts in the setter, if you think other code should do the validation but wrong values should never set.

In the book "Effective Java 2nd Edition" by Joshua Bloch (ISBN-13: 978-0-321-35668-0) saids that it's best to use the builder pattern than the bean convention for objects creations.
For instance (bean pattern):
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohydrate(27);
Usage with builder pattern:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).
sodium(35).
carbohydrate(27).
build();
The implementation of builder pattern:
// Builder Pattern
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
// Required parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
When the first two arguments ar required.
For validation you can use early validation (in each <field> method) or lazy validation (in the build() method). And the format is kind of python key-value initialization.

Related

How to use the getter method which is stored in mongodb for some other POJO class?

I am having one class which is having getter and setter methods i am storing that getter method in mongodb with some other collection. After getting the method name from DB how to access that method. Whether it is possible to do like this or not?
public class MappingAlgorithmScoreGenerationRules {
#Field(value = FieldNames.CATEGORY)
private String category;
#Field(value = FieldNames.ATTRIBUTE_NAME)
private MappingScoreGenerationLogic attributeName;
#Field(value = FieldNames.PRIORITY)
private Integer priority;
#Field(value = FieldNames.ATTRIBUTE_SCORE)
private Integer attributeScore;
#Field(value = FieldNames.FINAL_THRESHOLD)
private Integer finalThreshold;
#Field(value = FieldNames.RESULT_COUNT)
private Integer resultCount;
#Field(value = FieldNames.NORMALIZED_VALUE)
private Integer normalizedValue;
#Field(value = FieldNames.GETTER_METHOD)
private String getterMethod;
}
This is the class where i am storing the method name.
public class MatchEntry {
private double matchedWeight;
public double getMatchedWeight() {
return matchedWeight;
}
public void setMatchedWeight(double matchedWeight) {
this.matchedWeight = matchedWeight;
}
}
getMatchedWeight is the method name i am going to store in the DB MappingAlgorithmScoreGenerationRules.
After getting the method name how to access the method name?
I want to access like
For example: MatchEntry.(the value get from db)
Use reflection API - https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
Method methodToInvoke
= MatchEntry.class.getMethod("methodName", methodParams,..);
methodToInvoke.invoke(matchEntryInstance, params,..);
In Java you can achieve method access by name using reflection (https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html).
This is a tutorial you may be able to use to lean more about this language feature: https://www.geeksforgeeks.org/reflection-in-java/
In your example, let's say you have loaded an instance of MappingAlgorithmScoreGenerationRules from the database, whose getterMethod attribute returns "getMatchedWeight".
Let's also assume that you have an instance of MatchEntry.
You would then access as follows:
MappingAlgorithmScoreGenerationRules rules = ....; //load from DB
MatchEntry entry = ...; //wherever it comes from
String getterMethodName = rules.getGetterMethod();
Method getter = MatchEntry.class.getMethod(getterMethodName);
Object value = getter.invoke(entry);
This code snippet omits Exceptions, in particular NoSuchMethodException and InvocationTargetException.
Please note that if you choose this approach, and depending heavily on the rest of your domain model, you will also need to be very careful with assumptions about the return type of the actual value (unless you can somehow guarantee that they are all the same, in which case you could cast the value).
Code that uses reflection is also inherently brittle and prone to failure as soon as you refactor. Imagine you have a populated database with these rules, and during a code review a couple of methods are renamed. Inoccuous change? Or will your entire setup break on the next deploy?
A (type-)safer approach might be to ensure all entries and related objects derive from an interface that standardises the return type on a getValue(String attributeName) method, so instead of messing with reflection you might do:
MappingAlgorithmScoreGenerationRules rules = ....; //load from DB
MatchEntry entry = ...; //wherever it comes from
String attributeName = rules.getAttribute(); //instead of 'getterMethod'
Object value = entry.getValue(attributeName);
where MatchEntry.getValue might be defined as:
public Object getValue(String attribute) {
switch(attribute) {
case "matchedWeight": return getMatchedWeight();
default: return null; //or you could throw an exception
}
}
This would easily survive any kind of method name refactoring and reorganisation, but adds the overhead of adding a case to the switch for every new attribute.
This problem could be partially solved with a runtime annotation that essentially binds an attribute name to a getter method, e.g.:
public class MatchEntry implements Matchable {
private double matchedWeight;
#MyCustomAnnotation("matchedWeight")
public double getMatchedWeight() {
return matchedWeight;
}
public void setMatchedWeight(double matchedWeight) {
this.matchedWeight = matchedWeight;
}
}
public interface Matchable {
default Object getValue(String attributeName) {
//read methods annotated with 'MyCustomAnnotation's in current class and call the one with matching value
}
}
Your getValue(String attributeName) would be tasked with reading these annotations and dynamically figuring out which getter to call. Still requires the annotation to be added everywhere it's needed, but at least it's with the getter and not hidden in some switch that's potentially duplicated across multiple class definitions.
Instead you just need a single default definition in the parent interface, as hinted above.

Best practice for storing type of object in a class

I have a transaction of two types:
- income
- expense
class Transaction {
final public static int IN = 0x1, OUT = 0x2;
final private int type;
Transaction(int type)
{
this.type = type;
}
public int getType() {
return type;
}
// --- internal logic is same for both types ---
}
// create:
Transaction t = new Transaction(Transaction.IN);
What is the best practice for this case? I should declare an enum? Two clases? I should use Factory pattern?
I'd recommend using an Enumeration in such cases, because this way, you can restrict the possible values in a statically checked way:
enum TransactionType {
Income, Expense;
}
class Transaction {
final private TransactionType type;
Transaction(TransactionType type) {
this.type = type;
}
public TransactionType getType() {
return type;
}
}
Otherwise, any int value could be provided to your constructor Transaction(int type).
Another benefit of enums is, that you later can provide them with some additional information if you like to (e.g. different formatting patterns or the like).
This is really depending on what you find easiest. The advantage of enums is you can set it to any enum and transfer the instance and get the value out of itEnum example:
private enum ENUM{
EX1, EX2
};
and call it like so:
private ENUM instance = ENUM.EX1;
And if you want to retrieve the value:
switch(instance){
case ENUM.EX1:
break;
case ENUM.EX2:
break;
}
Here is the enum example:
enum Transaction {
IN(0x1), OUT(0x2);
private int marker;
Transaction(int marker) {
this.marker = marker;
}
}
Enum is easier, yes.
Comparativly:
The code is different, and calling is different. But not much.
The main difference is how you compare the value. You have to actually get the value of the instance(instance.getType()) in a switch loop.
Both are equally good, though in most cases I preffer enum as it saves me of creating another class as all I need is an enum. Though other times, enums just does not cut it. In your situation it does not appear like you can use enum(unless you change the codes to be "enum acceptable").
What is the best practice for this case? I should declare an enum?
In this case? Maybe. It is really up to you. Enum is however the easiest way to store things in.
Best practices really depends on the use case. Given what you added in the comments an enum seems like the better option. An enum can encapsulate additional information for the "marker". For example, you said you print with a color based on the transaction type. To avoid doing additional conditional logic you could add that information to the enum value itself. For example:
enum TransactionType {
IN(Color.GREEN), OUT(Color.RED);
public final Color TEXT_COLOR;
TransactionType(Color textColor) {
TEXT_COLOR = textColor;
}
}
It also provides safer usage through compile-time checking. You can make your code more dummy-proof by letting the compiler check for correct TransactionTypes. It's not completely dummy-proof though since you can still do TransactionType.valueOf("DUMMY") but it's better than needing to check against all possible goofs anywhere you might need to use the marker.
For example, you said there's a need to find the transactions of a given type. You might do that like this:
List<Transaction> ins = transactions.stream()
.filter(t -> t.getType() == TransactionType.IN).collect(Collectors.toList());
It would be possible to throw a 42 in there if your class relied on an int value.
List<Transaction> ins = transactions.stream()
.filter(t -> t.getType() == 42).collect(Collectors.toList());
Worst part is it would just return an empty list; no compile or runtime errors leaving you with the need to validate the value somewhere.
An additional note would be that, if it's truly just a marker, you might be able to replace the Transaction class completely with an enum but more information would be needed to determine that.
It really depends on the context, but if you have:
public class Transaction {
private double amount = 0.0d;
public static Transaction newExpenseTx() {
return new ExpenseTransaction();
}
public static Transaction newIncomeTx() {
return new IncomeTransaction();
}
public void setAmount(double a) { amount = a; }
public double getAmount() { return amount; }
public abstract Color getColor();
static class ExpenseTransaction extends Transaction {
Color getColor() { return Color.RED; }
}
static class IncomeTransaction extends Transaction {
Color getColor() { return Color.GREEN; }
}
}
You can see that your caller does not need to know about the subclasses and you do not need to have any switch.
Transaction t1 = Transaction.newExpenseTx();
assertEquals("Exprense Transactions need to be red, has amount " +
t1.getAmount(),
Color.RED, t1.getColor());
Of course if you need the type as a value, adding a TransactionType enum does not hurt.

Object-Oriented programming private class field + get / set or public class field?

I'm a junior developer (currently exercise Java) and I have one question about the correctness of my code, here is an example:
I am writing a simple MMO-game representation on Java, I have 2 classes (Character and spell).
Character has properties (mName, mHealth and mEnergy), Spell class has properties (mSpellName, mSpellCost, mSpellDamage). And Spell class also have a method called execute, here is a code
public void spellExecute(Character caster, Character target) {
caster.mEnergy -= this.spellCost;
target.mHealth -= this.spellDamage
}
This construction implies that Character fields are public and can be accessed directly, but in some examples I seen that all fields must be private and can be accessed only via get/set methods. My question is: Which way is more correct, in general? It's important to me because I wanna write a good code :)
Generally, you would use get/set methods, because they allow the class to control access, via those methods
Any other class which uses your class, should only be able to access and change your fields in the way you describe.
For example let's look at a simple (oversimplified) fuel pump
class Pump
{
constant int PRICE_PER_LITRE = 100; //in pence
private int litresDispensed;
private bool nozzleUp;
private int litresAvailable;
private int price; //in pence
construct()
{
litresDispensed = 0;
nozzleUp = false;
}
startFuelling()
{
nozzleUp = true;
}
stopFuelling()
{
nozzleUp = false;
}
takeFuel(int litresTaken)
{
if(nozzleUp = true)
{
litresAvailable -= litresTaken;
price += litresTaken * PRICE_PER_LITRE;
}
else
{
error("You must lift the nozzle before taking fuel!");
}
}
getPrice()
{
if(nozzleUp = true)
{
error("You can't pay until you've finished fuelling! Please return the nozzle");
}
else
{
return price;
}
}
}
Our final get method is important to ensure that the rest of the transaction is complete before the person tries to pay.
If we allowed direct access to the price, they could do it before they've finished taking fuel! And that would let them steal all our fuel.
As this shows, a get method protects the field from outside influence. It can still be manipulated, but only in the ways we want to allow it to be manipulated. Note also that there's no set method at all for this field: we don't want the user to be able to set their own price, only the one we dictate!
If you write get/set methods which only return and set the field, without any validation or checks, then you could simply make the field public (or, alternately, you need to decide whether that field should be accessed directly at all): that said, it's good practice to use get/set methods where possible, because it allows you to add validation in the future without breaking code.
You're right that it's important to write good code and at first getting the grasp of Object Oriented Programming can be a bit difficult.
In this case, I would recommend moving the spellExecute to a similar method, except on the Character class :
public void didUseSpell(Spell spell) {
this.mEnergy -= spell.spellCost;
}
public void wasHitBySpell(Spell spell) {
this.mHealth -= spell.spellDamage;
}
In your spell execute method, you would then call :
public void spellExecute(Character caster, Character target) {
caster.didUseSpell(this);
target.wasHitBySpell(this);
}
In general, there are many different was of solving this problem, and they all vary in terms of code cleanliness and verbosity. Another solution would be to create getter and setter methods for the fields that are affected by the spells.
Getters/setters are better, because it encapsulates or hides what the actual class is doing to set that data. Set the constructor private and let it initialize default values, then the user can call the set methods to set the variables.
Getters and setters with private fields is generally followed design choice. The reason is, you can guard your variables against unintentional changes from the clients using your API.
Consider this below example
public class Dummy{
public int age;
}
Now client can do this
new Dummy().age = -1
With setters and getters
public class Dummy{
private int age;
public void setAge(int age){
if (age < 0){
throw new RuntimeException("you are not allowed to do this");
}
......
}
Many frameworks for example Hibernate, IBATIS etc.. follow these naming conventions. Hope this answers your questions.
Getter and setter (Java bean) is more better.It also provide Encapsulation feature.Which is useful for hiding data.
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Constructor is used for initialization the value when You are creating object.But If you want to set value of data after object creation then you must call setter behavior instead of call constructor.
Getters and setters are preferred - after all, why use an Object Orientated language if you're not going to use its main feature?
With setters in this situation you can easily enforce sanity rules without each caller having to duplicate the logic, e.g. - in Character try:
public void reduceMentalHealth(int val) {
if(this.mHealth > val) {
this.mHealth -= val;
} else {
this.mHealth = 0;
}
Without setters you would need this logic everywhere you changed the field. You could also include things like checking whether the Character is wearing a ring of mental invincibility in this method too :-)
Warning
You are mixing two related questions.
Questions:
[1] Should I use direct access fields, or fields access by accesors methods ( "getter" (s) and "setter" (s) ).
[2] In both cases, which access modifiers, should apply ?
Short Quick Answer
[1] Should I use direct access fields, or fields access by accesors methods ( "getter" (s) and "setter" (s) ).
Go, for the "fields access by accessor methods" a.k.a. "getter (s) and setter (s)". The other method is NOT wrong, it depends, what do you want to do.
[2] In both cases, which access modifiers, should apply ?
If you go for "plain fields", use "public", unless there is an specific reason to use "private" or "protected". If you go for "accesors methods", use "protected" for the fields, and "protected" or "public" for the accesors.
Long Boring Extended Answer
[1] Should I use direct access fields, or fields access by accesors methods ( "getter" (s) and "setter" (s) ).
Go, for the "fields access by accessor methods" a.k.a. "getter (s) and setter (s)".
The other method is NOT wrong, it depends, what do you want to do.
But, since property access can be overriden by those methods, that allows more features to be added, removed or changed by methods.
I suggest, leave "plain fields" for Data Objects.
[2] In both cases, which access modifiers, should apply ?
If you go for "plain fields", use "public", unless there is an specific reason to use "private" or "protected".
If you go for "accesors methods", use "protected" for the fields, and "protected" or "public" for the accesors.
Is not a good idea to apply "public" access for accesors' fields, because this way, you confuse yourself and other programmer users of your classes,
on which one to directly use.
Code Example:
public class ControlClass {
// example of non private field (s)
protected String controlname;
// ...
// example of non private field (s)
protected int width;
protected int height;
// ...
// example of read-only property
public final String getControlName()
{
return this.controlname;
} // String getControlName(...)
// ...
#Override
public int getWidth()
{
return this.width;
} // int getWidth(...)
#Override
public void setWidth(int newvalue)
{
this.width = newvalue;
} // void setWidth(...)
#Override
public int getHeight()
{
return this.height;
} // int getHeight(...)
#Override
public void setHeight(int newvalue)
{
this.height = newvalue;
} // void setHeight(...)
// ...
// constructor assigns initial values to properties' fields
public ControlClass(){
this.controlname = "control";
this.height = 0;
this.width = 0;
} // ControlClass(...)
// ...
} // class ControlClass
public class ButtonClass extends ControlClass {
// ...
// example of overriden public property with non public field
#Override
public int getWidth()
{
if (this.width < 5)
return 5
else
return this.width;
} // int getWidth(...)
// example of overriden public property with non public field
#Override
public void setWidth(int newvalue)
{
if (newvalue < 5)
throw new ArithmeticException("integer underflow");
this.width = newvalue;
} // void setWidth(...)
// example of overriden public property with non public field
#Override
public int getHeight()
{
if (this.height < 5)
return 5
else
return this.height;
} // int getHeight(...)
// example of overriden public property with non public field
#Override
public void setHeight(int newvalue)
{
if (newvalue < 5)
throw new ArithmeticException("integer underflow");
this.height = newvalue;
} // void setHeight(...)
// ...
// constructor assigns initial values to properties' fields
public ControlClass(){
this.controlname = "ButtonClass";
this.height = 5;
this.width = 5;
} // ButtonClass(...)
// ...
} // class ControlClass
I started to use "private" for fields, like many programmers, buy, eventually, had to change to "protected", because sometimes required to use it. directly.
Additional Comment.
I have work with other object oriented programming languages, with its own way and syntax for "properties", and that's give you another perspective.
Such as Object Pascal ( a.k.a. "Delphi" ), ECMAScript ( "Javascript" ), C++, C#. Note that Delphi and C#, supports "full properties", not just accesors methods or fields, and that's give developer another way of designing an Object and Class Oriented Software Application.
What does this has to do with Java ?
We'll when I design a Class in Java or C++, I design properties, the same way, as C# or Delphi, does, a concept that is independent of fields, or methods, even if there can be implemented by them.
Cheers.

Java how do I use a set Method? [duplicate]

How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.
For example, for a member variable:
Integer x;
You might have methods:
Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.
I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
I think you want something like this:
public class Person {
private int age;
//public method to get the age variable
public int getAge(){
return this.age
}
//public method to set the age variable
public void setAge(int age){
this.age = age;
}
}
You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:
public void setAge(int age){
this.age = age;
double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;
if(averageCigarettesPerYear >= 7300.0) {
this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
}
}
Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.
Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:
private String x;
public void setX(String newX) {
if (newX == null) {
x = "";
} else {
x = newX;
}
}
public String getX() {
if (x == null) {
return "";
} else {
return x;
}
}
Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).
Some benefits of using getters and setters (known as encapsulation or data-hiding):
(originally answered here)
1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.
Example:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.
Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.
Example (getting a value):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3. Makes the code cleaner, more readable and easier to comprehend.
Here is an example:
No encapsulation:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
With encapsulation:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).
Here is good SO thread on this topic.
Here is good read on data encapsulation.
The above answers summarize the role of getters and setters better than I could, however I did want to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those without complex constructions, validation, and so forth, as they break encapsulation. This doesn't mean you can't ever use them (stivlo's answer shows an example of a good use of getters and setters), just try to minimize how often you use them.
The problem is that getters and setters can act as a workaround for direct access of private data. Private data is called private because it's not meant to be shared with other objects; it's meant as a representation of the object's state. Allowing other objects to access an object's private fields defeats the entire purpose of setting it private in the first place. Moreover, you introduce coupling for every getter or setter you write. Consider this, for example:
private String foo;
public void setFoo(String bar) {
this.foo = bar;
}
What happens if, somewhere down the road, you decide you don't need foo anymore, or you want to make it an integer? Every object that uses the setFoo method now needs to be changed along with foo.
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
The benefits of get() set() methods are as follows ..
You can serialize you object easily.
You can create a persistent object from the containing class.
You can convert the properties to JSON easily.
In the DAO layer (Frameworks like Hibernate) you can directly save the object to DB.
Easy understanding of object oriented concept.
Needs in all design pattern except possibly in single tone pattern.
Security for properties protecting direct access.
Polymorphism, Encapsulation can be easily understood and implemented by this type of class.
Example:
private String personName;
private int personId;
public void setPersonName(String name) throws Exception{
if(!(name.equals("")||name=="")){
this.personName = name;
}
}
public String getPersonName(){
return this.personName;
}
public void setPersonId(int id) throws Exception{
this.personId = id;
}
public int getPersonId(){
return this.personId;
}
Above answers all assume that the object in question is an object with behaviour.
An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.
With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again.
Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.
public class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
i think this is you want..
and this also called pojo
this is the code for set method
public void setAge(int age){
this.age = age;
}
It looks like you trying to do something similar to C# if you want setAge create method setAge(int age){
this.age = age;}
I don't see a simple answer to the second question (why) here. So here goes.
Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.
Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.
Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.
This answer is merged from another question.
Your getAge() method is called instance method in Java.
To invoke an instance method, you should have a object of the Class in which this method is defined.
For Example, If this method in a Class called Person, then
Create a Person object using new operator
Person p = new Person();
To get the age of a Person object, use this method
p.getAge()
Although still a second year undergraduate student I will say my opinion. I believe that Java and private variables within your class are "RULES". Therefore because the variables in your class are private I think you use getters and setters to be able to define these variables outside the class.

final optional member variable in Java classes

I have a scenario where some of the final variables declared at class level are optional in some cases.
That means I have different constructors. Some of those have to leave the member variables with null values.
Since I have declared the variable as final, I am forced to initialize those in the constructor. So I have to add var = null; statement in the constructor.
But explicitly assigning variables to null is considered to be a bad practice and tools like PMD, reports it as a violation. (Controversial rule in PMD. But do not want to switch it off, since I do not want the null assignment to be practiced in other areas of my code)
Any other suggessions or good practices to achieve this?
You can use constructor chaining, passing null to the values that are not used in your instance. (You can either use the super constructor if we are discussing inheritance, or a different constructor in the same class.)
After all I would reconsider the design of your classes, for example extract the optional part to a different class.
Instance variables are assigned default values(null in case of custom object).
So unless you are really assigning some value to your final variables why bother about null assignments?
As user has pointed out in the comment above does not stand good for final variables. So what can be done define a no-arg constructor with all final values set to null.
Now in individual arg constructors place a call to this default constructor by using this() as the 1st statement .. then you can assign values depending on the arguments passed.
What you are looking for is the builder pattern.
Say you have a class with a constructor that accepts all the values:
class Job {
private final Integer id;
private final String name;
private final Boolean retry;
public class Job(Integer id, String name, Boolean retry) {
this.id = id;
this.name = name;
this.retry = retry;
}
}
Now, you want to let other create different flavors of that object while keeping it immutable, removing the default value logic from it and keeping it clean. You create a new builder class:
class JobBuilder {
// Values the user MUST provide are non-initialized and
// declared as final
private final Integer id;
// Values the user MAY provide are initialized with default values
// and are not final
private String name = "[none]";
private Boolean retry = true;
public class JobBuilder(Integer id) {
this.id = id;
}
public JobBuilder name(String name) {
this.name = name;
}
public JobBuilder retry(Boolean retry) {
this.retry = retry;
}
public Job build() {
return new Job(this.id, this.name, this.retry);
}
}
Now, you can create different job objects easily while enforcing the requirements:
Job job1 = JobBuilder(1).name("firstJob").retry(false).build();
Job job2 = JobBuilder(2).name("secondJob").build();
Job job3 = JobBuilder(3).build();

Categories