Is it possible to make a create which returns a boolean - eiffel

hi i dont know if i asked the question clearly.
i have a deferred class "animal" which contains two features : "bite" (this returns a boolean -> bite:BOOLEAN) and "speak"(speak(word:BOOLEAN)).
now i made a class named "dog" what inherit from "animal". i redefined the two features without a compiler error. now i want to make a create, which contains the function bite (create bite:BOOLEAN).
this gaves me a compiler error, if i try it with the other feature it works fine.
my error code : VGCP(2) creators part lists improper identifier.
thank u for ur help
My Application.e:
note
description : "root class of the application"
date : "$Date$"
revision : "$Revision$"
class
APPLICATION
inherit
ARGUMENTS_32
create
make
feature
d1:DOG
feature {NONE} -- Initialization
make
-- Run application.
do
print(d1.bite)
print ("Hello Eiffel World!%N")
end
end
my animal class:
deferred class
ANIMAL
feature
bite_:BOOLEAN
deferred
end
feature
speak(word:BOOLEAN)
deferred
end
end
my dog class:
class
DOG
inherit
ANIMAL
redefine
bite_,speak_
end
create
bite_
feature
bite_:BOOLEAN
do
Result:=5<3
end
feature
speak(word:BOOLEAN)
do
print("yes")
end

I'm not sure what is the intended semantics of feature speak, so I'll focus solely on feature bite, or, to express the supposed intention better can_bite. Class ANIMAL is similar to what you have:
deferred class
ANIMAL
feature -- Status report
can_bite: BOOLEAN
-- Can this animal bite?
deferred
end
end
With class DOG, two variations are possible: when every dog bites (possibly, depending on some internal state), when the ability to bite is set at object creation time.
In the first scenario, can_bite is a function and the class looks like
class
DOG
inherit
ANIMAL
feature -- Status report
can_bite: BOOLEAN
-- Can this animal bite?
do
Result := True -- It could also be some expression.
end
end
In the second scenario, can_bite is an attribute initialized by a creation procedure, and the class looks like
class
DOG
inherit
ANIMAL
create
make
feature {NONE} -- Creation
make (is_biting: BOOLEAN)
-- Initialize with ability `is_biting`.
do
can_bite := is_biting
end
feature -- Status report
can_bite: BOOLEAN
-- Can this animal bite?
end
Note that in both cases the client has to create the dog object before making any calls on it. In the first case, the default creation procedure is used, and the client code looks like
create d1
print (d1.can_bite)
In the second case, the specific creation procedure is used (it initializes can_bite), and the client code looks like
create d1.make (True)
print (d1.can_bite)

Related

What does the "self" keyword references in this Ruby case?

