Best way to pass arguments in constructor - java

I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.
just example:
class RowWidget extends FlexTable{
public static void initWidget(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment)
{
// ...
}
}
Then I called below constructor for each record data.
public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
// ...
}
As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like
public RowWidget(DataRawType dataRawType,
Data data,
Data parentData,
Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) {
// ...
}
But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.
Is Anyone suggest me:
How to construct class which have same property required in another
instance?
Note:I know this is possible through static only but don't want to use static.
What is best way to construct class with having some default fix
property for all instances?
Note: I don't want to create another class to achieve it. or any getter/setter method.
Thanks In advance.

I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:
RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();
Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164

Why not create method which will accept the newValues for the properties you want to change & return a new instance of the classes with all other properties copied from the instance on which you invoked this method.

You could separate/extract the parameters from the RowWidget-class fro example in a RowWidgetConfig-class.
class RowWidgetConfig {
// put here all your parameters that you need to initialize only once
// init using setters
}
Now create once instance of that class and pass it among the other parameters to RowWidget constructor.
Another alternative would be to have factory for creating RowWidget instances. The factory would also contain all the parameters you need for a row instance plus a factory method createNewRowWidget witch creates an instance base on the parameters contained in the factory.
class RowWidgetFactory {
// put here all your parameters that you need to initialize only once
// init using setters
public RowWidget createNewRowWidget() {
// create
return ...
}
}

How to construct class which have same property required in another instance?
To achive this you can have a super class with all the properties you want. So any class extending this super class will be have these properties. This way you don't need to use static keyword.
What is best way to construct class with having some default fix property for all instances?
For this one you can have an interface with some constant properties. This way any class implementing this interface will be having the fixed properties.

