It appears clear from Hejlsberg, et. al. 2011 4th Ed. C# Programming Languages that you can make a 'new' function the same name as an existing class member. I can somewhat see why this might be useful , in some kind of versioning conflict scenario,
But what I don't get is why you would ever want to make the 'new' function or the 'shadow' function; private
There are few differences between those.
1. Shadowing is bad programming practice according to OOPs concepts.
2. In shadowing signature could be different.
3. In Shadowing both Derived class methods and Base Class methods are available for use.
In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class method, and the new modifier hides it.
Related
I would like to know why do we use implementsInterface element in entities. I know one example where they use it to make it as assignable entity. But I could not understand what other purpose and how/why it is being used in entities.
Example: Injuryincident entity has claimantsupplier and coveragesupplier interface
I like to see it from this prespective, simplified and assuming that you have some java background:
As you probably already know it, having an entity means in the end of the day, having a Java class... Well, by using the implementsInterface element in your entity, is similar to implement an interface in you java class.
Here you have a quick example...
Consider the following:
MyEntiti.eti
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable"/>
AnInterface.gs
package mypkg
interface AnInterface {
function doSomething()
}
AnInterfaceImpl.gs
package mypkg
class AnInterfaceImpl implements AnInterface {
override function doSomething() {
print("Hello!")
}
}
Image that you need MyEntity to have the ability of "doSomething", you just need to add the implementsInterface:
<?xml version="1.0"?>
<entity
xmlns="http://guidewire.com/datamodel"
entity="MyEntity"
table="myentity"
type="retireable">
<implementsInterface
iface="mypkg.AnInterface"
impl="mypkg.AnInterfaceImpl"/>
</entity>
By doing that, the following code must work:
var myEntity = new MyEntity()
myEntity.doSomething() //this will call the method defined in the interface-implementation
And even better, you migth let you implementation to recognize the related object of MyEntity and use it as per your needs:
package mypkg
class AnInterfaceImpl implements AnInterface {
private final var _relatedEntity : MyEntity
construct(relatedTo : MyEntity) {
_relatedEntity = relatedTo
}
override function doSomething() {
var createUser = _relatedEntity.CreateUser // you can accees to whatever you need
print("Hello!, this is the related instace of MyEntity: ${_relatedEntity}")
}
}
Hope it helps, regards!
I won't be repeating the other answer describing how it works, but I would like to mention how implementing an interface on an entity is different (and serves different purposes) compared to using enhancements.
On basic level both approaches let you add extra functionality to your entity classes. In most cases what you really want to do is just create/expand an enhancement - they are easier to write, more convenient to modify and just as effective when all you want is to just add a new function or calculated property.
When you implement an interface, you're bringing in some more serious guns. While this approach takes more work and requires creation of several files (not to mention modifying the entity itself), it gives you two important advantages over the enhancement mechanism:
The same interface can be implemented by several entities (typically each having its own implementation class) as well as non-entity classes. Objects of all such classes can then be used interchangeably in contexts expecting the interface (you can create an array of entity instances of several entities and even gosu-only wrappers/temporary objects and present it comfortably in the UI).
You can leverage polymorphism. While enhancement functions can't be overridden, the interface implementations allow you full flexibility of polymorphic OOP. You can, for example, set up a default "do nothing" implementation on high level entity that you intend to use and then add more meaningful implementations for specific subtypes meant to really make use of the new functionality.
It does have some overhead and complicates things, however. As mentioned - Enhancements are typically simpler. In practice you should ask yourself whether the extra effort of creating and implementing the interface is worth it - in many cases even situations seemingly calling for polymorphism can be handled well enough by a simple switch typeof this in the enhancement to provide all the necessary type-based logic.
In personal experience I've used interfaces in quite a few situations, but Enhancements are my first choice in overwhelming majority of cases.
As a final note I'd like to mention a delegate entity. If what you want to add to some unrelated entities is not functionality but Properties with underlying database fields, creating a delegate entity and "implement" it with the desired standalone entities. A delegate entity does work a bit like an interface (you can use entity objects implementing the delegate interchangeably in situations where the delegate is expected) and you can set-up both interface implementation and enhancements on delegate level as well.
i am using jaxb to generate code from an xsd.
The generated code contains a lot of annotations; for classes and fields.
I am trying to use com.sun.tools.internal.xjc.Plugin to modify the generated code.
In the plugin run() method we are given an Outline class from which we can get ClassOutline. ClassOutline has an JDefinedClass final member which has the info about actual class which will be generated.
If i want to add anything, there are apis in JDefinedClass which can be used. But if i want to remove something, there is no way.
e.g. i cannot clear annotations, because the JDefinedClass.annotations() method returns an UnmodifiableCollection. so i cannot clear it or remove anything from it.
i tried to create another JDefinedClass by invoking the _class method but the ClassOutline.implClass variable is final, so i cannot set it.
how to get a JDefinedClass which does not have any annotations?
is there another phase of code generation which i can trap into to really control the generation of JDefinedClass?
The code model is, indeed mostly "write only". But, speaking of annotations, you have probably missed the methods like com.sun.codemodel.JDefinedClass.removeAnnotation(JAnnotationUse) and com.sun.codemodel.JMethod.removeAnnotation(JAnnotationUse) (implemented from com.sun.codemodel.JAnnotatable.removeAnnotation(JAnnotationUse)).
So they're there. You can remove annotations with the normal CodeModel API.
As I can see, you can also remove fields and methods from classes. So what exactly are you missing?
JDefinedClass.annotations() It return an unmodifiable collection object and you cannot modify them.
So work around for this, you can restrict annotation addition/deletion at class and field level before building JCodeModel.
You need to create a custom Jackson2Annotator class which extends Jackson2Annotator and override their methods according to your requirement.
Following are few methods which are being used for specific type of annotation property:
propertyOrder(OTB JsonPropertyOrder)
propertyInclusion(OTB JsonInclude)
propertyField(can be used for custom defined annotation at field level)
More you can discover by looking Jackson2Annotator class what fit into your need.
How can we really say "Here it is, the class I just developed is a helper!"
Would the class have some special criteria? I have a class in Java that exporta my JTables into CVS Files. Is it a helper? I also use a class to validate my forms. Is it a helper?
I hear this term often, but I realize that I don't really know what is it.
I don't think there is a 'textbook' definition of what a helper is, but I think most people would define a helper Class as one that makes no sense on its own - in other words, a Class whose whole purpose of existence it to 'help' make some operation on another class easier to do.
For example, if you create a class that follows the 'Adapter' pattern (i.e. it wraps an object of type 'foo' and lets it be used where normally you can only use type 'bar',) I think that adapter class could loosely be called a 'helper' class as well.
A helper class is a class that is used only by another class to complete a function. Thus, the helper has no right or need to be public, and is only created as being private.
For example, Private Class B helps public class A complete a set of tasks, A is calling on B and is of no use on its own.
For example (just a quick write-up, not tested)
private int newInt(String str)
{
test = Integer.parseInt(str);
return test;
}
and it could be called by:
public int transformation(String str)
{
return newInt(str);
}
This of course would be a class of its own, which would have to be called in your main class.
From some of the quick research I did, and my own personal experience when dealing with helper classes (.Net and Java), a helper class, is a class that provides functionality that is not actually relevant to the code one is developing, but rather provides some boilerplate work, such as casting, converting datatypes, or performing some common mathematical functions, for instance.
Such code can be generally reused in other projects, to further facilitate work being done.
Not everything helps should be a helper, a class wouldn't even exist if it didn't 'help' something. Usually helper classes offer shortcuts, like sql helpers. I think they should be something spesific and contain a group of relevant shortcut functions.
I think a "helper" class is a class which has been created only to support another classes on their functions.
There are a lot of cases where you need to create a "helper" class to put on it some methods that they do some functions. Some examples would be a class that have methods to calculate holidays on a year or transform some fields or formats in another.
Another example could be when you have to develop an app that it has a progress bar. You can create a "helper" class only for manage the progress bar (setting texts, calculating times, providing estimations...).
If you divide your app on layers (GUI, Business, DAO, etc.), it's interesting to have some "helper" or "utility" class (or classes) to do some tasks that you need to do but that they don't belong to GUI, business or DAO (Data Access Objects) layers explicitly. In this case, you could have an utility class for each layer and put inside the auxiliary methods that you need.
After through search i was unable to find any question which answers this, in my opinion fairly common design problem.
Given domain object:
public class Item {
private Long itemSN;
private String name;
methods, etc...
}
We need to store specific set of String properties which describes an item. It can be weight, color, sizes etc. System must be flexible and able to persist changeable list o properties. It needs to store allowed properties names, and preferably enforce some of them.
I tried several approaches, but concept of common constraints shared by all Item objects just don't fit in any standard domain model.
So i started to think about constraints as a form of configuration. Each Item has its's own properties (in simple String Map), constraints at the other hand are common configuration for all Items. So the next dilema emerged... how to express it without making big hole in domain model ?
It's easy to introduce additional application layer object to store constraints, but "allowed/required properites" are business affair, we need to allow domain user (manager of some sort) to change it, so its feels really horrible to draw this logic away from domain layer.
Any suggestions are welcome.
Edit 1.
After lot of brainstorming i managed to create valid object model for given situation. From first sight it was impossible to encapsulate properties with common constraints, but the latest out-of-domain implementation gave me an idea:
public class Item {
private Long itemSN;
private String name;
private List<Property> properties;
}
Core of the problem was solved here:
public class Property {
private Long propertyId;
private String propertyValue;
private Constraint constraint;
}
public class Constraint {
private String name;
private Boolean required;
private List<String> allowedValues;
}
So, each property have its value and constraint object which specifies name, allowed values and required status. This way constraint object can be shared by many properites, and any of this properties can have its own value.
It's adding some complexity to DB mapping and will hit performance but it's also keeping all domain logic in domain objects.
Any improvements, suggestions and opinions are welcome.
This problem can very reasonably be solved by the usage of annotations. Annotations allow you, the coder, to keep on using the language for the usage of properties by simply annotating your properties with constraints while still making it possible to apply the same constraints to user defined fields without the annotations.
JSR-349 is a Java standard for applying such constraints. Hibernate validator is a well known implementation.
Hey folks, hopefully a nice easy one here.
I'm generating classes with JAXB from a schema, and I'd like to be able to process them with a Visitor pattern.
To do that, I think I need every JAXB-generated class to implement the interface I've defined, and add a very simple method to them, so a simple example would be:
Default class:
public class MyClass {
private String name;
public void get/setName() {...}
}
Desired class:
public class MyClass implements MyVisitorNode {
private String name;
public void get/setName() {...}
public void accept(MyVisitorVisitor visitor) {
visitor.visit(this);
}
}
Is this possible, and if it is, what are the options? (Change the schema, runtime bytecode manipulation, manipulate the JAXBContext somehow...)
Ideally, without relying on vendor-specific extensions.
Thanks!
The xjc compiler for JAXB has a plugin interface that allows developers to create plugins that modify the generated code. My personal favorite is the fluent-api but there are others to add toString, equals, hashCode, etc.
I created a plugin using this technology to implement the visitor pattern and made it available as a google code project. It may not be exactly what you're looking for but it might be a good place to start to review the code and tests if you need to modify it to suit your needs.
http://code.google.com/p/jaxb-visitor/
The JAX-B generated classes are standard Java classes that you can customize in any way you desire, e.g., extend interface, add additional methods, etc..). The annotations on the class and attributes are the driving factor for the marshalling and unmarshalling process.
With that said, there are somethings you need to take into account if you customize the JAXB generated classes. As stated at the top of each class "Any modifications to this file will be lost upon recompilation of the source schema". In short, if you customize the class, you will need to manually make code changes to support any schema updates. If you do regenerated the classes, your custom code will be removed and you will have to start all over.