Overriding mutator methods for sake of validation [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am currently working on an Object Oriented Design project, and would like to know if there is a better way to validate data in mutators of subclasses.
For example, I have a Home class with the subclasses Apartment, Condo, and House. In the Home class, I would like to include the mutators for (private) fields that the subclasses share. Say one of the fields is squareFootage. Is there a way to make the mutator in Home generic enough so that the subclasses can then set their own valid values for squareFootage without having to override the mutator completely? That is, I want different valid ranges for squareFootage for each subclass.
I've tried setting possible range values in Home, then override them in the subclasses. Unfortunately, the mutator in Home still grabs from the Home class and not the subclass.
So, I've resorted to abstracting the mutators, but unfortunately this results in a lot of repeated code, since I can literally copy and paste the mutators in each subclass.
I want to make the possible range values static if possible, and I understand this may be possible with reflection, but I'd really like to avoid using it for this project.

I think is possible by adding an abstract "validator" method that have to be implemented in the subclasses, something like this:
public class Home {
private float squareFootage;
public abstract void validateSquareFootage() throws MyValidationException; // you could throw an exception, runtime exception or return a boolean to indicate if value is valid or not
public void setSquareFootage(float squareFootage) {
validateSquareFootage(squareFootage); // again, throws exception or returns boolean, up to you
this.squareFootage = squareFootage;
}
// ... rest of implementation
}
And in a subclase:
public class Condo extends Home {
#Override
public void validateSquareFootage(float squareFootage) throws MyValidationException {
// ... do validations
}
}
and you don't have to override the mutator at all, just implement the correct validator.

It would probably be best to make the Home class an abstract class and have that extended in your subclasses. That way you can create methods in the home class that will hold true for all your subclasses but you can override them in the subclasses

If I understood your problem correctly, I think you want something like this ?
abstract class Home<T>{
protected T squareFootage;
abstract void setSquareFootage(T t);
}
class Apartment extends Home<String>{
#Override void setSquareFootage(String t) {
//...do something about the parameter
this.squareFootage = t;
}
}
class Condo extends Home<Integer>{
#Override void setSquareFootage(Integer t) {
//...do something about the parameter
this.squareFootage = t;
}
}
class House extends Home<Boolean>{
#Override void setSquareFootage(Boolean t) {
//...do something about the parameter
this.squareFootage = t;
}
}

Related