The static initWidget() thing just doesn't seem right for me. Though probably now you will only have one set of RowWidgets which share some properties, it is also reasonable to have 2 sets of RowWidgets, each set will have its own "shared" properties. Things will be much more fluent and you have much more choices in building more reasonable APIs if you refactor your code to make a more reasonable design
Assume now I introduce something like a RowGroup (which kind of represents the "shared" thing you mentioned)
(Honestly I don't quite get the meaning for your design, I am just making it up base on your code);
public class RowGroup {
public RowGroup(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) { .... }
public void addRow(DataRawType dataRawType, Data data, Data parentData) {...}
}
When people use, it looks something like:
RowGroup rowGroup = new RowGroup(form, permissionMap, gridMode, isApplied, isChildExist, isChildAttach);
rowGroup.addRow(DataRawType.A, dataA, parentA);
rowGroup.addRow(DataRawType.B, dataB, parentB);
You may even provide builder-like syntax or a lot other choices.
RowGroup rowGroup
= new RowGroup(.....)
.addRow(DataRawType.A, dataA, parentA)
.addRow(DataRawType.B, dataB, parentB);
Even more important, the design now make more sense to me.

If you did not want to create another class, I'd suggest what A4L suggested.
Without creating another class, I would create constructor that takes all parameters and factory method that uses current instance as template and pass its own parameters to constructor parameter.
example (with obvious parts ommited)
class A{
public A(int p1, int p2){...}
public A create(int p2) {
return new A(this.p1,p2);
}

Related

Access public final static field from tml page

I have a grid where I would like to load the data from method. This method is taking String as a parameter and produce necessary List as output.
For example, it can look like this:
public List<SomeObject> getContactBasedOnType(final String type)
{
final List<SomeObject> returnList = new ArrayList<>();
...//based on "type" list will be populated by different data
return returnList;
}
and then in my tml page I will use it as follows:
<t:grid t:source="getSomeData('STRING')"...
>...</t:grid>
Now, I would like to replace 'STRING' with a public static String field from a class other than component class, for example:
<t:grid t:source="getSomeData(com.example.Class.STATIC_FINAL_FIELD)"...
>...</t:grid>
Is there any way I can do that directly? So without using any additional methods in a component class or annotated fields?
There is a way to achieve what you asked, but it's an awful hack.
<t:grid
t:source="getSomeData(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').get(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').getType().newInstance()))">
...
</t:grid>
Note that, in your question, the method in the component class is named getContactBasedOnType while in your tmls you are referencing getSomeData. The method names must match, of course.
Again, the above is a terrible hack, but the only solution I got to work under the constraint that the component class may not be touched.
Making the list a property of the component class and populating it in the setupRender() method would be a much better design.

How these codes work (Constructor And ListView)

I was following the udemy android app development course, In the course, we were writing code to Create A listview and get some data when the user clicks on the list, to do that the teacher uses a thing called Constructor I know how constructors work theoretically but can't understand the way it works in code. It will be great if someone can explain what these lines of codes do.
edit: Full Code is here https://github.com/atilsamancioglu/A14-LandmarkBook
import android.graphics.Bitmap;
public class Globals {
private static Globals instance;
private Bitmap chosenImage;
private Globals(){
}
public void setData(Bitmap chosenImage){
this.chosenImage=chosenImage;
}
public Bitmap getData(){
return this.chosenImage;
}
public static Globals getInstance() {
if(instance==null){
instance = new Globals();
}
return instance;
}
}
Constructors are special methods invoked when an object is created and are used to initialize them.
A constructor can be used to provide initial values for object attributes.
You can think of constructors as methods that will set up your class by default, so you don’t need to repeat the same code every time.
In your codes, you can define the constructor as below(it may be unrelated, it's just an example):
private Globals(int id){
return chosenImage.setId(id);
}
The constructor is called when you create an object using the new keyword:
Globals objectGlobe = new Globals(000008);
Also a single class can have multiple constructors with different numbers of parameters.
The setter methods inside the constructors can be used to set the attribute values.
It's not bad to be mentioned that; Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.

Java - how can I loop methods with same name but different parameters

I have class named: ComplexValidator that extends absract class Validator which have two methods:
Validate(Part part);
getAnswer():
I also have validators, lets name them A, B, C and D.
So
AValidator extends Validator
BValidator extends Validator
CValidator extends Validator
DValidator extends Validator
I am not in front of my code right not so I will use pseudo-code.
CValidator takes different parameter than rest of it, A B and D uses part to get filename etc, but CValidator uses numberOfFiles (which are increased in loop (for part p: multipart) so after every time loop is repeated numberoffiles is increased so I can compare it with maxNumberOfFiles field).
Sadly I didnt know how to make abstract class that will take any parameter to method so all methods must take Part part. Cvalidator doesnt use it and I had to make field numberOfFiles static so I can get access to it.
Is there any way to make those validators takes no parameters but no using static?
Is there any way to make abstract class the way that child classes will be able to change arguments it take?
And if it takes other arguments HOW can I loop it all when I have:
List <Validator> validators = new ArrayList<>();
in my ComplexValidator.
and then I add all child validators to it and loop over them like that:
for (Validator v: validators){
validate(part);
}
The types of the parameters of an overriden method must be the same as the original method.
To face your problem I would create a custom class that wraps all the different parameters that you might want to pass to the validate function.
Something like that
class Wrapper{
Part param1;
File param2;
File param3;
}
class Validator{
void validate (Wrapper wrapper);
}
class ValidatorA extends Validate{
void validate (Wrapper wrapper){
//use wrapper.part...
}
}
class ValidatorC extends Validate{
void validate (Wrapper wrapper){
//use wrapper.file...
}
}
You may want to use java reflection. With a Class you can either getMethods and loop throught the methods and getParameterTypes of each method or if you know in advance the types of the method you wish you can getMethod (without s) and provide an array of type.
In your case I would go to the first method and depending on the presence of the second parameter (number of files), invoke the method the good way (with all the parameters needed).

How to avoid reading property file multiple times

We have some data in properties file. This data is used across many classes. So, we create a Properties class object in each and every class and then read data using getProperty() method. This is leading to duplication of code.
Can someone please suggest some best practices to avoid this?
One thing that came to my mind is:
Create a class
Have a public variable for each property in property file in this class
Have a method that assigns values to each and every property
In the class where property values are required, create an object for this class and access the public variables
But, things i don't like with this approach are public variables and if at all a new property is added to the property file, i need to add code to read that property in the class.
Any help is appreciated.
Thank you!
You can create a Singleton class, that loads the properties the first time it gets invoked.. and a public method that retrieves the property value, for a given property key..
This is assuming you're using a standart Properties file... But you can extrapolate this to any key-value pair, changing Properties type to a Map or something else.
Something like
public class PropertyHandler{
private static PropertyHandler instance = null;
private Properties props = null;
private PropertyHandler(){
// Here you could read the file into props object
this.props = .....
}
public static synchronized PropertyHandler getInstance(){
if (instance == null)
instance = new PropertyHandler();
return instance;
}
public String getValue(String propKey){
return this.props.getProperty(propKey);
}
}
Then you can invoke this as needed.. from any code.. like this.
String myValue = PropertyHandler.getInstance().getValue(propKey);
Hope this helps
for me static inner class is the best possible way to do it. It will do it with lazily, as class loading is synchronized so thread safe, plus performant also. So with this we are achieving three things:
good performance because with synchronizing the liveliness will suffer, but here we are using static inner class.
thread safety because when inner class will be loaded than only map will be initialized as the class loading is thread safe hence all total thread safe.
Inner class will be loaded when we will call Singleton.initialize().get(key) so the map gets initialized lazily.
Below is the code...
public class SingletonFactory
{
private static class Singleton
{
private static final Map<String, String> map = new HashMap<String, String>();
static
{
try
{
//here we can read properties files
map.put("KEY", "VALUE");
}
catch(Exception e)
{
//we can do the exception handling
System.out.println(e);
}
}
private static Map<String, String> initialize()
{
return map;
}
}
public static String getValue(String key)
{
return Singleton.initialize().get(key);
}
}
One out of the box option is to use system properties. You can add your own system properties to your execution environment.
You can do this with a dedicated class having a static Properties object. See here for an example.
I could be misunderstanding your data flow here, but this is what seems "normal" to me:
Create a readPropFile method.
This should read a file and appropriately parse the properties it finds.
These properties can be stored in a Map<String, Object>, hashed by property name.
Read property file once (presumably when the application starts, or whenever it's appropriate to load properties) --> Properties object (say, props).
Pass props around to anything that needs access to those properties.
Or if you don't want to pass it around explicitly, use a static accessor as illustrated here.
Access properties using props.get("PROPERTY_NAME") (which just looks up that property in the internal Map).
If you don't want to use String lookups, you can keep an enum of valid property names somewhere, and do storage/lookups using that, but then you have to update that enum every time you add a new property to the file.
I've had success using an Enum, and in the constructor using the name() method to read a property of the same name. Be sure to handle exceptions in a reasonable way or else the whole class will fail to load and you won't get a helpful error message.
Benefits of this approach are that each enum value automatically corresponds to a property without having to write individual mapping code for each property. You do of course need an enum value for each property (that's unavoidable if you want DRY prop references), but you avoid repetitive per-property initialization code using unchecked Strings.
Drawbacks are that enums don't allow generic types, so if you wanted certain properties to return Integer and others to return String, then you might be better served with a classic singleton class design.
If you want to go crazy with this you could also write a script to generate your Enum or singleton java source code from the properties file, to keep your code extra DRY.

How to deal with special "constant" instances of object when using DI

My project is heavily using dependency injection, and I'm being very careful to avoid service locator antipattern. All objects are structured using constructor injection that allow easily identifiable list of dependencies. Now I'm building an object, and it has a special "constant" instance, which is basically static/singleton (consider example of something like Integer.MinValue). So my initial reflex was to create a static field with a static "getter" method, which would create the instance of the object if it wasn't previously created. The object itself has dependencies however, so I'm confused on what's the best practice for instantiating this "special instance". I'm looking for recommendations on how to best structure code in this scenario, ideally without having to call upon the container for resolution of dependencies. Some code:
public class PressureUnit extends DataUnit {
private static PressureUnit standardAtmosphere;
public static PressureUnit StandardAtmosphere() {
if(standardAtmosphere == null){
standardAtmosphere = new PressureUnit(1013.25); // this line is what is bothering me as I need to resolve other dependencies (have to use new as it's a static method and can't be injected like everywhere else)
}
return standardAtmosphere;
}
#AssistedInject
public PressureUnit(ITimeProvider timeProvider, IUnitProvider unitProvider, #Assisted double value) {
this(timeProvider, unitProvider, value, PressureUnits.hPa);
}
...
}
I really don't see any problem in your code since you are not newing up dependencies here and there, now with that being said i can give some suggestions:
If you specifically want the container to call an existing static factory method, you can use StaticFactoryExtension.
Why don't you use a factory.
Consider refactoring you design and removing the static method if possible.

Categories

Resources