I would like to create a calculator application that can switch between different number bases. As far as entering digits is concerned, I was thinking the following would be a flexible api:
public interface ICalculator
{
string Enter(INumberElement element);
}
public class BaseTenCalculator : ICalculator
{
public string Enter(INumberElement element)
{
...
}
}
public class BaseTwoCalculator : ICalculator
{
public string Enter(INumberElement element)
{
...
}
}
My problem is that for the BaseTenCalculator, I would like a method
Enter(BaseTenNumberElement element)
and for a BaseTwoCalculator, I would like a method
Enter(BaseTwoNumberElement element)
to make sure only valid digits for that number base get entered. However, the only way I can think of enforcing this constraint is downcasting the 'element' argument in the two different implementations, and throwing an exception if INumberElement is not of the correct type. I feel like this is 'wrong', and I'm missing something. Is there another way? Is it even possible to create a common interface for two different number base calculators?
public interface ICalculator<in T> where T : INumberElement
{
string Enter(T element);
}
public class BaseTenCalculator : ICalculator<BaseTenNumberElement>
{
public string Enter(BaseTenNumberElement element)
{
throw new NotImplementedException();
}
}
public class BaseTwoCalculator : ICalculator<BaseTwoNumberElement>
{
public string Enter(BaseTwoNumberElement element)
{
throw new NotImplementedException();
}
}
I think you're thinking of the problem incorrectly. A number is a number regardless of base. Base is only a visible representation of the number. A good example to work from might be BigInteger. It has a constructor: BigInteger(String val, int radix), and a function: toString(int radix). All the work of representing the number is done the same. The only thing that differs is parsing from a string representation into the number, and then getting back out into a number format in a particular base.
You could create a multi-base calculator by using BigInteger or BigDecimal underneath and just using a base selection to set the radix value to parse or print the number(s). You'd also want to limit the input buttons (assuming you're using buttons), but that's really just a counting problem.
Related
I have a design problem where the requirement is something like this :
Write a generate function that takes a parameter("TYPE")
Depending on the TYPE, I need to generate a String and return it. So TYPE effectively changes the way you generate the String.
I am deliberating between two design options :
Using enum : Create a enum having the TYPES. Then provide a generate method that depending on TYPE does the processing and returns a string.
Using Interface : Create an interface having a function generate(). Create implementations for each TYPE, to implement the generate().
Which do you feel is better and for what reasons.
Although, Approach # 2, follows the Open/Closed Principle of OOAD i.e You will be adding new interface implementation, everytime new TYPE is added and you will not modify existing code, which is very safe approach as it does not need testing of old code/method. So your code will be open for extension but closed for modification. However, if you are going to very frequently add new TYPE, then Approach # 2, makes sense.
IMO, in this case, I would suggest to use Approach # 1, as the business requirement is really simple i.e to generate a String based on Parameter TYPE. So using interface will be over-engineering in my opinion(if TYPES are not going to be added frequently).
It will be good to use some design pattern for this problem statement to make your code more robust and reusable. I will suggest to you Strategy Design Pattern. It is abstraction based pattern that uses Interface.
Basic Example:
public interface IMyStrategy
{
string Generate(string someValue);
}
public class StragegyA : IMyStrategy
{
public string Generate(string somevalue)
{
return /Implementation/;
}
}
public class StragegyB : IMyStrategy
{
public string Generate(string somevalue)
{
return /Implementation/;
}
}
public class MyStrategyContext
{
private readonly IMyStrategy _ImyStrategy;
public MyStrategyContextIMyStrategy(IMyStrategy myStragegy)
{
_ImyStrategy = myStragegy
}
public string GenerateResult(string someValue)
{
return _ImyStrategy .Generate(someValue);
}
}
[Test]
public void GenerateValue()
{
var abc = new MyStrategyContext(new StragegyA());
abc.GenerateResult("hey print");
}
I have a class that we use for paginated results, as follows:
public class PaginatedList<T> extends LinkedList<T> {
private int offset;
private int count;
private int totalResultCount;
//...
}
and I'd like Jackson to serialize it like this:
{
"results":[1,2,3],
"offset":0,
"count":3,
"totalResultCount":15
}
(where the parent list contains the three integer values 1,2 and 3.)
In my first attempt I discovered that Jackson effectively ignores any properties on classes which are assignable to a Collection class. In hindsight, this makes sense, and so I'm now in search of a workaround. A search of SO resulted in two similar questions:
jackson-serialization-includes-subclasss-fields
jaxb-how-to-serialize-fields-in-a-subclass-of-a-collection
However, both of these resulted in the suggestion to switch from inheritance to composition.
I am specifically looking for a solution that allows the class to extend a collection. This 'PaginatedList' class is part of the common core of the enterprise, and extends Collection so that it can be used (and introspected) as a collection throughout the code. Changing to composition isn't an option. That being said, I am free to annotate and otherwise change this class to support serialization as I described above.
So, from what I can tell, there's two parts I'm missing (what I'm looking for in an answer):
How to get Jackson to 'see' the added properties?
How to get Jackson to label the collection's content as a 'results' property in the JSON output?
(PS: I'm only concerned with serialization.)
Ashley Frieze pointed this out in a comment, and deserves the credit for this answer.
I solved this by creating a JsonSerializer instance as follows:
public class PaginatedListSerializer extends JsonSerializer<PaginatedList> {
#Override
public Class<PaginatedList> handledType() {
return PaginatedList.class;
}
#Override
public void serialize(PaginatedList value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeArrayFieldStart("results");
for (Object entry : value) {
jgen.writeObject(entry);
}
jgen.writeEndArray();
jgen.writeNumberField("offset", value.offset);
jgen.writeNumberField("count", value.count);
jgen.writeNumberField("totalResultCount", value.totalResultCount);
jgen.writeEndObject();
}
}
and, of course, register it as a module:
SimpleModule testModule = new SimpleModule("PaginatedListSerializerModule", new Version(1, 0, 0, null, null, null));
testModule.addSerializer(new PaginatedListSerializer());
mapper.registerModule(testModule);
Imagine we have a number of related objects (equivalently DB tables), for example:
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
}
public class Job {
private String company;
private int salary;
..
}
public class House {
private Address address;
private int age;
private int numRooms;
..
}
public class Address {
private String town;
private String street;
..
}
How to best design a system for easily defining and accessing widely varying subsets of data on these objects/tables? Design patterns, pros and cons, are very welcome. I'm using Java, but this is a more general problem.
For example, I want to easily say:
I'd like some object with (Person.name, Person.height, Job.company, Address.street)
I'd like some object with (Job.company, House.numRooms, Address.town)
Etc.
Other assumptions:
We can assume that we're always getting a known structure of objects on the input, e.g. a Person with its Job, House, and Address.
The resulting object doesn't necessarily need to know the names of the fields it was constructed from, i.e. for subset defined as (Person.name, Person.height, Job.company, Address.street) it can be the array of Objects {"Joe Doe", 180, "ACompany Inc.", "Main Street"}.
The object/table hierarchy is complex, so there are hundreds of data fields.
There may be hundreds of subsets that need to be defined.
A minority of fields to obtain may be computed from actual fields, e.g. I may want to get a person's age, computed as (now().getYear() - Person.birtday.getYear()).
Here are some options I see:
A SQL view for each subset.
Minuses:
They will be almost the same for similar subsets. This is OK just for field names, but not great for the joins part, which could ideally be refactored out to a common place.
Less testable than a solution in code.
Using a DTO assembler, e.g. http://www.genericdtoassembler.org/
This could be used to flatten the complex structure of input objects into a single DTO.
Minuses:
I'm not sure how I'd then proceed to easily define subsets of fields on this DTO. Perhaps if I could somehow set the ones irrelevant to the current subset to null? Not sure how.
Not sure if I can do computed fields easily in this way.
A custom mapper I came up with.
Relevant code:
// The enum has a value for each field in the Person objects hierarchy
// that we may be interested in.
public enum DataField {
PERSON_NAME(new PersonNameExtractor()),
..
PERSON_AGE(new PersonAgeExtractor()),
..
COMPANY(new CompanyExtractor()),
..
}
// This is the container for field-value pairs from a given instance of
// the object hierarchy.
public class Vector {
private Map<DataField, Object> fields;
..
}
// Extractors know how to get the value for a given DataField
// from the object hierarchy. There's one extractor per each field.
public interface Extractor<T> {
public T extract(Person person);
}
public class PersonNameExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getName();
}
}
public class PersonAgeExtractor implements Extractor<Integer> {
public int extract(Person person) {
return now().getYear() - person.getBirthday().getYear();
}
}
public class CompanyExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getJob().getCompany();
}
}
// Building the Vector using all the fields from the DataField enum
// and the extractors.
public class FullVectorBuilder {
public Vector buildVector(Person person) {
Vector vector = new Vector();
for (DataField field : DataField.values()) {
vector.addField(field, field.getExtractor().extract(person));
}
return vector;
}
}
// Definition of a subset of fields on the Vector.
public interface Selector {
public List<DataField> getFields();
}
public class SampleSubsetSelector implements Selector {
private List<DataField> fields = ImmutableList.of(PERSON_NAME, COMPANY);
...
}
// Finally, a builder for the subset Vector, choosing only
// fields pointed to by the selector.
public class SubsetVectorBuilder {
public Vector buildSubsetVector(Vector fullVector, Selector selector) {
Vector subsetVector = new Vector();
for (DataField field : selector.getFields()) {
subsetVector.addField(field, fullVector.getValue(field));
}
return subsetVector;
}
}
Minuses:
Need to create a tiny Extractor class for each of hundreds of data fields.
This is a custom solution that I came up with, seems to work and I like it, but I feel this problem must have been encountered and solved before, likely in a better way.. Has it?
Edit
Each object knows how to turn itself into a Map of fields, keyed on an enum of all fields.
E.g.
public enum DataField {
PERSON_NAME,
..
PERSON_AGE,
..
COMPANY,
..
}
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
public Map<DataField, Object> toMap() {
return ImmutableMap
.add(DataField.PERSON_NAME, name)
.add(DataField.BIRTHDAY, birthday)
.add(DataField.HEIGHT, height)
.add(DataField.AGE, now().getYear() - birthday.getYear())
.build();
}
}
Then, I could build a Vector combining all the Maps, and select subsets from it like in 3.
Minuses:
Enum name clashes, e.g. if Job has an Address and House has an Address, then I want to be able to specify a subset taking street name of both. But how do I then define the toMap() method in the Address class?
No obvious place to put code doing computed fields requiring data from more than one object, e.g. physical distance from Address of House to Address of Company.
Many thanks!
Over in-memory object mapping in the application, I would favor database processing of the data for better performance. Views, or more elaborate OLAP/datawarehouse tooling could do the trick. If the calculated fields remain basic, as in "age = now - birth", I see nothing wrong with having that logic in the DB.
On the code side, given the large number of DTOs you have to deal with, you could use classless dynamic (available in some JVM languages) or JSON objects. The idea is that when a data structure changes, you only need to modify the DB and the UI, saving you the cost of changing a whole bunch of classes in between.
In a my view I have an HBox
#FXML
private HBox hboxWarning;
and I want hide/show it according to the value of
private ObjectProperty<Integer> maxClientCount;
If maxClientCount > 10 then hboxWarning is visible else it's hide.
I bound the two elements in this way
hboxWarning.visibleProperty().bind(IntegerProperty.integerProperty(maxClientCount).greaterThan(10));
and works well. My problem is that
IntegerProperty.integerProperty(maxClientCount)
sets to zero the current value of maxClientCount. Is it a JavaFx bug or I'm using IntegerProperty.integerProperty improperly? And
how can I achieve my goal?
Turned out to be not as easy as assumed: the core fix needs additional methods in BidirectionalBinding to cope with the swapped sequence of number types. The actual number bindings are private, so no way to access in workaround code.
// method in u5, binds the wrong way round
// (for usage in IntegerProperty.integerProperty)
public static BidirectionalBinding bindNumber(Property<Integer> property1,
IntegerProperty property2)
// calls
private static <T extends Number> BidirectionalBinding bindNumber(Property<T> property1,
Property<Number> property2) {
The sequence is crucial because we need a type-cast from Number to T when setting the value of p1 (which is safe because we know that the number-type property copes with conversion from Number -> concrete type). Core fix simply adds all those methods with switched parameter sequence.
For a custom hack until the release of JDK 8u20, the only way I see is to not use the special number binding methods but the generic object binding:
public static IntegerProperty integerProperty(final Property<Integer> property) {
if (property == null) {
throw new NullPointerException("Property cannot be null");
}
return new IntegerPropertyBase() {
{
bindBidirectional(cast(property));
// original:
//BidirectionalBinding.bindNumber(property, this);
}
#Override
public Object getBean() {
return null; // Virtual property, no bean
}
#Override
public String getName() {
return property.getName();
}
#Override
protected void finalize() throws Throwable {
try {
unbindBidirectional(cast(property));
// original
// BidirectionalBinding.unbindNumber(property, this);
} finally {
super.finalize();
}
}
};
}
/**
* Type cast to allow bidi binding with a concrete XXProperty (with
* XX = Integer, Double ...). This is (?) safe because the XXProperty
* internally copes with type conversions from Number to the concrete
* type on setting its own value and exports the concrete type as
* needed by the object property.
*
*/
private static <T extends Number> Property<Number> cast(Property<T> p) {
return (Property<Number>) p;
}
Take it with a grain of salt - while rudimentarily tested, there might be side-effects I overlooked.
As rightly said by #kleopatra this is a JavaFx bug fixed in JDK 8u20.
Meanwhile I used the following workaround:
int maxClients = maxClientCount.get();
hboxWarning.visibleProperty().bind(IntegerProperty.integerProperty(maxClientCount).greaterThan(10));
maxClientCount.setValue(maxClients);
I hope this can help someone.
I wanted to know if there is a known pattern or convention for the following scenario:
I have two classes: MAT (name:String, address:String) & MATversion(type:String, version:int)
Now I have a DataGrid (DataTable) which will take a generic List of objects for the column mapping and data filling.
The columns should be name, type, version. (Which are distributed in MAT and MATversion)
So I create a class to make this work. This class will merge the needed properties from each class (MAT, MATversion).
-> MAT_MATversion (name:String, type:String, version:int).
Does there exist a naming convention for such an class like MAT_MATversion? Any pattern that mirrors that?
Thanks!
Is there any specific reason why the merged result has to be a unique class?
I'm assuming every MAT object has a single MATversion
you can add a couple of custom properties who will return the type and version of the underlying MATversion object
In C# this would result in something like this
public class MAT{
public String name{ get;set;};
public String adress{ get;set;};
public MATversion myVersion;
public String type {
get{
return myVersion.type;
}
set{
myVersion.type = value;
}
}
public int version {
get{
return myVersion.version;
}
set{
myVersion.version = value;
}
}
}
I'm aware that this doesn't answer the question about design patterns, but I couldn't ask/suggest another approach in a comment since I don't have that right yet.