I would like some help understanding what does self refers to in this case. I understand that self refers to the class, module, etc that "owns" the code currently executing. In my example, my_each is an instance method for the Enumerable module. I'd like to know how does the self keyword works so that when I pass it to my example array it references it.
module Enumerable
def my_each
i = 0
while i < self.size
yield(self[i])
i += 1
end
self
end
end
[2,4,5].my_each { |i|
puts i
}
=> 2
=> 4
=> 5
What self refers to depends on the context. In your case, in an instance method, self refers to the object receiver of your instance method, so in your case the array [2, 4, 5].
But self can refer to other objects too. For example,
class Foo
puts self
end
prints Foo because in that context self refers to the class object. And that's why the two following definitions are the same thing
class Foo
def Foo.m
end
end
class Foo
def self.m
end
end
In Ruby it's all about self and every method is always executed against a particular self.
In your example instance method my_each self will refer to an instance which is using the method.
As you said self can also refer to a class, module..
It is a very powerfull ruby keyword since it can be used to create metaclasses.
If you are interested in understanding more I suggest you read chapter 5 in The Well Grounded Rubyist
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everywhere:
For instance variables: #myvar
For method and constant lookup
When defining methods, classes and modules.
Inside of an instance method
In the code below, reflect is an instance method. It belongs to the object we created via Event.new. So self points to that object.
class Event
def reflect
self
end
end
g = Event.new
g.reflect == g # => true
Inside of a class method
For this example, reflect is a class method of Ghost. With class methods, the class itself "owns" the method. self points to the class.
class Event
def self.reflect
self
end
end
Event.reflect == Event # => true
It works the same with "class" methods inside of modules. For example:
module Event
def self.reflect
self
end
end
Event.reflect == Event # => true
Remember, classes and modules are treated as objects in Ruby. So this behavior isn't that different from the instance method behavior we saw in the first example.
Inside of a class or module definition
One feature of Ruby that makes it such a good fit for frameworks like Rails is that you can execute arbitrary code inside class and module definitions. When you put code inside of a class/module definition, it runs just like any other Ruby code. The only real difference is the value of self.
As you can see below, self points to the class or module that's in the process of being defined.
class Event
self == Event # => true
end
module Join
self == Join # => true
end
Inside mixin methods
Mixed-in methods behave just like "normal" instance or class methods when it comes to self. This makes sense. Otherwise the mixin wouldn't be able to interact with the class you mixed it into.
Instance methods
Even though the reflect method as defined in the module, its self is the instance of the class it was mixed into.
module Reflection
def reflect
self
end
end
class Event
include Reflection
end
g = Event.new
g.reflect == g # => true
Class methods
When we extend a class to mix in class methods, self behaves exactly like it does in normal class methods.
module Reflection
def reflect
self
end
end
class Event
extend Reflection
end
Event.reflect == Event # => true
Inside the metaclass
Chances are you've seen this popular shortcut for defining lots of class methods at once.
class Event
class << self
def method1
end
def method2
end
end
end
The class << foo syntax is actually pretty interesting. It lets you access an object's metaclass - which is also called the "singleton class" or "eigenclass." I plan on covering metaclasses more deeply in a future post. But for now, you just need to know that the metaclass is where Ruby stores methods that are unique to a specific object.
If you access self from inside the class << foo block, you get the metaclass.
class << "test"
puts self.inspect
end
# => #<Class:#<String:0x007f8de283bd88>
Outside of any class
If you're running code outside of any class, Ruby still provides self. It points to "main", which is an instance of Object:
puts self.inspect # => main

Eiffel: change the signature of a inherited feature

How is the correct way to change the signature of a feature in Eiffel if any? if there is no option as I understood, how would be the correct way to define in a parent class that there will be a feature to be able to select but still don't know arguments number and types (types are resolvable with polymorphism...)
Is the only available playing with polymorphism having an argument into class a to select of type ANY?
class SELECTABLE
class SELECTABLE
select
deferred
end
end -- class
class DB_SERVICE
class DB_SERVICE
inherit
SELECTABLE
(...)
feature -- Status setting
select (a_db_connection: DB_CONNECTION)
local
l_qry: STRING
do
item := first_item_from_qry (l_qry)
end
end -- class
Having the following in class SELECTABLE is indeed a solution:
select (a: ANY)
deferred
end
Another solution is to use TUPLE:
select (a: TUPLE)
deferred
end
This allows you to have more than one argument in descendant classes:
select (a: TUPLE [db_connection: DB_CONNECTION])
do
a.db_connection.do_something
end
which can be called:
a_db_server.select (a_db_connection)
or:
select (a: TUPLE [db_connection: DB_CONNECTION; db_parameters: DB_PARAMETERS])
do
a.db_connection.do_something (a.db_parameters)
end
which can be called:
a_db_server.select (a_db_connection, a_dp_parameters)
Note that in that case, the need for the explicit tuple notation [...] in the argument of select is optional.
And of course, select is a keyword in Eiffel. You will have to use another name for your feature.

Eiffel: Creator instruction applies to target of a deferred type