Design pattern to enrich a class with new features [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have implemented a series of classes to manage search / detail page with JSF and PrimeFaces.
More in detail, I've created an abstract class SearchDetailView<C extends BaseView, M> in order to centralize common functionality for Search/Detail page.
In short, I've a class MyView that extends the base SearchDetailView.
Now I'd like to add another behavior to MyView, that is Confirm Dialog.
I'm wondering what design pattern I have to use? I was going to use the design pattern Decorator, but I don't need to add new behaviors at runtime, but I've already know what behaviors MyView needs.
I can't extends two classes (obviously), but I didn't like to have many combinations of "base" classes. I'd like to create a second abstract class like ConfirmDialogDecorator in order to add "programmatically" the extra functionality.
So, I ask you which design pattern add behavior to a class?
Actually my code is like the following:
public abstract class SearchDetailView<C extends BaseController, M> extends BaseView {
[...]
}
public abstract class ConfirmDialogDecorator<C extends BaseController, M> extends SearchDetailView<C, M> {
public void showDialog(final String message) { [...] }
}
public class MyView extends ConfirmDialogDecorator<MyController, MyModel> {
[...]
}
But I'd like to separate ConfirmDialogDecorator from SearchDetailView.
Any idea? Thanks.
UPDATE:
As suggested in the two answers I used the Java 8 default methods (Mixin pattern?):
public interface ConfirmDialog {
Dialog dialog = new Dialog();
default public String getConfirmMessage() {
return "Do you confirm?";
}
default String getWidgetVar() {
return "confirmDialog";
}
public void onConfirm();
default void showDialog(final String message) {
dialog.setWidgetVar(this.getWidgetVar());
dialog.setMessage(message);
dialog.showDialog(message);
}
class Dialog {
private String message;
private String widgetVar;
String getMessage() {
return message;
}
void setMessage(final String message) {
this.message = message;
}
public String getWidgetVar() {
return widgetVar;
}
public void setWidgetVar(final String widgetVar) {
this.widgetVar = widgetVar;
}
void showDialog(final String message) {
final PrimeFaces current = PrimeFaces.current();
current.executeScript("PF('" + this.widgetVar + "').show();");
}
}
}
public class MyView extends SearchDetailView<MyController, MyModel>
implements ConfirmDialog {
public void onSave() {
if(!this.someCheck()) {
this.showDialog("Are you really sure?");
} else {
this.save();
}
}
#Override
public void onConfirm() {
this.save();
}
public void save() {
// The save
}
}
In the xhtml:
<p:confirmDialog widgetVar="confirmDialog" global="true">
<h:outputText value="#{myView.confirmMessage}" />
<p:commandButton value="Yes" type="button" styleClass="ui-confirmdialog-yes" icon="pi pi-check" />
<p:commandButton value="No" type="button" styleClass="ui-confirmdialog-no" icon="pi pi-times" />
</p:confirmDialog>
I was going to use the design pattern Decorator, but I don't need to
add new behaviors at runtime, but I've already know what behaviors
MyView needs.
and then
I'd like to create a second abstract class like ConfirmDialogDecorator
in order to add "dynamically" the extra functionality.
Don't you say a thing and its contrary ?
The fact that you know decorating possibilities at compile time doesn't mean that the pattern is not adapted.
But I'd like to separate ConfirmDialogDecorator from SearchDetailView.
Decorator is also a alternative to subclassing and avoid classes hierarchies.
Using the pattern by introducing a decorator interface is probably a right way for your requirement.
As alternative Java 8 introduced the notion of default methods in interfaces that allows to add behaviors to classes implementing it.
In a some way, we can consider it as a way to decorate statically classes with additional behaviors without subclassing. Note that as interfaces cannot define instance fields, default methods cannot use it either. So you should consider this alternative according to this constraint.
Usually to add functionality to a class without inheritance be used mixim/trait conception.
You can use default methods or aspect-objected programming in Java to the implementation of this conception

How to inherit fields properly without making them open to the package?

Say, I have a package Pack containing classes A and B. A is self-contained and no one (even in the Pack) should see A's insides, so most of the fields and methods are private.
Now I want to extend A to change one of its private methods keeping the rest - let it be class AMod. Doing it requires most of A's fields and the method to override to be protected, but protected gives access to the package.
So how do I create AMod inside Pack so that AMod has an access to A's fields and methods while no one else does? Make a nested/separate package?
UPD:
UPD2:
UPD3:
As Jacob G. suggested, my code needed redesigning, and I managed to remove the derived class from the architecture. Thanks for help!
The one answer I find missing: don't be so focused on using inheritance in order to avoid code duplication.
If you only need a subtle variation of behavior of A then you should first consider to "wrap" around A (for example via decorator) instead of extending A - the good old FCoI!
If that isn't possible: have a very close look at the common behavior of A and Amod and extract those parts in a common base class.
Finally: don't get too energetic about java access modifiers in the first place. In the end, they help you to communicate a certain thought or idea. "Evil-willing" people will always find a way to work around your intentions. What I am saying is: if you are concerned that your team members use your class in the wrong way ... that is a social problem; and you will never be able to solve that on the technical layer. You have to solve it on the social layer, too (by educating people to ensure that they understand what to do; instead of hoping that private here or protected there will prevent them from doing the wrong thing).
In other words: establish a simple policy such as "only what is marked public is meant to be public; anything else is not" might be able to table such discussions for all times. Versus spending hours and hours to find a perfect private-protected solution within source code.
Thanks for posting code.
My advice would be to first move B#stepBMod into A.java. Then, you can pass a boolean parameter to A#build; with this, you can rewrite A#build:
public Result build(boolean mod) {
stepA();
if (mod) {
stepBMod();
} else {
stepB();
}
stepC();
return result;
}
Now, B.java isn't needed anymore.
Your question is two parts. 1)Accessing fields and 2)Accessing methods.
Case1), you should make class A's fields protected. This means no one can access it by name, except derived classes.
Case2), you cannot access a protected method by name, unless in a derived class. But still you can access a protected method by name using an object of A. In order to prevent other classes making objects, your A class should be abstract.
Here is an example
public abstract class A{
protected int n;
protected void display(){
System.out.println(n);
}
}
public class B extends A{
public void demo(){
B object = new B();
object.display();
}
public void modify(){
n = 0;
}
}
Update
class A
{
public A(Args args){...}
public Result build() {
stepA();
stepB();
stepC();
return result;
}
protected void stepA() {...}
private void stepB() {...}
protected void stepC() {...}
protected T field;
}
class AMod extends A
{
public AMod(Args args){
super(args);
...
}
public Result build() {
stepA();
stepBMod();
stepC();
return result;
}
private void stepBMod() {...}
}

