In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were
private to the instance and not the
class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
public class Example {
private int a;
public int getOtherA(Example other) {
return other.a;
}
}
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful.
If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
Here's the equivalent of Michael Borgwardt's answer for when you are not able to access the private fields of the other object:
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return other.valueEquals(this.value); // <------------
}
#Override // This method would probably also be declared in an interface
public boolean valueEquals(int oValue) {
return this.value == oValue;
}
}
Nowadays this is familiar to Ruby programmers but I have been doing this in Java for a while. I prefer not to rely on access to another object's private fields. Remember that the other object may belong to a subclass, which could store the value in a different object field, or in a file or database etc.
Example code (Java):
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return this.value == other.value; // <------------
}
}
If the assumption "private member variables are private to the instance" were correct, the marked line would cause a compiler error, because the other.value field is private and part of a different object than the one whose equals() method is being called.
But since in Java (and most other languages that have the visibility concept) private visibility is per-class, access to the field is allowed to all code of the MutableInteger, irrelevant of what instance was used to invoke it.
Related
I have some code that generates answers based on the user input. But in somecases i need to update the values later by calling SetAnswers But when i compile my code i get the following error:
NullReferenceException: Object reference not set to an instance of an object
I get this error on the line marked by the arrow.
See below for my code:
public class Generate_Questions : MonoBehaviour{
public Question q5, q4;
void Start(){
q4 = create_question("Select object to edit", EXTERNAL);
Visual_Question vq1 = new Visual_Question(1, q4, new vector(1,1,1), Ui, Canvas);
vq1.draw_question();
}
void Update(){
}
public class Visual_Question : Generate_Questions{
public Visual_Question(int order_id, Question q, Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas){
}
public void draw_question(){
q4.SetAnswers(new Answer[]{ <--------- this generates the error.
new Answer(null, "Select an option")
});
}
}
public class Question{
public string text;
public int answers_loc;
public List<Answer> answers;
public Question(string q_text, int answers_loc){
answers = new List<Answer>();
this.text = q_text;
this.answers_loc = answers_loc;
}
public void SetAnswers(Answer[] c_answers){
foreach(Answer answer in c_answers){
this.answers.Add(answer);
}
}
public bool CheckIfAnswersAvailable(){
if(answers.Count > 0){
return true;
}else{
return false;
}
}
public int QuestionLocation(){
return answers_loc;
}
}
public Question create_question(string text, int a_type){
Question Q = new Question(text, a_type);
return Q;
}
public interface IAnswer{
string GetText();
string GetDataType();
object GetValue();
Question GetNextQuestion();
}
public class Answer : IAnswer{
public string text;
public Question next = null;
public int? action = null;
public Element obj = null;
public string property = null;
public float? value = null;
public Answer(Question next, string text){
this.text = text;
this.next = next;
}
public Answer(Question next, string text, Element obj, int? action){
this.action = action;
this.text = text;
this.next = next;
this.obj = obj;
}
public Answer(Question next, string text, Element obj, int? action, string property, float? value){
this.action = action;
this.next = next;
this.text = text;
this.obj = obj;
this.property = property;
this.value = value;
}
public string GetText(){
return text;
}
public string GetDataType(){
throw new System.NotImplementedException();
}
public object GetValue(){
return value;
}
public Question GetNextQuestion(){
return next;
}
}
}
how would i go about fixing this problem? I am a complete newbie to c#. So my question may be already answered but i just dont know what i am looking for.
I assume that IAnswer[] is an interface and since you are trying to initialize an abstract object you get that runtime exception
NullReferenceException: Object reference not set to an instance of an object
if you want to create instance of IAnswer object you have to restructure it like class or structure.
Your class Visual_Question derives from Generate_Questions, so the member q4 that you use en draw_question is not initialized. This is not the member of Generated_Questions but a member of Visual_Question that is not initialized.
In Generate_Questions you are creating a new instance of Visual_Question and then immediately calling draw_question on that new instance. You now have 2 instances of a question (both derive from Generate_Questions), but only one of them has had the Start method, which initializes q4 called. If, however, you attempt to call Start from your second instance, you're going to find yourself in an infinite series of recursive calls and quickly crash with a different error (a stack overflow in this case).
One issue with the current code is that Generate_Questions sounds more like an action than a class. I'd suggest removing the inheritance from Visual_Question and make that an interface that you would implement on Question. Question should probably have the create_question method removed. That probably belongs in a MonoBehavior script (technically it's a factory method -- look up the factory pattern -- I'm not going to go into it here since this is a beginner topic).
Something like (obviously not complete):
public class Generate_Questions : MonoBehaviour
{
private IVisualQuestion q4;
void Start()
{
q4 = new Question("Select object to edit", EXTERNAL);
q4.DrawQuestion(new vector(1,1,1), Ui, Canvas)
}
void Update() {}
}
public interface IVisualQuestion
{
void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas);
}
public class Question : IVisualQuestion
{
// ... insert the Question constructor and code here ...
// Implement VisualQuestion interface
public void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas)
{
this.SetAnswers(new Answer[]{new Answer(null, "Select an option")});
}
}
In general, you probably don't need inheritance. As you learn more C#, you'll discover that when inheritance is going to help it will be clear. More often than not, using an interface is a far better and flexible approach. As a commenter noted, you probably don't want to inherit from MonoBehavior. You really only need that for classes that the Unity Engine is going to directly handle.
Another note: the convention in C# is to name methods, variables, etc. in PascalCase, not using underscores to separate words.
Class that i want to mock:
TestClass.java
public class testClass(){
public String getDescription(String input){
String value = this.getDetails(input); // i am not going to change this line, hence want to mock this.
//below this i have some complexity logic, which i would like to fix cyclomatic complexity issue
}
private String getDetails(String input){
return "More details for the "+input;
}
}
My questions is how do i mock "this.getDetails(input)" to return some string for testing purpose?
If you've got a class that is big and complex enough that you need to mock a small piece of it, take that as a hint that you're violating the Single Responsibility Principle and properly split up the classes. If you use dependency injection, you can then supply whatever implementation you'd like.
public class TestClass {
/**
* Computes a detail string based on an input. Supply this in the constructor
* for full DI, relax visibility, or add a setter.
*/
private final Function<String, String> detailFunction;
public String getDescription(String input){
String value = detailFunction.apply(input);
// ...
}
}
As a lightweight alternative, you can test an override or spy of your actual class.
#Test public void testTestClassWithOverride() {
TestClass instanceUnderTest = new TestClass() {
#Override public String getDescription(String input) {
return "Predictable value";
}
};
// test your instanceUnderTest here
}
#Test public void testTestClassWithSpy() {
TestClass spyUnderTest = Mockito.spy(new TestClass());
doReturn("Predictable value").when(spyUnderTest).getDescription(anyString());
// test your spyUnderTest here
}
Bear in mind that, though this is an option for you, it shouldn't be your first option: Rather than testing your actual class, you're testing a one-off variant of it, and you've made it so other consumers can subclass your TestClass as well. If possible, write the flexibility you need into the class itself and treat your test as a consumer that plays by the same rules.
First of all, it is a bad practice to make a so-called "partials mocks". This illustrates that your code doesn't follow single responsibility principle that leads to your code being not (or hardly) testable.
I would suggest you to extract getDescription method from your class and use it indirectly via dependency inversion or more concrete - dependency injection (for instance by employing Spring Framework):
public class TestClass() {
private DetailsServiceProvider detailsServiceProvider;
public TestClass(DetailsServiceProvider detailsServiceProvider) {
this.detailsServiceProvider = detailsServiceProvider;
}
public String getDescription(String input) {
String value = detailsServiceProvider.getDetails(input); // i am not going to change this line, hence want to mock this.
//below this i have some complexity logic, which i would like to fix cyclomatic complexity issue
}
}
public interface DetailsServiceProvider {
String getDetails(String input);
}
public class DetailsServiceProviderImpl implements DetailsServiceProvider{
#Override
public String getDetails(String input) {
return "More details for the "+input;
}
}
Then in your test, you could simply:
#Test
public void test() {
DetailsServiceProvider mockedProvider = Mockito.mock(DetailsServiceProvider.class);
//TODO: add scenarios for the mocked object
TestClass target = new TestClass(mockedProvider);
String description = target.getDescription();
//TODO: add assertions
}
If you do not want to struggle with the preferred approach you could use #Spy in Mockito. This will create exactly what you want - a partial mock for your object where part of the methods will be real and another part - mocks:
#Test
public void test() {
TestClass partialMockedObject = Mockito.spy(new TestClass());
Mockito.doReturn("test details").when(partialMockedObject).getDetails();
String description = partialMockedObject.getDescription();
//TODO: add assertions
}
Again, this method is not desired but can be used if no other options are given. Note that this requires getDetails() to be visible in tests, meaning that the private modifier won't work here.
At any point of time i will be setting only one setter method but the JsonProperty name should be same for both . when i am compiling this i am getting an exception. How to set the same name for both .?
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
Jackson tends to favor common scenarios and good design choices for annotation support.
Your case represents a very uncommon scenario. You have one field having two different meanings in different contexts. Typically this would not be a favourable data format since it adds messy logic to the consumer on the other end...they need to divine what the "Json" property should mean in each case. It would be cleaner for the consumer if you just used two different property names. Then it would be sufficient to simply check for the presence of each property to know which alternative it's getting.
Your Java class also seems poorly designed. Classes should not have this type of context or modes, where in one context a field is allowed, but in another context it's not.
Since this is primarily a smell with your design, and not serialization logic, the best approach would probably be to correct your Java class hierarchy:
class BaseClass {
}
class SubClassWithItems {
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
}
class SubClassWithType {
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
}
That way your class does not have a different set of fields based on some runtime state. If runtime state is driving what fields your class contains, you're not much better off than with just a Map.
If you can't change that, you're left with custom serialization.
I've inherited a system that uses the Castle Windsor IRepository pattern to abstract away from the DAL which is LinqToSQL.
The main problem that I can see, is that IRepository only implements IEnumerable. So even the simplest of queries have to load ALL the data from the datatable, to return a single object.
Current usage is as follows
using (IUnitOfWork context2 = IocServiceFactory.Resolve<IUnitOfWork>())
{
KpiFormDocumentEntry entry = context2.GetRepository<KpiFormDocumentEntry>().FindById(id, KpiFormDocumentEntry.LoadOptions.FormItem);
And this uses lambda to filter, like so
public static KpiFormDocumentEntry FindById(this IRepository<KpiFormDocumentEntry> source, int id, KpiFormDocumentEntry.LoadOptions loadOptions)
{
return source.Where( qi => qi.Id == id ).LoadWith( loadOptions ).FirstOrDefault();
}
So it becomes a nice extension method.
My Question is, how can I use this same Interface/pattern etc. but also implement IQueryable to properly support LinqToSQL and get some serious performance improvements?
The current implementation/Interfaces for IRepository are as follows
public interface IRepository<T> : IEnumerable<T> where T : class
{
void Add(T entity);
void AddMany(IEnumerable<T> entities);
void Delete(T entity);
void DeleteMany(IEnumerable<T> entities);
IEnumerable<T> All();
IEnumerable<T> Find(Func<T, bool> predicate);
T FindFirst(Func<T, bool> predicate);
}
and then this is implemented by an SqlClientRepository like so
public sealed class SqlClientRepository<T> : IRepository<T> where T : class
{
private readonly Table<T> _source;
internal SqlClientRepository(Table<T> source)
{
if( source == null ) throw new ArgumentNullException( "source", Gratte.Aurora.SHlib.labelText("All_TableIsNull",1) );
_source = source;
}
//removed add delete etc
public IEnumerable<T> All()
{
return _source;
}
public IEnumerator<T> GetEnumerator()
{
return _source.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
The problem at the moment is, in our example above, the .Where is calling 'GetEnumerator', which then loads all rows into memory, and then looks for the one we need.
If I change IRepository to implement IQueryable, I can't implement the three methods needed, as these are not public in the Table class.
I think I should change the SQLClientRepository to be defined like so
public sealed class SqlClientRepository<T> : IQueryable<T>, IRepository<T> where T : class
And then implement the necessary methods, but I can't figure out how to pass the expressions around etc. as they are private members of the Table class, like so
public override Type ElementType
{
get { return _source.ElementType; } //Won't work as ElementType is private
}
public override Expression Expression
{
get { return _source.Expression; } //Won't work as Expression is private
}
public override IQueryProvider Provider
{
get { return _source.Provider; } //Won't work as Provider is private
}
Any help really appreciated to move this from 'iterate through every row in the database after loading it' to 'select x where id=1'!
If you want to expose linq you can stop using the repository pattern and use Linq2Sql directly. The reason to this is that every Linq To Sql provider has it's own custom solutions. So if you expose LINQ you get a leaky abstraction. There is no point in using an abstraction layer then.
Instead of exposing LINQ you got two options:
Implement the specification pattern
Use the repository pattern as I describe here: http://blog.gauffin.org/2013/01/repository-pattern-done-right/
So, while it may not be a true abstraction any longer, the main point was to get the benefit of linq to sql without updating all the queries already written.
so, I made the IRepository implement IQueryable instead of IEnumerable.
then in the SqlClientRepository implementation, I can call AsQueryable() to cast the Table to IQueryable, and then all is good, like so.
Now everywhere somebody has written IRepository().Where(qi => qi.id = id) or similar, it actually passes the ID to sql server and only pulls back one record, instead of all of them, and loops through looking for the correct one.
/// <summary>Provides the ability to query and access entities within a SQL Server data store.</summary>
/// <typeparam name="T">The type of entity in the repository.</typeparam>
public sealed class SqlClientRepository<T> : IRepository<T> where T : class
{
private readonly Table<T> _source;
private readonly IQueryable<T> _sourceQuery;
IQueryable<T> Query()
{
return (IQueryable<T>)_source;
}
public Type ElementType
{
get { return _sourceQuery.GetType(); }
}
public Expression Expression
{
get { return _sourceQuery.Expression; }
}
public IQueryProvider Provider
{
get { return _sourceQuery.Provider; }
}
/// <summary>Initializes a new instance of the <see cref="SqlClientRepository{T}"/> class.</summary>
/// <param name="source">A <see cref="Table{T}"/> to a collection representing the entities from a SQL Server data store.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is a <c>null</c> reference (<c>Nothing</c> in Visual Basic).</exception>
internal SqlClientRepository(Table<T> source)
{
if( source == null ) throw new ArgumentNullException( "source", "All_TableIsNull" ) );
_source = source;
_sourceQuery = _source.AsQueryable();
}
A predicate (an object that is a boolean-valued function which tests its input for a condition) is generally assumed to be stateless.
What's the most appropriate name for an object which has a testing function with state?
e.g. in Java, the CountTrigger class below returns true only on the Nth time it is tested against a value that matches a desired value, and false otherwise.
interface QuasiPredicate<T> // what should this be renamed to?
{
public boolean test(T value);
}
class CountTrigger<T> implements QuasiPredicate<T>
{
// for simplicity, ignore synchronization + null-value issues
private int remainingTriggers = 0;
final private T testValue;
public CountTrigger(T testValue, int count)
{
this.remainingTriggers = count;
this.testValue = testValue;
}
#Override public boolean test(T value)
{
if (!this.testValue.equals(value))
return false;
if (this.remainingTriggers == 0)
return false;
if (--this.remainingTriggers == 0)
return true;
}
}
Considering it's an interface and interfaces are implemented and not extended then I don't see the problem in your object implementing a predicate.
If you're going to put public CountTrigger(T testValue, int count) in the interface as well then maybe you need a different name. Perhaps IFiniteRule or another suitable synonym. Maybe ask at https://english.stackexchange.com/ ;-)