Class A
deferred Class A
feature --
item: X -- X is deferred
set_item_for_some_reason (param: N)
do
create item.make_from_param (param)
end
end -- class
Class B
Class B inherit
A
feature --
item: Y -- Y not deferred inherits from X
end -- class
I'd like to create in the same class an attribute which will be defined in the descendent and get a Creator instruction applies to target of a deferred type Error which makes sens in a way of reduced context, but not in the context I intend it to do it.
For me it does make sense to be able to create an object in current deferred class, I wont have to implement in all the descendants! which will be a wrong design... something like this:
deferred Class A
feature --
item: X -- X is deferred
set_item_for_some_reason (param: N)
do
set_item_from_param (param)
end
set_item_from_param (param: N)
deferred
end
end -- class
Class B inherit
A
feature --
item: Y -- Y not deferred
set_item_from_param(param: N)
do
create item.make_from_param (param)
end
end -- class
Am I wrong with my design or is it a restriction which is still discussed about Eiffel compiler as I understood? and if yes, what would be the best practice workaround?
A possible solution is to use generic classes. In the class A, the formal generic parameter has a creation constraint that the corresponding actual generic parameter should have a particular creation procedure:
class A [G -> X create make_from_param end] feature
item: detachable G
set_item_for_some_reason (param: N)
do
create item.make_from_param (param)
end
end
A descendant class can specify an actual generic that has this creation procedure:
class B inherit
A [Y]
end
To make sure we are on the same page, here is the code of classes X and Y:
deferred class X feature
make_from_param (param: N)
deferred
end
end
class Y inherit
X
create
make_from_param
feature
make_from_param (param: N)
do
end
end
You can add as many such descendants as you wish. The main restriction is that whenever class A is used, its actual generic parameter should have the specified feature as a creation one. For example, it's OK to declare a type A [Y]. But A [X] would trigger an error.
If in a descendant, the type of item should not be fixed yet, it's possible to propagate it, repeating the constraint on the formal generic:
class C [G -> X create make_from_param end] inherit
A [G]
end

How to get Apex class that implements the Schedulable interface?