Using methods with returned jcomponents and generics

This is a two part question. First, is it possible use a generic defined objects method such as:
public class MyClass<T>{
public MyClass(T t){
t.setText("Hello World"); // Assume class T is JMenuIten has the special method setText
}
}
This code doesn't work as is, but show the general idea for what I'm aiming for. I want to use the methods which are particular to that encapsulated object. If however I were to pass in another object such as which contains the encapsulated method .doSomething. I would like to do ...
public class MyClass<T>{
public MyClass(T t){
t.doSomething("Hello World"); // Assume class T is JMenuIten has the special method setText
}
}
I'm hoping that it is possible to do this, otherwise I would have to write multiple constructors to take care of all my special cases.
My second question is similar in that I would like to return a GUI component and execute a statement such as ...
myJPanel.getComponent(1).setText("Hello"); // Assuming index 1 is a JLabel and setText is a specific method defined in the JLabel class
This code does not work because the compiler cannot tell ahead of time what symbols will be needed at runtime, though I was hoping that there was a way of making things like this work. I would also like to know if there is a method that can tell me what class type .getComponent() is returning if that is possible. I'm trying to make code as dynamic as possible without having to hardcode everything.
Thanks
You have to use a bounded wildcard.
e.g.
public interface MyObject {
void myMethod();
}
public class GenericObj<T extends MyObject> {
private T t;
public void invokeMethod() {
t.myMethod(); //this way you can invoke methods (declcared in MyObject) on T
}
}

Call a child class method from a parent class object

I have the following classes
class Person {
private String name;
void getName(){...}}
class Student extends Person{
String class;
void getClass(){...}
}
class Teacher extends Person{
String experience;
void getExperience(){...}
}
This is just a simplified version of my actual schema. Initially I don't know the type of person that needs to be created, so the function that handles the creation of these objects takes the general Person object as a parameter.
void calculate(Person p){...}
Now I want to access the methods of the child classes using this parent class object. I also need to access parent class methods from time to time so I CANNOT MAKE IT ABSTRACT.
I guess I simplified too much in the above example, so here goes , this is the actual structure.
class Question {
// private attributes
:
private QuestionOption option;
// getters and setters for private attributes
:
public QuestionOption getOption(){...}
}
class QuestionOption{
....
}
class ChoiceQuestionOption extends QuestionOption{
private boolean allowMultiple;
public boolean getMultiple(){...}
}
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption().getMultiple())
{...}
}
}
The if statement says "cannot find getMultiple for QuestionOption." OuestionOption has many more child classes that have different types of methods that are not common among the children (getMultiple is not common among the children)
NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you should be able to do it like:
void calculate(Person p) {
((Student)p).method();
}
a safe way would be:
void calculate(Person p) {
if(p instanceof Student) ((Student)p).method();
}
A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:
class Person {
String name;
void getName(){...}
void calculate();
}
and then
class Student extends Person{
String class;
void getClass(){...}
#Override
void calculate() {
// do something with a Student
}
}
and
class Teacher extends Person{
String experience;
void getExperience(){...}
#Override
void calculate() {
// do something with a Teacher
}
}
By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.
In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.
Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).
I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.
http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html
The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.
UPDATE: found it here.
Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:
void caluculate(Person p){
p.dotheCalculate();
}
This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
class Car extends Vehicle {
protected int numberOfSeats = 1;
public int getNumberOfSeats() {
return this.numberOfSeats;
}
public void printNumberOfSeats() {
// return this.numberOfSeats;
System.out.println(numberOfSeats);
}
}
//Parent class
class Vehicle {
protected String licensePlate = null;
public void setLicensePlate(String license) {
this.licensePlate = license;
System.out.println(licensePlate);
}
public static void main(String []args) {
Vehicle c = new Vehicle();
c.setLicensePlate("LASKF12341");
//Used downcasting to call the child method from the parent class.
//Downcasting = It’s the casting from a superclass to a subclass.
Vehicle d = new Car();
((Car) d).printNumberOfSeats();
}
}
One possible solution can be
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption() instanceof ChoiceQuestionOption)
{
ChoiceQuestionOption choiceQuestion = (ChoiceQuestionOption)q.getOption();
boolean result = choiceQuestion.getMultiple();
//do something with result......
}
}
}