I have many classes that implement Schedulable Interface. I want to schdule multiple Apex classes at a time through an another apex class. So I need to query all the classes that are implement Schedulable interface.
I am using the following code snipet to achieve this, but I am getting a compiler error like below
ERROR:
"You must select an Apex class that implements the Schedulable interface. at line 127 column 13"
CODE:
list<ApexClass> listClasses;
String input='0 0 8 13 2 ?';
listClasses=[Select Id, Name,body from ApexClass]
for(ApexClass a:listClasses){
system.schedule(a.Name+' AutoScheduler', input, a);
}
Question:
How do I query all the apex class which implement schedulable interface? So that I can directly pass it to system.schedule() method.
DIFFERENT TRY:
When after getting this error I tried to query only one apex class(Known Class) which implements schedulable interface. Again no use. Please see the below snipet for the different try
CODE:
list<ApexClass> listClasses;
String input='0 0 8 13 2 ?';
//Retriving only one class of Name='SchedularTest'
listClasses=[Select Id, Name,body from ApexClass where Name ='SchedularTest']
for(ApexClass a:listClasses){
system.schedule(a.Name+' AutoScheduler', input, a);
}
ERROR:
"You must select an Apex class that implements the Schedulable interface. at line 127 column 13"
Thanks in advance
Satheeskumar
I'd say the error message is quite clear?
The last parameter you're passing to System.schedule has to be a new object. New instance of the class. What you're passing is the metadata information about the class, it's body etc... This stuff can't be "run" like that.
I'm going to bet that system.schedule('SchedulerTest AutoScheduler', input, new SchedulerTest()); will work OK? If it doesn't - make sure the class compiles OK and maybe also whether it is marked as valid.
See? how do you expect something that represents a row in the database / file on disk to "work" like an object of the class?
If you need to create a new object of given class having only this class' name - you might want to check Type methods.
String className = 'SchedulerTest';
Type t = Type.forName(className);
System.schedule(className, '0 0 8 13 2 ?', (Schedulable)t.newInstance());
This makes a new object (it's actually a generic Object) and then you cast it to something that's acceptable for the method. You'll get a runtime failure if the class doesn't implement the interface:
System.TypeException: Invalid conversion from runtime type
SchedulerTest to system.Schedulable

Design decision: (VB.NET) Should I create a class or module to easily connect to one of many databases?

Basically, we have three databases to grab data from. One is a SQL Server database, one is an Access database (which is particularly annoying to connect to because we have to map a network drive and such), and the final one will be an Oracle database when IT finally gives us rights.
I'm thinking about creating a helper function that makes querying any one of these databases as easy as possible. Ideally, I want to create a two-dimensional array
Dim myEasyResultArray(10,10) as String
myEasyResultArray = DatabaseHelper("Access", "SELECT * FROM Employee")
Is this a good design decision? Also, how can I have the array be the right size? Can I just do this?
Dim myEasyResultArray = DatabaseHelper("Access", "SELECT * FROM Employee")
Should this be a module or a class? I don't really need to share variables,
I would try to put all my data access logic into a data access layer. Ideally this would be in a separate library and namespace, but it doesn't have to be. I would use classes, typically one per table/entity and design all the classes to be stateless (so you don't have to ever reuse the same instance of the data access object, you can just instantiate a new one any time you need to access the DB).
Instead of having it return arrays, I would have it return data objects (often called DTO's - data transfer objects). I would keep the DTO classes as clean as possible containing only public properties and no methods, if possible. The data access classes should all implement interfaces so that multiple versions of each one can be created. One for Access, one for Oracle, one for SQL, etc. Then, wherever I needed to access the database (hopefully only in my business layer, not ever in my UI layer), I would request the appropriate data access objects by their "generic" interface type (thereby requiring a factory class to inject the correct concrete data access object type into my business object).
Here's a real simple example of a DTO:
Public Class Employee
Public Id As Guid
Public Name As String
Public StartDate As Date
End Class
Here's an example Data Access interface
Public Interface IEmployeeDataAccess
Function GetEmployee(id As Guid) As Employee
Function GetEmployees() As List(Of Employee)
End Interface
Here's an example of an data access class:
Public Class SqlEmployeeDataAccess
Inherits IEmployeeDataAccess
Public Function GetEmployee(id As Guid) As Employee Implements IEmployeeDataAccess.GetEmployee
Dim employee As New Employee()
' Connect to SQL DB and populate employee DTO object
Return employee
End Function
Public Function GetEmployees() As List(Of Employee) Implements IEmployeeDataAccess.GetEmployees
Dim employees As New List(Of Employee)()
' Connect to SQL DB and populate list of employee DTO objects
Return employees
End Function
End Interface
You might then make similar classes called AccessEmployeeDataAccess and OracleEmployeeDataAccess which also implement the IEmployeeDataAccess interface. Then, also in the data access layer, I would create a factory class for each supported DB provider. I would make all the DataAccess factories implement the same interface, like this:
Public Interface IDataAccessFactory
Function NewEmployeeDataAccess() As IEmployeeDataAccess
End Interface
Public Class SqlDataAccessFactory
Implements IDataAccessFactory
Public Function NewEmployeeDataAccess() As IEmployeeDataAccess
Return New SqlEmployeeDataAccess()
End Function
End Class
Then, in my business class, I might do something like this:
Public Class EmployeeBusiness
Public Sub New(employeeDataAccess As IEmployeeDataAcess)
_employeeDataAccess = employeeDataAccess
End Sub
Private _employeeDataAccess As IEmployeeDataAcess
Public Function GetEmployee(id As Guid) As Employee
Return _employeeDataAccess.GetEmployee(id)
End Function
End Class
And then in my business factory, I'd do something like this:
Public Class BusinessFactory
Public Sub New()
Select Case dataAccessType
Case "SQL"
_dataAccessFactory = New SqlDataAccessFactory()
Case "Oracle"
_dataAccessFactory = New OracleDataAccessFactory()
Case "Access"
_dataAccessFactory = New AccessDataAccessFactory()
End Select
End Sub
_dataAccessFactory As IDataAccessFactory
Public Function NewEmployeeBusiness() As IEmployeeBusiness
Return New EmployeeBusiness(_dataAccessFactory.NewEmployeeDataAccess())
End Function
End Class
This could be simplified a great deal by having a single set of data access objects that work with any database provider. To do that, you'd need to use only base ADO types like IDbConnection instead of SqlConnection, and IDbCommand instead of SqlCommand. Then your data access objects could ask for a DB Provider factory which could create a new connection, etc., whenever the DataAccess class needs one. This, however, is easier to do when you are simply calling stored procedures, or something. Often, especially when you are dynamically building your SQL sentences in code, there are too many differences between providers so you can't just use the same DataAccess class for all DB providers.
But, that's just me...
I see one big issue with your proposal.
The first is that I often see programmers want to build a database help with methods that resemble this form:
DataTable GetData(string sql)
The important point here is that the method accepts an sql string, with no provision for query parameters. This is wrong. It is an anti-pattern, because it encourages you (pretty much forces you) to encode sql data as part of the query code. You must provide some mechanism for the correct passing of query parameters as separate data. Arrays are common, but that's not the only way. I also normally do not even provide an overload that accepts only the string, as it inevitably leads to abuse. If you want to send a query with no parameter, then pass an empty array. This way it is clear that is what you intend, and anyone who uses your database helper will be encouraged to learn to use parameters the right way.
There are other things that could be improved as well, but this to my mind is the main issue.

Resources