Elegant alternatives for huge amount of arguments in class constructor [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
For example I have a class that builds the GUI, a class that handles all the events for the GUI and the main class that holds all the objects that are affected by the GUI-Objects (mostly sliders) and instances both the GUI-class and event-class.
Now the event-class's constructor has as arguments the GUI class and every object that is being changed by the GUI. These are quite allot of objects so the amount of arguments I have now are about 8 and still growing.
Is there a more elegant solution to my problem, 30 arguments simply doesn't feel right?
ps, I'd rather not combine classes because all three are quite big and would make everything much less readable.
Often a builder object with fluent syntax is used in such a case. You change:
new XYZEvent(a, null, null, b, null, c, d, null, null)
to
new XYZEventBuilder().setA(a).setB(b).setC(c).setD(d).build()
You can create a configuration class which holds default values for all parameters:
public class GUIConfig {
private String name = "default";
// more private declarations
public GUIConfig() {
// constructor, just for setting defaults
}
// getters and setters
}
Now you can simply create your GUI class instance like this:
GUIConfig guiConfig = new GUIConfig();
guiConfig.setName("foo");
// more setters
GUI myGUI = new GUI(guiConfig);
or for using only defaults:
GUI myGUI = new GUI(new GUIConfig());
Use a DTO (Data Transfer Object) to hold all your classes. This can then be passed in a single parameter.
a DTO does not have any behavior
except for storage and retrieval of
its own data
You should consider using Google's AutoValue library: https://github.com/google/auto/blob/master/value/userguide/index.md
#AutoValue
public abstract class Card {
#Nullable
public abstract Integer localId();
public abstract Long utcStart();
public abstract Integer paramA();
public abstract Integer paramB();
#Nullable
public abstract Boolean paramC();
public static Builder builder() {
return new AutoValue_Card.Builder();
}
#AutoValue.Builder
public abstract static class Builder {
public abstract Builder setLocalId(final Integer localId);
public abstract Builder setUtcStart(final Long utcStart);
public abstract Builder setParamA(final Integer paramA);
public abstract Builder setParamB(final Integer paramB);
public abstract Builder setParamC(final Boolean paramC);
public abstract Card build();
}
}
All the no-mandatory fields can be annotated with #Nullable.
To create an immutable Card object you just use this:
Card myCard = Card.builder()
.setLocalId(123456) // this line can be omitted
.setUtcStart(158632478000)
.setParamA(5)
.setParamB(58)
.setParamC(true) // this line can be omitted
.build();
"AutoValue is a great tool for eliminating the drudgery of writing mundane value classes in Java. It encapsulates much of the advice in Effective Java Chapter 2, and frees you to concentrate on the more interesting aspects of your program. The resulting program is likely to be shorter, clearer, and freer of bugs. Two thumbs up."
-- Joshua Bloch, author, Effective Java

Categories

Resources